slnodejs 6.1.625 → 6.1.627

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ContextAPI=void 0;const NoopContextManager_1=require("../context/NoopContextManager");const global_utils_1=require("../internal/global-utils");const diag_1=require("./diag");const API_NAME="context";const NOOP_CONTEXT_MANAGER=new NoopContextManager_1.NoopContextManager;class ContextAPI{constructor(){}static getInstance(){if(!this._instance){this._instance=new ContextAPI}return this._instance}setGlobalContextManager(contextManager){return(0,global_utils_1.registerGlobal)(API_NAME,contextManager,diag_1.DiagAPI.instance())}active(){return this._getContextManager().active()}with(context,fn,thisArg,...args){return this._getContextManager().with(context,fn,thisArg,...args)}bind(context,target){return this._getContextManager().bind(context,target)}_getContextManager(){return(0,global_utils_1.getGlobal)(API_NAME)||NOOP_CONTEXT_MANAGER}disable(){this._getContextManager().disable();(0,global_utils_1.unregisterGlobal)(API_NAME,diag_1.DiagAPI.instance())}}exports.ContextAPI=ContextAPI},{"../context/NoopContextManager":11,"../internal/global-utils":19,"./diag":2}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiagAPI=void 0;const ComponentLogger_1=require("../diag/ComponentLogger");const logLevelLogger_1=require("../diag/internal/logLevelLogger");const types_1=require("../diag/types");const global_utils_1=require("../internal/global-utils");const API_NAME="diag";class DiagAPI{constructor(){function _logProxy(funcName){return function(...args){const logger=(0,global_utils_1.getGlobal)("diag");if(!logger)return;return logger[funcName](...args)}}const self=this;const setLogger=(logger,optionsOrLogLevel={logLevel:types_1.DiagLogLevel.INFO})=>{var _a,_b,_c;if(logger===self){const err=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");self.error((_a=err.stack)!==null&&_a!==void 0?_a:err.message);return false}if(typeof optionsOrLogLevel==="number"){optionsOrLogLevel={logLevel:optionsOrLogLevel}}const oldLogger=(0,global_utils_1.getGlobal)("diag");const newLogger=(0,logLevelLogger_1.createLogLevelDiagLogger)((_b=optionsOrLogLevel.logLevel)!==null&&_b!==void 0?_b:types_1.DiagLogLevel.INFO,logger);if(oldLogger&&!optionsOrLogLevel.suppressOverrideMessage){const stack=(_c=(new Error).stack)!==null&&_c!==void 0?_c:"<failed to generate stacktrace>";oldLogger.warn(`Current logger will be overwritten from ${stack}`);newLogger.warn(`Current logger will overwrite one already registered from ${stack}`)}return(0,global_utils_1.registerGlobal)("diag",newLogger,self,true)};self.setLogger=setLogger;self.disable=()=>{(0,global_utils_1.unregisterGlobal)(API_NAME,self)};self.createComponentLogger=options=>{return new ComponentLogger_1.DiagComponentLogger(options)};self.verbose=_logProxy("verbose");self.debug=_logProxy("debug");self.info=_logProxy("info");self.warn=_logProxy("warn");self.error=_logProxy("error")}static instance(){if(!this._instance){this._instance=new DiagAPI}return this._instance}}exports.DiagAPI=DiagAPI},{"../diag/ComponentLogger":14,"../diag/internal/logLevelLogger":16,"../diag/types":17,"../internal/global-utils":19}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MetricsAPI=void 0;const NoopMeterProvider_1=require("../metrics/NoopMeterProvider");const global_utils_1=require("../internal/global-utils");const diag_1=require("./diag");const API_NAME="metrics";class MetricsAPI{constructor(){}static getInstance(){if(!this._instance){this._instance=new MetricsAPI}return this._instance}setGlobalMeterProvider(provider){return(0,global_utils_1.registerGlobal)(API_NAME,provider,diag_1.DiagAPI.instance())}getMeterProvider(){return(0,global_utils_1.getGlobal)(API_NAME)||NoopMeterProvider_1.NOOP_METER_PROVIDER}getMeter(name,version,options){return this.getMeterProvider().getMeter(name,version,options)}disable(){(0,global_utils_1.unregisterGlobal)(API_NAME,diag_1.DiagAPI.instance())}}exports.MetricsAPI=MetricsAPI},{"../internal/global-utils":19,"../metrics/NoopMeterProvider":24,"./diag":2}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PropagationAPI=void 0;const global_utils_1=require("../internal/global-utils");const NoopTextMapPropagator_1=require("../propagation/NoopTextMapPropagator");const TextMapPropagator_1=require("../propagation/TextMapPropagator");const context_helpers_1=require("../baggage/context-helpers");const utils_1=require("../baggage/utils");const diag_1=require("./diag");const API_NAME="propagation";const NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator_1.NoopTextMapPropagator;class PropagationAPI{constructor(){this.createBaggage=utils_1.createBaggage;this.getBaggage=context_helpers_1.getBaggage;this.getActiveBaggage=context_helpers_1.getActiveBaggage;this.setBaggage=context_helpers_1.setBaggage;this.deleteBaggage=context_helpers_1.deleteBaggage}static getInstance(){if(!this._instance){this._instance=new PropagationAPI}return this._instance}setGlobalPropagator(propagator){return(0,global_utils_1.registerGlobal)(API_NAME,propagator,diag_1.DiagAPI.instance())}inject(context,carrier,setter=TextMapPropagator_1.defaultTextMapSetter){return this._getGlobalPropagator().inject(context,carrier,setter)}extract(context,carrier,getter=TextMapPropagator_1.defaultTextMapGetter){return this._getGlobalPropagator().extract(context,carrier,getter)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,global_utils_1.unregisterGlobal)(API_NAME,diag_1.DiagAPI.instance())}_getGlobalPropagator(){return(0,global_utils_1.getGlobal)(API_NAME)||NOOP_TEXT_MAP_PROPAGATOR}}exports.PropagationAPI=PropagationAPI},{"../baggage/context-helpers":6,"../baggage/utils":9,"../internal/global-utils":19,"../propagation/NoopTextMapPropagator":28,"../propagation/TextMapPropagator":29,"./diag":2}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceAPI=void 0;const global_utils_1=require("../internal/global-utils");const ProxyTracerProvider_1=require("../trace/ProxyTracerProvider");const spancontext_utils_1=require("../trace/spancontext-utils");const context_utils_1=require("../trace/context-utils");const diag_1=require("./diag");const API_NAME="trace";class TraceAPI{constructor(){this._proxyTracerProvider=new ProxyTracerProvider_1.ProxyTracerProvider;this.wrapSpanContext=spancontext_utils_1.wrapSpanContext;this.isSpanContextValid=spancontext_utils_1.isSpanContextValid;this.deleteSpan=context_utils_1.deleteSpan;this.getSpan=context_utils_1.getSpan;this.getActiveSpan=context_utils_1.getActiveSpan;this.getSpanContext=context_utils_1.getSpanContext;this.setSpan=context_utils_1.setSpan;this.setSpanContext=context_utils_1.setSpanContext}static getInstance(){if(!this._instance){this._instance=new TraceAPI}return this._instance}setGlobalTracerProvider(provider){const success=(0,global_utils_1.registerGlobal)(API_NAME,this._proxyTracerProvider,diag_1.DiagAPI.instance());if(success){this._proxyTracerProvider.setDelegate(provider)}return success}getTracerProvider(){return(0,global_utils_1.getGlobal)(API_NAME)||this._proxyTracerProvider}getTracer(name,version){return this.getTracerProvider().getTracer(name,version)}disable(){(0,global_utils_1.unregisterGlobal)(API_NAME,diag_1.DiagAPI.instance());this._proxyTracerProvider=new ProxyTracerProvider_1.ProxyTracerProvider}}exports.TraceAPI=TraceAPI},{"../internal/global-utils":19,"../trace/ProxyTracerProvider":35,"../trace/context-utils":37,"../trace/spancontext-utils":43,"./diag":2}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deleteBaggage=exports.setBaggage=exports.getActiveBaggage=exports.getBaggage=void 0;const context_1=require("../api/context");const context_2=require("../context/context");const BAGGAGE_KEY=(0,context_2.createContextKey)("OpenTelemetry Baggage Key");function getBaggage(context){return context.getValue(BAGGAGE_KEY)||undefined}exports.getBaggage=getBaggage;function getActiveBaggage(){return getBaggage(context_1.ContextAPI.getInstance().active())}exports.getActiveBaggage=getActiveBaggage;function setBaggage(context,baggage){return context.setValue(BAGGAGE_KEY,baggage)}exports.setBaggage=setBaggage;function deleteBaggage(context){return context.deleteValue(BAGGAGE_KEY)}exports.deleteBaggage=deleteBaggage},{"../api/context":1,"../context/context":12}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaggageImpl=void 0;class BaggageImpl{constructor(entries){this._entries=entries?new Map(entries):new Map}getEntry(key){const entry=this._entries.get(key);if(!entry){return undefined}return Object.assign({},entry)}getAllEntries(){return Array.from(this._entries.entries()).map(([k,v])=>[k,v])}setEntry(key,entry){const newBaggage=new BaggageImpl(this._entries);newBaggage._entries.set(key,entry);return newBaggage}removeEntry(key){const newBaggage=new BaggageImpl(this._entries);newBaggage._entries.delete(key);return newBaggage}removeEntries(...keys){const newBaggage=new BaggageImpl(this._entries);for(const key of keys){newBaggage._entries.delete(key)}return newBaggage}clear(){return new BaggageImpl}}exports.BaggageImpl=BaggageImpl},{}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.baggageEntryMetadataSymbol=void 0;exports.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.baggageEntryMetadataFromString=exports.createBaggage=void 0;const diag_1=require("../api/diag");const baggage_impl_1=require("./internal/baggage-impl");const symbol_1=require("./internal/symbol");const diag=diag_1.DiagAPI.instance();function createBaggage(entries={}){return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)))}exports.createBaggage=createBaggage;function baggageEntryMetadataFromString(str){if(typeof str!=="string"){diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);str=""}return{__TYPE__:symbol_1.baggageEntryMetadataSymbol,toString(){return str}}}exports.baggageEntryMetadataFromString=baggageEntryMetadataFromString},{"../api/diag":2,"./internal/baggage-impl":7,"./internal/symbol":8}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.context=void 0;const context_1=require("./api/context");exports.context=context_1.ContextAPI.getInstance()},{"./api/context":1}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopContextManager=void 0;const context_1=require("./context");class NoopContextManager{active(){return context_1.ROOT_CONTEXT}with(_context,fn,thisArg,...args){return fn.call(thisArg,...args)}bind(_context,target){return target}enable(){return this}disable(){return this}}exports.NoopContextManager=NoopContextManager},{"./context":12}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ROOT_CONTEXT=exports.createContextKey=void 0;function createContextKey(description){return Symbol.for(description)}exports.createContextKey=createContextKey;class BaseContext{constructor(parentContext){const self=this;self._currentContext=parentContext?new Map(parentContext):new Map;self.getValue=key=>self._currentContext.get(key);self.setValue=(key,value)=>{const context=new BaseContext(self._currentContext);context._currentContext.set(key,value);return context};self.deleteValue=key=>{const context=new BaseContext(self._currentContext);context._currentContext.delete(key);return context}}}exports.ROOT_CONTEXT=new BaseContext},{}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.diag=void 0;const diag_1=require("./api/diag");exports.diag=diag_1.DiagAPI.instance()},{"./api/diag":2}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiagComponentLogger=void 0;const global_utils_1=require("../internal/global-utils");class DiagComponentLogger{constructor(props){this._namespace=props.namespace||"DiagComponentLogger"}debug(...args){return logProxy("debug",this._namespace,args)}error(...args){return logProxy("error",this._namespace,args)}info(...args){return logProxy("info",this._namespace,args)}warn(...args){return logProxy("warn",this._namespace,args)}verbose(...args){return logProxy("verbose",this._namespace,args)}}exports.DiagComponentLogger=DiagComponentLogger;function logProxy(funcName,namespace,args){const logger=(0,global_utils_1.getGlobal)("diag");if(!logger){return}args.unshift(namespace);return logger[funcName](...args)}},{"../internal/global-utils":19}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiagConsoleLogger=void 0;const consoleMap=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class DiagConsoleLogger{constructor(){function _consoleFunc(funcName){return function(...args){if(console){let theFunc=console[funcName];if(typeof theFunc!=="function"){theFunc=console.log}if(typeof theFunc==="function"){return theFunc.apply(console,args)}}}}for(let i=0;i<consoleMap.length;i++){this[consoleMap[i].n]=_consoleFunc(consoleMap[i].c)}}}exports.DiagConsoleLogger=DiagConsoleLogger},{}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createLogLevelDiagLogger=void 0;const types_1=require("../types");function createLogLevelDiagLogger(maxLevel,logger){if(maxLevel<types_1.DiagLogLevel.NONE){maxLevel=types_1.DiagLogLevel.NONE}else if(maxLevel>types_1.DiagLogLevel.ALL){maxLevel=types_1.DiagLogLevel.ALL}logger=logger||{};function _filterFunc(funcName,theLevel){const theFunc=logger[funcName];if(typeof theFunc==="function"&&maxLevel>=theLevel){return theFunc.bind(logger)}return function(){}}return{error:_filterFunc("error",types_1.DiagLogLevel.ERROR),warn:_filterFunc("warn",types_1.DiagLogLevel.WARN),info:_filterFunc("info",types_1.DiagLogLevel.INFO),debug:_filterFunc("debug",types_1.DiagLogLevel.DEBUG),verbose:_filterFunc("verbose",types_1.DiagLogLevel.VERBOSE)}}exports.createLogLevelDiagLogger=createLogLevelDiagLogger},{"../types":17}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DiagLogLevel=void 0;var DiagLogLevel;(function(DiagLogLevel){DiagLogLevel[DiagLogLevel["NONE"]=0]="NONE";DiagLogLevel[DiagLogLevel["ERROR"]=30]="ERROR";DiagLogLevel[DiagLogLevel["WARN"]=50]="WARN";DiagLogLevel[DiagLogLevel["INFO"]=60]="INFO";DiagLogLevel[DiagLogLevel["DEBUG"]=70]="DEBUG";DiagLogLevel[DiagLogLevel["VERBOSE"]=80]="VERBOSE";DiagLogLevel[DiagLogLevel["ALL"]=9999]="ALL"})(DiagLogLevel=exports.DiagLogLevel||(exports.DiagLogLevel={}))},{}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.trace=exports.propagation=exports.metrics=exports.diag=exports.context=exports.INVALID_SPAN_CONTEXT=exports.INVALID_TRACEID=exports.INVALID_SPANID=exports.isValidSpanId=exports.isValidTraceId=exports.isSpanContextValid=exports.createTraceState=exports.TraceFlags=exports.SpanStatusCode=exports.SpanKind=exports.SamplingDecision=exports.ProxyTracerProvider=exports.ProxyTracer=exports.defaultTextMapSetter=exports.defaultTextMapGetter=exports.ValueType=exports.createNoopMeter=exports.DiagLogLevel=exports.DiagConsoleLogger=exports.ROOT_CONTEXT=exports.createContextKey=exports.baggageEntryMetadataFromString=void 0;var utils_1=require("./baggage/utils");Object.defineProperty(exports,"baggageEntryMetadataFromString",{enumerable:true,get:function(){return utils_1.baggageEntryMetadataFromString}});var context_1=require("./context/context");Object.defineProperty(exports,"createContextKey",{enumerable:true,get:function(){return context_1.createContextKey}});Object.defineProperty(exports,"ROOT_CONTEXT",{enumerable:true,get:function(){return context_1.ROOT_CONTEXT}});var consoleLogger_1=require("./diag/consoleLogger");Object.defineProperty(exports,"DiagConsoleLogger",{enumerable:true,get:function(){return consoleLogger_1.DiagConsoleLogger}});var types_1=require("./diag/types");Object.defineProperty(exports,"DiagLogLevel",{enumerable:true,get:function(){return types_1.DiagLogLevel}});var NoopMeter_1=require("./metrics/NoopMeter");Object.defineProperty(exports,"createNoopMeter",{enumerable:true,get:function(){return NoopMeter_1.createNoopMeter}});var Metric_1=require("./metrics/Metric");Object.defineProperty(exports,"ValueType",{enumerable:true,get:function(){return Metric_1.ValueType}});var TextMapPropagator_1=require("./propagation/TextMapPropagator");Object.defineProperty(exports,"defaultTextMapGetter",{enumerable:true,get:function(){return TextMapPropagator_1.defaultTextMapGetter}});Object.defineProperty(exports,"defaultTextMapSetter",{enumerable:true,get:function(){return TextMapPropagator_1.defaultTextMapSetter}});var ProxyTracer_1=require("./trace/ProxyTracer");Object.defineProperty(exports,"ProxyTracer",{enumerable:true,get:function(){return ProxyTracer_1.ProxyTracer}});var ProxyTracerProvider_1=require("./trace/ProxyTracerProvider");Object.defineProperty(exports,"ProxyTracerProvider",{enumerable:true,get:function(){return ProxyTracerProvider_1.ProxyTracerProvider}});var SamplingResult_1=require("./trace/SamplingResult");Object.defineProperty(exports,"SamplingDecision",{enumerable:true,get:function(){return SamplingResult_1.SamplingDecision}});var span_kind_1=require("./trace/span_kind");Object.defineProperty(exports,"SpanKind",{enumerable:true,get:function(){return span_kind_1.SpanKind}});var status_1=require("./trace/status");Object.defineProperty(exports,"SpanStatusCode",{enumerable:true,get:function(){return status_1.SpanStatusCode}});var trace_flags_1=require("./trace/trace_flags");Object.defineProperty(exports,"TraceFlags",{enumerable:true,get:function(){return trace_flags_1.TraceFlags}});var utils_2=require("./trace/internal/utils");Object.defineProperty(exports,"createTraceState",{enumerable:true,get:function(){return utils_2.createTraceState}});var spancontext_utils_1=require("./trace/spancontext-utils");Object.defineProperty(exports,"isSpanContextValid",{enumerable:true,get:function(){return spancontext_utils_1.isSpanContextValid}});Object.defineProperty(exports,"isValidTraceId",{enumerable:true,get:function(){return spancontext_utils_1.isValidTraceId}});Object.defineProperty(exports,"isValidSpanId",{enumerable:true,get:function(){return spancontext_utils_1.isValidSpanId}});var invalid_span_constants_1=require("./trace/invalid-span-constants");Object.defineProperty(exports,"INVALID_SPANID",{enumerable:true,get:function(){return invalid_span_constants_1.INVALID_SPANID}});Object.defineProperty(exports,"INVALID_TRACEID",{enumerable:true,get:function(){return invalid_span_constants_1.INVALID_TRACEID}});Object.defineProperty(exports,"INVALID_SPAN_CONTEXT",{enumerable:true,get:function(){return invalid_span_constants_1.INVALID_SPAN_CONTEXT}});const context_api_1=require("./context-api");Object.defineProperty(exports,"context",{enumerable:true,get:function(){return context_api_1.context}});const diag_api_1=require("./diag-api");Object.defineProperty(exports,"diag",{enumerable:true,get:function(){return diag_api_1.diag}});const metrics_api_1=require("./metrics-api");Object.defineProperty(exports,"metrics",{enumerable:true,get:function(){return metrics_api_1.metrics}});const propagation_api_1=require("./propagation-api");Object.defineProperty(exports,"propagation",{enumerable:true,get:function(){return propagation_api_1.propagation}});const trace_api_1=require("./trace-api");Object.defineProperty(exports,"trace",{enumerable:true,get:function(){return trace_api_1.trace}});exports.default={context:context_api_1.context,diag:diag_api_1.diag,metrics:metrics_api_1.metrics,propagation:propagation_api_1.propagation,trace:trace_api_1.trace}},{"./baggage/utils":9,"./context-api":10,"./context/context":12,"./diag-api":13,"./diag/consoleLogger":15,"./diag/types":17,"./metrics-api":21,"./metrics/Metric":22,"./metrics/NoopMeter":23,"./propagation-api":27,"./propagation/TextMapPropagator":29,"./trace-api":30,"./trace/ProxyTracer":34,"./trace/ProxyTracerProvider":35,"./trace/SamplingResult":36,"./trace/internal/utils":40,"./trace/invalid-span-constants":41,"./trace/span_kind":42,"./trace/spancontext-utils":43,"./trace/status":44,"./trace/trace_flags":45}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.unregisterGlobal=exports.getGlobal=exports.registerGlobal=void 0;const platform_1=require("../platform");const version_1=require("../version");const semver_1=require("./semver");const major=version_1.VERSION.split(".")[0];const GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for(`opentelemetry.js.api.${major}`);const _global=platform_1._globalThis;function registerGlobal(type,instance,diag,allowOverride=false){var _a;const api=_global[GLOBAL_OPENTELEMETRY_API_KEY]=(_a=_global[GLOBAL_OPENTELEMETRY_API_KEY])!==null&&_a!==void 0?_a:{version:version_1.VERSION};if(!allowOverride&&api[type]){const err=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);diag.error(err.stack||err.message);return false}if(api.version!==version_1.VERSION){const err=new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);diag.error(err.stack||err.message);return false}api[type]=instance;diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);return true}exports.registerGlobal=registerGlobal;function getGlobal(type){var _a,_b;const globalVersion=(_a=_global[GLOBAL_OPENTELEMETRY_API_KEY])===null||_a===void 0?void 0:_a.version;if(!globalVersion||!(0,semver_1.isCompatible)(globalVersion)){return}return(_b=_global[GLOBAL_OPENTELEMETRY_API_KEY])===null||_b===void 0?void 0:_b[type]}exports.getGlobal=getGlobal;function unregisterGlobal(type,diag){diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);const api=_global[GLOBAL_OPENTELEMETRY_API_KEY];if(api){delete api[type]}}exports.unregisterGlobal=unregisterGlobal},{"../platform":26,"../version":46,"./semver":20}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isCompatible=exports._makeCompatibilityCheck=void 0;const version_1=require("../version");const re=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(ownVersion){const acceptedVersions=new Set([ownVersion]);const rejectedVersions=new Set;const myVersionMatch=ownVersion.match(re);if(!myVersionMatch){return()=>false}const ownVersionParsed={major:+myVersionMatch[1],minor:+myVersionMatch[2],patch:+myVersionMatch[3],prerelease:myVersionMatch[4]};if(ownVersionParsed.prerelease!=null){return function isExactmatch(globalVersion){return globalVersion===ownVersion}}function _reject(v){rejectedVersions.add(v);return false}function _accept(v){acceptedVersions.add(v);return true}return function isCompatible(globalVersion){if(acceptedVersions.has(globalVersion)){return true}if(rejectedVersions.has(globalVersion)){return false}const globalVersionMatch=globalVersion.match(re);if(!globalVersionMatch){return _reject(globalVersion)}const globalVersionParsed={major:+globalVersionMatch[1],minor:+globalVersionMatch[2],patch:+globalVersionMatch[3],prerelease:globalVersionMatch[4]};if(globalVersionParsed.prerelease!=null){return _reject(globalVersion)}if(ownVersionParsed.major!==globalVersionParsed.major){return _reject(globalVersion)}if(ownVersionParsed.major===0){if(ownVersionParsed.minor===globalVersionParsed.minor&&ownVersionParsed.patch<=globalVersionParsed.patch){return _accept(globalVersion)}return _reject(globalVersion)}if(ownVersionParsed.minor<=globalVersionParsed.minor){return _accept(globalVersion)}return _reject(globalVersion)}}exports._makeCompatibilityCheck=_makeCompatibilityCheck;exports.isCompatible=_makeCompatibilityCheck(version_1.VERSION)},{"../version":46}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.metrics=void 0;const metrics_1=require("./api/metrics");exports.metrics=metrics_1.MetricsAPI.getInstance()},{"./api/metrics":3}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ValueType=void 0;var ValueType;(function(ValueType){ValueType[ValueType["INT"]=0]="INT";ValueType[ValueType["DOUBLE"]=1]="DOUBLE"})(ValueType=exports.ValueType||(exports.ValueType={}))},{}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createNoopMeter=exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=exports.NOOP_OBSERVABLE_GAUGE_METRIC=exports.NOOP_OBSERVABLE_COUNTER_METRIC=exports.NOOP_UP_DOWN_COUNTER_METRIC=exports.NOOP_HISTOGRAM_METRIC=exports.NOOP_COUNTER_METRIC=exports.NOOP_METER=exports.NoopObservableUpDownCounterMetric=exports.NoopObservableGaugeMetric=exports.NoopObservableCounterMetric=exports.NoopObservableMetric=exports.NoopHistogramMetric=exports.NoopUpDownCounterMetric=exports.NoopCounterMetric=exports.NoopMetric=exports.NoopMeter=void 0;class NoopMeter{constructor(){}createHistogram(_name,_options){return exports.NOOP_HISTOGRAM_METRIC}createCounter(_name,_options){return exports.NOOP_COUNTER_METRIC}createUpDownCounter(_name,_options){return exports.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(_name,_options){return exports.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(_name,_options){return exports.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(_name,_options){return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(_callback,_observables){}removeBatchObservableCallback(_callback){}}exports.NoopMeter=NoopMeter;class NoopMetric{}exports.NoopMetric=NoopMetric;class NoopCounterMetric extends NoopMetric{add(_value,_attributes){}}exports.NoopCounterMetric=NoopCounterMetric;class NoopUpDownCounterMetric extends NoopMetric{add(_value,_attributes){}}exports.NoopUpDownCounterMetric=NoopUpDownCounterMetric;class NoopHistogramMetric extends NoopMetric{record(_value,_attributes){}}exports.NoopHistogramMetric=NoopHistogramMetric;class NoopObservableMetric{addCallback(_callback){}removeCallback(_callback){}}exports.NoopObservableMetric=NoopObservableMetric;class NoopObservableCounterMetric extends NoopObservableMetric{}exports.NoopObservableCounterMetric=NoopObservableCounterMetric;class NoopObservableGaugeMetric extends NoopObservableMetric{}exports.NoopObservableGaugeMetric=NoopObservableGaugeMetric;class NoopObservableUpDownCounterMetric extends NoopObservableMetric{}exports.NoopObservableUpDownCounterMetric=NoopObservableUpDownCounterMetric;exports.NOOP_METER=new NoopMeter;exports.NOOP_COUNTER_METRIC=new NoopCounterMetric;exports.NOOP_HISTOGRAM_METRIC=new NoopHistogramMetric;exports.NOOP_UP_DOWN_COUNTER_METRIC=new NoopUpDownCounterMetric;exports.NOOP_OBSERVABLE_COUNTER_METRIC=new NoopObservableCounterMetric;exports.NOOP_OBSERVABLE_GAUGE_METRIC=new NoopObservableGaugeMetric;exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new NoopObservableUpDownCounterMetric;function createNoopMeter(){return exports.NOOP_METER}exports.createNoopMeter=createNoopMeter},{}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NOOP_METER_PROVIDER=exports.NoopMeterProvider=void 0;const NoopMeter_1=require("./NoopMeter");class NoopMeterProvider{getMeter(_name,_version,_options){return NoopMeter_1.NOOP_METER}}exports.NoopMeterProvider=NoopMeterProvider;exports.NOOP_METER_PROVIDER=new NoopMeterProvider},{"./NoopMeter":23}],25:[function(require,module,exports){(function(global){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports._globalThis=void 0;exports._globalThis=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],26:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./globalThis"),exports)},{"./globalThis":25}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.propagation=void 0;const propagation_1=require("./api/propagation");exports.propagation=propagation_1.PropagationAPI.getInstance()},{"./api/propagation":4}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopTextMapPropagator=void 0;class NoopTextMapPropagator{inject(_context,_carrier){}extract(context,_carrier){return context}fields(){return[]}}exports.NoopTextMapPropagator=NoopTextMapPropagator},{}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.defaultTextMapSetter=exports.defaultTextMapGetter=void 0;exports.defaultTextMapGetter={get(carrier,key){if(carrier==null){return undefined}return carrier[key]},keys(carrier){if(carrier==null){return[]}return Object.keys(carrier)}};exports.defaultTextMapSetter={set(carrier,key,value){if(carrier==null){return}carrier[key]=value}}},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.trace=void 0;const trace_1=require("./api/trace");exports.trace=trace_1.TraceAPI.getInstance()},{"./api/trace":5}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NonRecordingSpan=void 0;const invalid_span_constants_1=require("./invalid-span-constants");class NonRecordingSpan{constructor(_spanContext=invalid_span_constants_1.INVALID_SPAN_CONTEXT){this._spanContext=_spanContext}spanContext(){return this._spanContext}setAttribute(_key,_value){return this}setAttributes(_attributes){return this}addEvent(_name,_attributes){return this}setStatus(_status){return this}updateName(_name){return this}end(_endTime){}isRecording(){return false}recordException(_exception,_time){}}exports.NonRecordingSpan=NonRecordingSpan},{"./invalid-span-constants":41}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopTracer=void 0;const context_1=require("../api/context");const context_utils_1=require("../trace/context-utils");const NonRecordingSpan_1=require("./NonRecordingSpan");const spancontext_utils_1=require("./spancontext-utils");const contextApi=context_1.ContextAPI.getInstance();class NoopTracer{startSpan(name,options,context=contextApi.active()){const root=Boolean(options===null||options===void 0?void 0:options.root);if(root){return new NonRecordingSpan_1.NonRecordingSpan}const parentFromContext=context&&(0,context_utils_1.getSpanContext)(context);if(isSpanContext(parentFromContext)&&(0,spancontext_utils_1.isSpanContextValid)(parentFromContext)){return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext)}else{return new NonRecordingSpan_1.NonRecordingSpan}}startActiveSpan(name,arg2,arg3,arg4){let opts;let ctx;let fn;if(arguments.length<2){return}else if(arguments.length===2){fn=arg2}else if(arguments.length===3){opts=arg2;fn=arg3}else{opts=arg2;ctx=arg3;fn=arg4}const parentContext=ctx!==null&&ctx!==void 0?ctx:contextApi.active();const span=this.startSpan(name,opts,parentContext);const contextWithSpanSet=(0,context_utils_1.setSpan)(parentContext,span);return contextApi.with(contextWithSpanSet,fn,undefined,span)}}exports.NoopTracer=NoopTracer;function isSpanContext(spanContext){return typeof spanContext==="object"&&typeof spanContext["spanId"]==="string"&&typeof spanContext["traceId"]==="string"&&typeof spanContext["traceFlags"]==="number"}},{"../api/context":1,"../trace/context-utils":37,"./NonRecordingSpan":31,"./spancontext-utils":43}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopTracerProvider=void 0;const NoopTracer_1=require("./NoopTracer");class NoopTracerProvider{getTracer(_name,_version,_options){return new NoopTracer_1.NoopTracer}}exports.NoopTracerProvider=NoopTracerProvider},{"./NoopTracer":32}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ProxyTracer=void 0;const NoopTracer_1=require("./NoopTracer");const NOOP_TRACER=new NoopTracer_1.NoopTracer;class ProxyTracer{constructor(_provider,name,version,options){this._provider=_provider;this.name=name;this.version=version;this.options=options}startSpan(name,options,context){return this._getTracer().startSpan(name,options,context)}startActiveSpan(_name,_options,_context,_fn){const tracer=this._getTracer();return Reflect.apply(tracer.startActiveSpan,tracer,arguments)}_getTracer(){if(this._delegate){return this._delegate}const tracer=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!tracer){return NOOP_TRACER}this._delegate=tracer;return this._delegate}}exports.ProxyTracer=ProxyTracer},{"./NoopTracer":32}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ProxyTracerProvider=void 0;const ProxyTracer_1=require("./ProxyTracer");const NoopTracerProvider_1=require("./NoopTracerProvider");const NOOP_TRACER_PROVIDER=new NoopTracerProvider_1.NoopTracerProvider;class ProxyTracerProvider{getTracer(name,version,options){var _a;return(_a=this.getDelegateTracer(name,version,options))!==null&&_a!==void 0?_a:new ProxyTracer_1.ProxyTracer(this,name,version,options)}getDelegate(){var _a;return(_a=this._delegate)!==null&&_a!==void 0?_a:NOOP_TRACER_PROVIDER}setDelegate(delegate){this._delegate=delegate}getDelegateTracer(name,version,options){var _a;return(_a=this._delegate)===null||_a===void 0?void 0:_a.getTracer(name,version,options)}}exports.ProxyTracerProvider=ProxyTracerProvider},{"./NoopTracerProvider":33,"./ProxyTracer":34}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SamplingDecision=void 0;var SamplingDecision;(function(SamplingDecision){SamplingDecision[SamplingDecision["NOT_RECORD"]=0]="NOT_RECORD";SamplingDecision[SamplingDecision["RECORD"]=1]="RECORD";SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(SamplingDecision=exports.SamplingDecision||(exports.SamplingDecision={}))},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSpanContext=exports.setSpanContext=exports.deleteSpan=exports.setSpan=exports.getActiveSpan=exports.getSpan=void 0;const context_1=require("../context/context");const NonRecordingSpan_1=require("./NonRecordingSpan");const context_2=require("../api/context");const SPAN_KEY=(0,context_1.createContextKey)("OpenTelemetry Context Key SPAN");function getSpan(context){return context.getValue(SPAN_KEY)||undefined}exports.getSpan=getSpan;function getActiveSpan(){return getSpan(context_2.ContextAPI.getInstance().active())}exports.getActiveSpan=getActiveSpan;function setSpan(context,span){return context.setValue(SPAN_KEY,span)}exports.setSpan=setSpan;function deleteSpan(context){return context.deleteValue(SPAN_KEY)}exports.deleteSpan=deleteSpan;function setSpanContext(context,spanContext){return setSpan(context,new NonRecordingSpan_1.NonRecordingSpan(spanContext))}exports.setSpanContext=setSpanContext;function getSpanContext(context){var _a;return(_a=getSpan(context))===null||_a===void 0?void 0:_a.spanContext()}exports.getSpanContext=getSpanContext},{"../api/context":1,"../context/context":12,"./NonRecordingSpan":31}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceStateImpl=void 0;const tracestate_validators_1=require("./tracestate-validators");const MAX_TRACE_STATE_ITEMS=32;const MAX_TRACE_STATE_LEN=512;const LIST_MEMBERS_SEPARATOR=",";const LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceStateImpl{constructor(rawTraceState){this._internalState=new Map;if(rawTraceState)this._parse(rawTraceState)}set(key,value){const traceState=this._clone();if(traceState._internalState.has(key)){traceState._internalState.delete(key)}traceState._internalState.set(key,value);return traceState}unset(key){const traceState=this._clone();traceState._internalState.delete(key);return traceState}get(key){return this._internalState.get(key)}serialize(){return this._keys().reduce((agg,key)=>{agg.push(key+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(key));return agg},[]).join(LIST_MEMBERS_SEPARATOR)}_parse(rawTraceState){if(rawTraceState.length>MAX_TRACE_STATE_LEN)return;this._internalState=rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg,part)=>{const listMember=part.trim();const i=listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(i!==-1){const key=listMember.slice(0,i);const value=listMember.slice(i+1,part.length);if((0,tracestate_validators_1.validateKey)(key)&&(0,tracestate_validators_1.validateValue)(value)){agg.set(key,value)}else{}}return agg},new Map);if(this._internalState.size>MAX_TRACE_STATE_ITEMS){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const traceState=new TraceStateImpl;traceState._internalState=new Map(this._internalState);return traceState}}exports.TraceStateImpl=TraceStateImpl},{"./tracestate-validators":39}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateValue=exports.validateKey=void 0;const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]";const VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;const VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;const VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);const VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/;const INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(key){return VALID_KEY_REGEX.test(key)}exports.validateKey=validateKey;function validateValue(value){return VALID_VALUE_BASE_REGEX.test(value)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)}exports.validateValue=validateValue},{}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createTraceState=void 0;const tracestate_impl_1=require("./tracestate-impl");function createTraceState(rawTraceState){return new tracestate_impl_1.TraceStateImpl(rawTraceState)}exports.createTraceState=createTraceState},{"./tracestate-impl":38}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.INVALID_SPAN_CONTEXT=exports.INVALID_TRACEID=exports.INVALID_SPANID=void 0;const trace_flags_1=require("./trace_flags");exports.INVALID_SPANID="0000000000000000";exports.INVALID_TRACEID="00000000000000000000000000000000";exports.INVALID_SPAN_CONTEXT={traceId:exports.INVALID_TRACEID,spanId:exports.INVALID_SPANID,traceFlags:trace_flags_1.TraceFlags.NONE}},{"./trace_flags":45}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SpanKind=void 0;var SpanKind;(function(SpanKind){SpanKind[SpanKind["INTERNAL"]=0]="INTERNAL";SpanKind[SpanKind["SERVER"]=1]="SERVER";SpanKind[SpanKind["CLIENT"]=2]="CLIENT";SpanKind[SpanKind["PRODUCER"]=3]="PRODUCER";SpanKind[SpanKind["CONSUMER"]=4]="CONSUMER"})(SpanKind=exports.SpanKind||(exports.SpanKind={}))},{}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.wrapSpanContext=exports.isSpanContextValid=exports.isValidSpanId=exports.isValidTraceId=void 0;const invalid_span_constants_1=require("./invalid-span-constants");const NonRecordingSpan_1=require("./NonRecordingSpan");const VALID_TRACEID_REGEX=/^([0-9a-f]{32})$/i;const VALID_SPANID_REGEX=/^[0-9a-f]{16}$/i;function isValidTraceId(traceId){return VALID_TRACEID_REGEX.test(traceId)&&traceId!==invalid_span_constants_1.INVALID_TRACEID}exports.isValidTraceId=isValidTraceId;function isValidSpanId(spanId){return VALID_SPANID_REGEX.test(spanId)&&spanId!==invalid_span_constants_1.INVALID_SPANID}exports.isValidSpanId=isValidSpanId;function isSpanContextValid(spanContext){return isValidTraceId(spanContext.traceId)&&isValidSpanId(spanContext.spanId)}exports.isSpanContextValid=isSpanContextValid;function wrapSpanContext(spanContext){return new NonRecordingSpan_1.NonRecordingSpan(spanContext)}exports.wrapSpanContext=wrapSpanContext},{"./NonRecordingSpan":31,"./invalid-span-constants":41}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SpanStatusCode=void 0;var SpanStatusCode;(function(SpanStatusCode){SpanStatusCode[SpanStatusCode["UNSET"]=0]="UNSET";SpanStatusCode[SpanStatusCode["OK"]=1]="OK";SpanStatusCode[SpanStatusCode["ERROR"]=2]="ERROR"})(SpanStatusCode=exports.SpanStatusCode||(exports.SpanStatusCode={}))},{}],45:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceFlags=void 0;var TraceFlags;(function(TraceFlags){TraceFlags[TraceFlags["NONE"]=0]="NONE";TraceFlags[TraceFlags["SAMPLED"]=1]="SAMPLED"})(TraceFlags=exports.TraceFlags||(exports.TraceFlags={}))},{}],46:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VERSION=void 0;exports.VERSION="1.7.0"},{}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExportResultCode=void 0;var ExportResultCode;(function(ExportResultCode){ExportResultCode[ExportResultCode["SUCCESS"]=0]="SUCCESS";ExportResultCode[ExportResultCode["FAILED"]=1]="FAILED"})(ExportResultCode=exports.ExportResultCode||(exports.ExportResultCode={}))},{}],48:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BAGGAGE_MAX_TOTAL_LENGTH=exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=exports.BAGGAGE_MAX_NAME_VALUE_PAIRS=exports.BAGGAGE_HEADER=exports.BAGGAGE_ITEMS_SEPARATOR=exports.BAGGAGE_PROPERTIES_SEPARATOR=exports.BAGGAGE_KEY_PAIR_SEPARATOR=void 0;exports.BAGGAGE_KEY_PAIR_SEPARATOR="=";exports.BAGGAGE_PROPERTIES_SEPARATOR=";";exports.BAGGAGE_ITEMS_SEPARATOR=",";exports.BAGGAGE_HEADER="baggage";exports.BAGGAGE_MAX_NAME_VALUE_PAIRS=180;exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096;exports.BAGGAGE_MAX_TOTAL_LENGTH=8192},{}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.W3CBaggagePropagator=void 0;const api_1=require("@opentelemetry/api");const suppress_tracing_1=require("../../trace/suppress-tracing");const constants_1=require("../constants");const utils_1=require("../utils");class W3CBaggagePropagator{inject(context,carrier,setter){const baggage=api_1.propagation.getBaggage(context);if(!baggage||(0,suppress_tracing_1.isTracingSuppressed)(context))return;const keyPairs=(0,utils_1.getKeyPairs)(baggage).filter(pair=>{return pair.length<=constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS}).slice(0,constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS);const headerValue=(0,utils_1.serializeKeyPairs)(keyPairs);if(headerValue.length>0){setter.set(carrier,constants_1.BAGGAGE_HEADER,headerValue)}}extract(context,carrier,getter){const headerValue=getter.get(carrier,constants_1.BAGGAGE_HEADER);const baggageString=Array.isArray(headerValue)?headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR):headerValue;if(!baggageString)return context;const baggage={};if(baggageString.length===0){return context}const pairs=baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);pairs.forEach(entry=>{const keyPair=(0,utils_1.parsePairKeyValue)(entry);if(keyPair){const baggageEntry={value:keyPair.value};if(keyPair.metadata){baggageEntry.metadata=keyPair.metadata}baggage[keyPair.key]=baggageEntry}});if(Object.entries(baggage).length===0){return context}return api_1.propagation.setBaggage(context,api_1.propagation.createBaggage(baggage))}fields(){return[constants_1.BAGGAGE_HEADER]}}exports.W3CBaggagePropagator=W3CBaggagePropagator},{"../../trace/suppress-tracing":77,"../constants":48,"../utils":50,"@opentelemetry/api":18}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parseKeyPairsIntoRecord=exports.parsePairKeyValue=exports.getKeyPairs=exports.serializeKeyPairs=void 0;const api_1=require("@opentelemetry/api");const constants_1=require("./constants");function serializeKeyPairs(keyPairs){return keyPairs.reduce((hValue,current)=>{const value=`${hValue}${hValue!==""?constants_1.BAGGAGE_ITEMS_SEPARATOR:""}${current}`;return value.length>constants_1.BAGGAGE_MAX_TOTAL_LENGTH?hValue:value},"")}exports.serializeKeyPairs=serializeKeyPairs;function getKeyPairs(baggage){return baggage.getAllEntries().map(([key,value])=>{let entry=`${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;if(value.metadata!==undefined){entry+=constants_1.BAGGAGE_PROPERTIES_SEPARATOR+value.metadata.toString()}return entry})}exports.getKeyPairs=getKeyPairs;function parsePairKeyValue(entry){const valueProps=entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR);if(valueProps.length<=0)return;const keyPairPart=valueProps.shift();if(!keyPairPart)return;const keyPair=keyPairPart.split(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR);if(keyPair.length!==2)return;const key=decodeURIComponent(keyPair[0].trim());const value=decodeURIComponent(keyPair[1].trim());let metadata;if(valueProps.length>0){metadata=(0,api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR))}return{key:key,value:value,metadata:metadata}}exports.parsePairKeyValue=parsePairKeyValue;function parseKeyPairsIntoRecord(value){if(typeof value!=="string"||value.length===0)return{};return value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).map(entry=>{return parsePairKeyValue(entry)}).filter(keyPair=>keyPair!==undefined&&keyPair.value.length>0).reduce((headers,keyPair)=>{headers[keyPair.key]=keyPair.value;return headers},{})}exports.parseKeyPairsIntoRecord=parseKeyPairsIntoRecord},{"./constants":48,"@opentelemetry/api":18}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AnchoredClock=void 0;class AnchoredClock{constructor(systemClock,monotonicClock){this._monotonicClock=monotonicClock;this._epochMillis=systemClock.now();this._performanceMillis=monotonicClock.now()}now(){const delta=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+delta}}exports.AnchoredClock=AnchoredClock},{}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isAttributeValue=exports.isAttributeKey=exports.sanitizeAttributes=void 0;const api_1=require("@opentelemetry/api");function sanitizeAttributes(attributes){const out={};if(typeof attributes!=="object"||attributes==null){return out}for(const[key,val]of Object.entries(attributes)){if(!isAttributeKey(key)){api_1.diag.warn(`Invalid attribute key: ${key}`);continue}if(!isAttributeValue(val)){api_1.diag.warn(`Invalid attribute value set for key: ${key}`);continue}if(Array.isArray(val)){out[key]=val.slice()}else{out[key]=val}}return out}exports.sanitizeAttributes=sanitizeAttributes;function isAttributeKey(key){return typeof key==="string"&&key.length>0}exports.isAttributeKey=isAttributeKey;function isAttributeValue(val){if(val==null){return true}if(Array.isArray(val)){return isHomogeneousAttributeValueArray(val)}return isValidPrimitiveAttributeValue(val)}exports.isAttributeValue=isAttributeValue;function isHomogeneousAttributeValueArray(arr){let type;for(const element of arr){if(element==null)continue;if(!type){if(isValidPrimitiveAttributeValue(element)){type=typeof element;continue}return false}if(typeof element===type){continue}return false}return true}function isValidPrimitiveAttributeValue(val){switch(typeof val){case"number":case"boolean":case"string":return true}return false}},{"@opentelemetry/api":18}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.globalErrorHandler=exports.setGlobalErrorHandler=void 0;const logging_error_handler_1=require("./logging-error-handler");let delegateHandler=(0,logging_error_handler_1.loggingErrorHandler)();function setGlobalErrorHandler(handler){delegateHandler=handler}exports.setGlobalErrorHandler=setGlobalErrorHandler;function globalErrorHandler(ex){try{delegateHandler(ex)}catch(_a){}}exports.globalErrorHandler=globalErrorHandler},{"./logging-error-handler":54}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.loggingErrorHandler=void 0;const api_1=require("@opentelemetry/api");function loggingErrorHandler(){return ex=>{api_1.diag.error(stringifyException(ex))}}exports.loggingErrorHandler=loggingErrorHandler;function stringifyException(ex){if(typeof ex==="string"){return ex}else{return JSON.stringify(flattenException(ex))}}function flattenException(ex){const result={};let current=ex;while(current!==null){Object.getOwnPropertyNames(current).forEach(propertyName=>{if(result[propertyName])return;const value=current[propertyName];if(value){result[propertyName]=String(value)}});current=Object.getPrototypeOf(current)}return result}},{"@opentelemetry/api":18}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isTimeInput=exports.isTimeInputHrTime=exports.hrTimeToMicroseconds=exports.hrTimeToMilliseconds=exports.hrTimeToNanoseconds=exports.hrTimeToTimeStamp=exports.hrTimeDuration=exports.timeInputToHrTime=exports.hrTime=void 0;const platform_1=require("../platform");const NANOSECOND_DIGITS=9;const SECOND_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS);function numberToHrtime(epochMillis){const epochSeconds=epochMillis/1e3;const seconds=Math.trunc(epochSeconds);const nanos=Number((epochSeconds-seconds).toFixed(NANOSECOND_DIGITS))*SECOND_TO_NANOSECONDS;return[seconds,nanos]}function getTimeOrigin(){let timeOrigin=platform_1.otperformance.timeOrigin;if(typeof timeOrigin!=="number"){const perf=platform_1.otperformance;timeOrigin=perf.timing&&perf.timing.fetchStart}return timeOrigin}function hrTime(performanceNow){const timeOrigin=numberToHrtime(getTimeOrigin());const now=numberToHrtime(typeof performanceNow==="number"?performanceNow:platform_1.otperformance.now());let seconds=timeOrigin[0]+now[0];let nanos=timeOrigin[1]+now[1];if(nanos>SECOND_TO_NANOSECONDS){nanos-=SECOND_TO_NANOSECONDS;seconds+=1}return[seconds,nanos]}exports.hrTime=hrTime;function timeInputToHrTime(time){if(isTimeInputHrTime(time)){return time}else if(typeof time==="number"){if(time<getTimeOrigin()){return hrTime(time)}else{return numberToHrtime(time)}}else if(time instanceof Date){return numberToHrtime(time.getTime())}else{throw TypeError("Invalid input type")}}exports.timeInputToHrTime=timeInputToHrTime;function hrTimeDuration(startTime,endTime){let seconds=endTime[0]-startTime[0];let nanos=endTime[1]-startTime[1];if(nanos<0){seconds-=1;nanos+=SECOND_TO_NANOSECONDS}return[seconds,nanos]}exports.hrTimeDuration=hrTimeDuration;function hrTimeToTimeStamp(time){const precision=NANOSECOND_DIGITS;const tmp=`${"0".repeat(precision)}${time[1]}Z`;const nanoString=tmp.substr(tmp.length-precision-1);const date=new Date(time[0]*1e3).toISOString();return date.replace("000Z",nanoString)}exports.hrTimeToTimeStamp=hrTimeToTimeStamp;function hrTimeToNanoseconds(time){return time[0]*SECOND_TO_NANOSECONDS+time[1]}exports.hrTimeToNanoseconds=hrTimeToNanoseconds;function hrTimeToMilliseconds(time){return Math.round(time[0]*1e3+time[1]/1e6)}exports.hrTimeToMilliseconds=hrTimeToMilliseconds;function hrTimeToMicroseconds(time){return Math.round(time[0]*1e6+time[1]/1e3)}exports.hrTimeToMicroseconds=hrTimeToMicroseconds;function isTimeInputHrTime(value){return Array.isArray(value)&&value.length===2&&typeof value[0]==="number"&&typeof value[1]==="number"}exports.isTimeInputHrTime=isTimeInputHrTime;function isTimeInput(value){return isTimeInputHrTime(value)||typeof value==="number"||value instanceof Date}exports.isTimeInput=isTimeInput},{"../platform":64}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],57:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.internal=exports.baggageUtils=void 0;__exportStar(require("./baggage/propagation/W3CBaggagePropagator"),exports);__exportStar(require("./common/anchored-clock"),exports);__exportStar(require("./common/attributes"),exports);__exportStar(require("./common/global-error-handler"),exports);__exportStar(require("./common/logging-error-handler"),exports);__exportStar(require("./common/time"),exports);__exportStar(require("./common/types"),exports);__exportStar(require("./ExportResult"),exports);__exportStar(require("./version"),exports);exports.baggageUtils=require("./baggage/utils");__exportStar(require("./platform"),exports);__exportStar(require("./propagation/composite"),exports);__exportStar(require("./trace/W3CTraceContextPropagator"),exports);__exportStar(require("./trace/IdGenerator"),exports);__exportStar(require("./trace/rpc-metadata"),exports);__exportStar(require("./trace/sampler/AlwaysOffSampler"),exports);__exportStar(require("./trace/sampler/AlwaysOnSampler"),exports);__exportStar(require("./trace/sampler/ParentBasedSampler"),exports);__exportStar(require("./trace/sampler/TraceIdRatioBasedSampler"),exports);__exportStar(require("./trace/suppress-tracing"),exports);__exportStar(require("./trace/TraceState"),exports);__exportStar(require("./utils/environment"),exports);__exportStar(require("./utils/merge"),exports);__exportStar(require("./utils/sampling"),exports);__exportStar(require("./utils/url"),exports);__exportStar(require("./utils/wrap"),exports);__exportStar(require("./utils/callback"),exports);__exportStar(require("./version"),exports);const exporter_1=require("./internal/exporter");exports.internal={_export:exporter_1._export}},{"./ExportResult":47,"./baggage/propagation/W3CBaggagePropagator":49,"./baggage/utils":50,"./common/anchored-clock":51,"./common/attributes":52,"./common/global-error-handler":53,"./common/logging-error-handler":54,"./common/time":55,"./common/types":56,"./internal/exporter":58,"./platform":64,"./propagation/composite":68,"./trace/IdGenerator":69,"./trace/TraceState":70,"./trace/W3CTraceContextPropagator":71,"./trace/rpc-metadata":72,"./trace/sampler/AlwaysOffSampler":73,"./trace/sampler/AlwaysOnSampler":74,"./trace/sampler/ParentBasedSampler":75,"./trace/sampler/TraceIdRatioBasedSampler":76,"./trace/suppress-tracing":77,"./utils/callback":78,"./utils/environment":79,"./utils/merge":81,"./utils/sampling":83,"./utils/url":84,"./utils/wrap":85,"./version":86}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports._export=void 0;const api_1=require("@opentelemetry/api");const suppress_tracing_1=require("../trace/suppress-tracing");function _export(exporter,arg){return new Promise(resolve=>{api_1.context.with((0,suppress_tracing_1.suppressTracing)(api_1.context.active()),()=>{exporter.export(arg,result=>{resolve(result)})})})}exports._export=_export},{"../trace/suppress-tracing":77,"@opentelemetry/api":18}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.validateValue=exports.validateKey=void 0;const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]";const VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;const VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;const VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);const VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/;const INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(key){return VALID_KEY_REGEX.test(key)}exports.validateKey=validateKey;function validateValue(value){return VALID_VALUE_BASE_REGEX.test(value)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)}exports.validateValue=validateValue},{}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RandomIdGenerator=void 0;const SPAN_ID_BYTES=8;const TRACE_ID_BYTES=16;class RandomIdGenerator{constructor(){this.generateTraceId=getIdGenerator(TRACE_ID_BYTES);this.generateSpanId=getIdGenerator(SPAN_ID_BYTES)}}exports.RandomIdGenerator=RandomIdGenerator;const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(bytes){return function generateId(){for(let i=0;i<bytes*2;i++){SHARED_CHAR_CODES_ARRAY[i]=Math.floor(Math.random()*16)+48;if(SHARED_CHAR_CODES_ARRAY[i]>=58){SHARED_CHAR_CODES_ARRAY[i]+=39}}return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,bytes*2))}}},{}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getEnv=void 0;const environment_1=require("../../utils/environment");const globalThis_1=require("./globalThis");function getEnv(){const globalEnv=(0,environment_1.parseEnvironment)(globalThis_1._globalThis);return Object.assign({},environment_1.DEFAULT_ENVIRONMENT,globalEnv)}exports.getEnv=getEnv},{"../../utils/environment":79,"./globalThis":62}],62:[function(require,module,exports){(function(global){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports._globalThis=void 0;exports._globalThis=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.hexToBase64=void 0;function hexToBase64(hexStr){const hexStrLen=hexStr.length;let hexAsciiCharsStr="";for(let i=0;i<hexStrLen;i+=2){const hexPair=hexStr.substring(i,i+2);const hexVal=parseInt(hexPair,16);hexAsciiCharsStr+=String.fromCharCode(hexVal)}return btoa(hexAsciiCharsStr)}exports.hexToBase64=hexToBase64},{}],64:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./environment"),exports);__exportStar(require("./globalThis"),exports);__exportStar(require("./hex-to-base64"),exports);__exportStar(require("./RandomIdGenerator"),exports);__exportStar(require("./performance"),exports);__exportStar(require("./sdk-info"),exports);__exportStar(require("./timer-util"),exports)},{"./RandomIdGenerator":60,"./environment":61,"./globalThis":62,"./hex-to-base64":63,"./performance":65,"./sdk-info":66,"./timer-util":67}],65:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.otperformance=void 0;exports.otperformance=performance},{}],66:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SDK_INFO=void 0;const version_1=require("../../version");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");exports.SDK_INFO={[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME]:"opentelemetry",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]:"browser",[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]:semantic_conventions_1.TelemetrySdkLanguageValues.WEBJS,[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION]:version_1.VERSION}},{"../../version":86,"@opentelemetry/semantic-conventions":152}],67:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.unrefTimer=void 0;function unrefTimer(_timer){}exports.unrefTimer=unrefTimer},{}],68:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CompositePropagator=void 0;const api_1=require("@opentelemetry/api");class CompositePropagator{constructor(config={}){var _a;this._propagators=(_a=config.propagators)!==null&&_a!==void 0?_a:[];this._fields=Array.from(new Set(this._propagators.map(p=>typeof p.fields==="function"?p.fields():[]).reduce((x,y)=>x.concat(y),[])))}inject(context,carrier,setter){for(const propagator of this._propagators){try{propagator.inject(context,carrier,setter)}catch(err){api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`)}}}extract(context,carrier,getter){return this._propagators.reduce((ctx,propagator)=>{try{return propagator.extract(ctx,carrier,getter)}catch(err){api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`)}return ctx},context)}fields(){return this._fields.slice()}}exports.CompositePropagator=CompositePropagator},{"@opentelemetry/api":18}],69:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],70:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceState=void 0;const validators_1=require("../internal/validators");const MAX_TRACE_STATE_ITEMS=32;const MAX_TRACE_STATE_LEN=512;const LIST_MEMBERS_SEPARATOR=",";const LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceState{constructor(rawTraceState){this._internalState=new Map;if(rawTraceState)this._parse(rawTraceState)}set(key,value){const traceState=this._clone();if(traceState._internalState.has(key)){traceState._internalState.delete(key)}traceState._internalState.set(key,value);return traceState}unset(key){const traceState=this._clone();traceState._internalState.delete(key);return traceState}get(key){return this._internalState.get(key)}serialize(){return this._keys().reduce((agg,key)=>{agg.push(key+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(key));return agg},[]).join(LIST_MEMBERS_SEPARATOR)}_parse(rawTraceState){if(rawTraceState.length>MAX_TRACE_STATE_LEN)return;this._internalState=rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg,part)=>{const listMember=part.trim();const i=listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(i!==-1){const key=listMember.slice(0,i);const value=listMember.slice(i+1,part.length);if((0,validators_1.validateKey)(key)&&(0,validators_1.validateValue)(value)){agg.set(key,value)}else{}}return agg},new Map);if(this._internalState.size>MAX_TRACE_STATE_ITEMS){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const traceState=new TraceState;traceState._internalState=new Map(this._internalState);return traceState}}exports.TraceState=TraceState},{"../internal/validators":59}],71:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.W3CTraceContextPropagator=exports.parseTraceParent=exports.TRACE_STATE_HEADER=exports.TRACE_PARENT_HEADER=void 0;const api_1=require("@opentelemetry/api");const suppress_tracing_1=require("./suppress-tracing");const TraceState_1=require("./TraceState");exports.TRACE_PARENT_HEADER="traceparent";exports.TRACE_STATE_HEADER="tracestate";const VERSION="00";const VERSION_PART="(?!ff)[\\da-f]{2}";const TRACE_ID_PART="(?![0]{32})[\\da-f]{32}";const PARENT_ID_PART="(?![0]{16})[\\da-f]{16}";const FLAGS_PART="[\\da-f]{2}";const TRACE_PARENT_REGEX=new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);function parseTraceParent(traceParent){const match=TRACE_PARENT_REGEX.exec(traceParent);if(!match)return null;if(match[1]==="00"&&match[5])return null;return{traceId:match[2],spanId:match[3],traceFlags:parseInt(match[4],16)}}exports.parseTraceParent=parseTraceParent;class W3CTraceContextPropagator{inject(context,carrier,setter){const spanContext=api_1.trace.getSpanContext(context);if(!spanContext||(0,suppress_tracing_1.isTracingSuppressed)(context)||!(0,api_1.isSpanContextValid)(spanContext))return;const traceParent=`${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags||api_1.TraceFlags.NONE).toString(16)}`;setter.set(carrier,exports.TRACE_PARENT_HEADER,traceParent);if(spanContext.traceState){setter.set(carrier,exports.TRACE_STATE_HEADER,spanContext.traceState.serialize())}}extract(context,carrier,getter){const traceParentHeader=getter.get(carrier,exports.TRACE_PARENT_HEADER);if(!traceParentHeader)return context;const traceParent=Array.isArray(traceParentHeader)?traceParentHeader[0]:traceParentHeader;if(typeof traceParent!=="string")return context;const spanContext=parseTraceParent(traceParent);if(!spanContext)return context;spanContext.isRemote=true;const traceStateHeader=getter.get(carrier,exports.TRACE_STATE_HEADER);if(traceStateHeader){const state=Array.isArray(traceStateHeader)?traceStateHeader.join(","):traceStateHeader;spanContext.traceState=new TraceState_1.TraceState(typeof state==="string"?state:undefined)}return api_1.trace.setSpanContext(context,spanContext)}fields(){return[exports.TRACE_PARENT_HEADER,exports.TRACE_STATE_HEADER]}}exports.W3CTraceContextPropagator=W3CTraceContextPropagator},{"./TraceState":70,"./suppress-tracing":77,"@opentelemetry/api":18}],72:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getRPCMetadata=exports.deleteRPCMetadata=exports.setRPCMetadata=exports.RPCType=void 0;const api_1=require("@opentelemetry/api");const RPC_METADATA_KEY=(0,api_1.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA");var RPCType;(function(RPCType){RPCType["HTTP"]="http"})(RPCType=exports.RPCType||(exports.RPCType={}));function setRPCMetadata(context,meta){return context.setValue(RPC_METADATA_KEY,meta)}exports.setRPCMetadata=setRPCMetadata;function deleteRPCMetadata(context){return context.deleteValue(RPC_METADATA_KEY)}exports.deleteRPCMetadata=deleteRPCMetadata;function getRPCMetadata(context){return context.getValue(RPC_METADATA_KEY)}exports.getRPCMetadata=getRPCMetadata},{"@opentelemetry/api":18}],73:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AlwaysOffSampler=void 0;const api_1=require("@opentelemetry/api");class AlwaysOffSampler{shouldSample(){return{decision:api_1.SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}exports.AlwaysOffSampler=AlwaysOffSampler},{"@opentelemetry/api":18}],74:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AlwaysOnSampler=void 0;const api_1=require("@opentelemetry/api");class AlwaysOnSampler{shouldSample(){return{decision:api_1.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}exports.AlwaysOnSampler=AlwaysOnSampler},{"@opentelemetry/api":18}],75:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ParentBasedSampler=void 0;const api_1=require("@opentelemetry/api");const global_error_handler_1=require("../../common/global-error-handler");const AlwaysOffSampler_1=require("./AlwaysOffSampler");const AlwaysOnSampler_1=require("./AlwaysOnSampler");class ParentBasedSampler{constructor(config){var _a,_b,_c,_d;this._root=config.root;if(!this._root){(0,global_error_handler_1.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new AlwaysOnSampler_1.AlwaysOnSampler}this._remoteParentSampled=(_a=config.remoteParentSampled)!==null&&_a!==void 0?_a:new AlwaysOnSampler_1.AlwaysOnSampler;this._remoteParentNotSampled=(_b=config.remoteParentNotSampled)!==null&&_b!==void 0?_b:new AlwaysOffSampler_1.AlwaysOffSampler;this._localParentSampled=(_c=config.localParentSampled)!==null&&_c!==void 0?_c:new AlwaysOnSampler_1.AlwaysOnSampler;this._localParentNotSampled=(_d=config.localParentNotSampled)!==null&&_d!==void 0?_d:new AlwaysOffSampler_1.AlwaysOffSampler}shouldSample(context,traceId,spanName,spanKind,attributes,links){const parentContext=api_1.trace.getSpanContext(context);if(!parentContext||!(0,api_1.isSpanContextValid)(parentContext)){return this._root.shouldSample(context,traceId,spanName,spanKind,attributes,links)}if(parentContext.isRemote){if(parentContext.traceFlags&api_1.TraceFlags.SAMPLED){return this._remoteParentSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}return this._remoteParentNotSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}if(parentContext.traceFlags&api_1.TraceFlags.SAMPLED){return this._localParentSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}return this._localParentNotSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}exports.ParentBasedSampler=ParentBasedSampler},{"../../common/global-error-handler":53,"./AlwaysOffSampler":73,"./AlwaysOnSampler":74,"@opentelemetry/api":18}],76:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceIdRatioBasedSampler=void 0;const api_1=require("@opentelemetry/api");class TraceIdRatioBasedSampler{constructor(_ratio=0){this._ratio=_ratio;this._ratio=this._normalize(_ratio);this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(context,traceId){return{decision:(0,api_1.isValidTraceId)(traceId)&&this._accumulate(traceId)<this._upperBound?api_1.SamplingDecision.RECORD_AND_SAMPLED:api_1.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(ratio){if(typeof ratio!=="number"||isNaN(ratio))return 0;return ratio>=1?1:ratio<=0?0:ratio}_accumulate(traceId){let accumulation=0;for(let i=0;i<traceId.length/8;i++){const pos=i*8;const part=parseInt(traceId.slice(pos,pos+8),16);accumulation=(accumulation^part)>>>0}return accumulation}}exports.TraceIdRatioBasedSampler=TraceIdRatioBasedSampler},{"@opentelemetry/api":18}],77:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isTracingSuppressed=exports.unsuppressTracing=exports.suppressTracing=void 0;const api_1=require("@opentelemetry/api");const SUPPRESS_TRACING_KEY=(0,api_1.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing(context){return context.setValue(SUPPRESS_TRACING_KEY,true)}exports.suppressTracing=suppressTracing;function unsuppressTracing(context){return context.deleteValue(SUPPRESS_TRACING_KEY)}exports.unsuppressTracing=unsuppressTracing;function isTracingSuppressed(context){return context.getValue(SUPPRESS_TRACING_KEY)===true}exports.isTracingSuppressed=isTracingSuppressed},{"@opentelemetry/api":18}],78:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BindOnceFuture=void 0;const promise_1=require("./promise");class BindOnceFuture{constructor(_callback,_that){this._callback=_callback;this._that=_that;this._isCalled=false;this._deferred=new promise_1.Deferred}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...args){if(!this._isCalled){this._isCalled=true;try{Promise.resolve(this._callback.call(this._that,...args)).then(val=>this._deferred.resolve(val),err=>this._deferred.reject(err))}catch(err){this._deferred.reject(err)}}return this._deferred.promise}}exports.BindOnceFuture=BindOnceFuture},{"./promise":82}],79:[function(require,module,exports){(function(process){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getEnvWithoutDefaults=exports.parseEnvironment=exports.DEFAULT_ENVIRONMENT=exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT=exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=void 0;const api_1=require("@opentelemetry/api");const sampling_1=require("./sampling");const globalThis_1=require("../platform/browser/globalThis");const DEFAULT_LIST_SEPARATOR=",";const ENVIRONMENT_NUMBERS_KEYS=["OTEL_BSP_EXPORT_TIMEOUT","OTEL_BSP_MAX_EXPORT_BATCH_SIZE","OTEL_BSP_MAX_QUEUE_SIZE","OTEL_BSP_SCHEDULE_DELAY","OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT","OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT","OTEL_SPAN_EVENT_COUNT_LIMIT","OTEL_SPAN_LINK_COUNT_LIMIT","OTEL_EXPORTER_OTLP_TIMEOUT","OTEL_EXPORTER_OTLP_TRACES_TIMEOUT","OTEL_EXPORTER_OTLP_METRICS_TIMEOUT","OTEL_EXPORTER_JAEGER_AGENT_PORT"];function isEnvVarANumber(key){return ENVIRONMENT_NUMBERS_KEYS.indexOf(key)>-1}const ENVIRONMENT_LISTS_KEYS=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function isEnvVarAList(key){return ENVIRONMENT_LISTS_KEYS.indexOf(key)>-1}exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=Infinity;exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128;exports.DEFAULT_ENVIRONMENT={CONTAINER_NAME:"",ECS_CONTAINER_METADATA_URI_V4:"",ECS_CONTAINER_METADATA_URI:"",HOSTNAME:"",KUBERNETES_SERVICE_HOST:"",NAMESPACE:"",OTEL_BSP_EXPORT_TIMEOUT:3e4,OTEL_BSP_MAX_EXPORT_BATCH_SIZE:512,OTEL_BSP_MAX_QUEUE_SIZE:2048,OTEL_BSP_SCHEDULE_DELAY:5e3,OTEL_EXPORTER_JAEGER_AGENT_HOST:"",OTEL_EXPORTER_JAEGER_AGENT_PORT:6832,OTEL_EXPORTER_JAEGER_ENDPOINT:"",OTEL_EXPORTER_JAEGER_PASSWORD:"",OTEL_EXPORTER_JAEGER_USER:"",OTEL_EXPORTER_OTLP_ENDPOINT:"",OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:"",OTEL_EXPORTER_OTLP_METRICS_ENDPOINT:"",OTEL_EXPORTER_OTLP_HEADERS:"",OTEL_EXPORTER_OTLP_TRACES_HEADERS:"",OTEL_EXPORTER_OTLP_METRICS_HEADERS:"",OTEL_EXPORTER_OTLP_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:1e4,OTEL_EXPORTER_OTLP_METRICS_TIMEOUT:1e4,OTEL_EXPORTER_ZIPKIN_ENDPOINT:"http://localhost:9411/api/v2/spans",OTEL_LOG_LEVEL:api_1.DiagLogLevel.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,OTEL_ATTRIBUTE_COUNT_LIMIT:exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_TRACES_EXPORTER:"otlp",OTEL_TRACES_SAMPLER:sampling_1.TracesSamplerValues.ParentBasedAlwaysOn,OTEL_TRACES_SAMPLER_ARG:"",OTEL_EXPORTER_OTLP_INSECURE:"",OTEL_EXPORTER_OTLP_TRACES_INSECURE:"",OTEL_EXPORTER_OTLP_METRICS_INSECURE:"",OTEL_EXPORTER_OTLP_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE:"",OTEL_EXPORTER_OTLP_COMPRESSION:"",OTEL_EXPORTER_OTLP_TRACES_COMPRESSION:"",OTEL_EXPORTER_OTLP_METRICS_COMPRESSION:"",OTEL_EXPORTER_OTLP_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY:"",OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE:"",OTEL_EXPORTER_OTLP_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_PROTOCOL:"http/protobuf",OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE:"cumulative"};function parseNumber(name,environment,values,min=-Infinity,max=Infinity){if(typeof values[name]!=="undefined"){const value=Number(values[name]);if(!isNaN(value)){if(value<min){environment[name]=min}else if(value>max){environment[name]=max}else{environment[name]=value}}}}function parseStringList(name,output,input,separator=DEFAULT_LIST_SEPARATOR){const givenValue=input[name];if(typeof givenValue==="string"){output[name]=givenValue.split(separator).map(v=>v.trim())}}const logLevelMap={ALL:api_1.DiagLogLevel.ALL,VERBOSE:api_1.DiagLogLevel.VERBOSE,DEBUG:api_1.DiagLogLevel.DEBUG,INFO:api_1.DiagLogLevel.INFO,WARN:api_1.DiagLogLevel.WARN,ERROR:api_1.DiagLogLevel.ERROR,NONE:api_1.DiagLogLevel.NONE};function setLogLevelFromEnv(key,environment,values){const value=values[key];if(typeof value==="string"){const theLevel=logLevelMap[value.toUpperCase()];if(theLevel!=null){environment[key]=theLevel}}}function parseEnvironment(values){const environment={};for(const env in exports.DEFAULT_ENVIRONMENT){const key=env;switch(key){case"OTEL_LOG_LEVEL":setLogLevelFromEnv(key,environment,values);break;default:if(isEnvVarANumber(key)){parseNumber(key,environment,values)}else if(isEnvVarAList(key)){parseStringList(key,environment,values)}else{const value=values[key];if(typeof value!=="undefined"&&value!==null){environment[key]=String(value)}}}}return environment}exports.parseEnvironment=parseEnvironment;function getEnvWithoutDefaults(){return typeof process!=="undefined"?parseEnvironment(process.env):parseEnvironment(globalThis_1._globalThis)}exports.getEnvWithoutDefaults=getEnvWithoutDefaults}).call(this)}).call(this,require("_process"))},{"../platform/browser/globalThis":62,"./sampling":83,"@opentelemetry/api":18,_process:162}],80:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isPlainObject=void 0;const objectTag="[object Object]";const nullTag="[object Null]";const undefinedTag="[object Undefined]";const funcProto=Function.prototype;const funcToString=funcProto.toString;const objectCtorString=funcToString.call(Object);const getPrototype=overArg(Object.getPrototypeOf,Object);const objectProto=Object.prototype;const hasOwnProperty=objectProto.hasOwnProperty;const symToStringTag=Symbol?Symbol.toStringTag:undefined;const nativeObjectToString=objectProto.toString;function overArg(func,transform){return function(arg){return func(transform(arg))}}function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!==objectTag){return false}const proto=getPrototype(value);if(proto===null){return true}const Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return typeof Ctor=="function"&&Ctor instanceof Ctor&&funcToString.call(Ctor)===objectCtorString}exports.isPlainObject=isPlainObject;function isObjectLike(value){return value!=null&&typeof value=="object"}function baseGetTag(value){if(value==null){return value===undefined?undefinedTag:nullTag}return symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value)}function getRawTag(value){const isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];let unmasked=false;try{value[symToStringTag]=undefined;unmasked=true}catch(e){}const result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag]=tag}else{delete value[symToStringTag]}}return result}function objectToString(value){return nativeObjectToString.call(value)}},{}],81:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.merge=void 0;const lodash_merge_1=require("./lodash.merge");const MAX_LEVEL=20;function merge(...args){let result=args.shift();const objects=new WeakMap;while(args.length>0){result=mergeTwoObjects(result,args.shift(),0,objects)}return result}exports.merge=merge;function takeValue(value){if(isArray(value)){return value.slice()}return value}function mergeTwoObjects(one,two,level=0,objects){let result;if(level>MAX_LEVEL){return undefined}level++;if(isPrimitive(one)||isPrimitive(two)||isFunction(two)){result=takeValue(two)}else if(isArray(one)){result=one.slice();if(isArray(two)){for(let i=0,j=two.length;i<j;i++){result.push(takeValue(two[i]))}}else if(isObject(two)){const keys=Object.keys(two);for(let i=0,j=keys.length;i<j;i++){const key=keys[i];result[key]=takeValue(two[key])}}}else if(isObject(one)){if(isObject(two)){if(!shouldMerge(one,two)){return two}result=Object.assign({},one);const keys=Object.keys(two);for(let i=0,j=keys.length;i<j;i++){const key=keys[i];const twoValue=two[key];if(isPrimitive(twoValue)){if(typeof twoValue==="undefined"){delete result[key]}else{result[key]=twoValue}}else{const obj1=result[key];const obj2=twoValue;if(wasObjectReferenced(one,key,objects)||wasObjectReferenced(two,key,objects)){delete result[key]}else{if(isObject(obj1)&&isObject(obj2)){const arr1=objects.get(obj1)||[];const arr2=objects.get(obj2)||[];arr1.push({obj:one,key:key});arr2.push({obj:two,key:key});objects.set(obj1,arr1);objects.set(obj2,arr2)}result[key]=mergeTwoObjects(result[key],twoValue,level,objects)}}}}else{result=two}}return result}function wasObjectReferenced(obj,key,objects){const arr=objects.get(obj[key])||[];for(let i=0,j=arr.length;i<j;i++){const info=arr[i];if(info.key===key&&info.obj===obj){return true}}return false}function isArray(value){return Array.isArray(value)}function isFunction(value){return typeof value==="function"}function isObject(value){return!isPrimitive(value)&&!isArray(value)&&!isFunction(value)&&typeof value==="object"}function isPrimitive(value){return typeof value==="string"||typeof value==="number"||typeof value==="boolean"||typeof value==="undefined"||value instanceof Date||value instanceof RegExp||value===null}function shouldMerge(one,two){if(!(0,lodash_merge_1.isPlainObject)(one)||!(0,lodash_merge_1.isPlainObject)(two)){return false}return true}},{"./lodash.merge":80}],82:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Deferred=void 0;class Deferred{constructor(){this._promise=new Promise((resolve,reject)=>{this._resolve=resolve;this._reject=reject})}get promise(){return this._promise}resolve(val){this._resolve(val)}reject(err){this._reject(err)}}exports.Deferred=Deferred},{}],83:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TracesSamplerValues=void 0;var TracesSamplerValues;(function(TracesSamplerValues){TracesSamplerValues["AlwaysOff"]="always_off";TracesSamplerValues["AlwaysOn"]="always_on";TracesSamplerValues["ParentBasedAlwaysOff"]="parentbased_always_off";TracesSamplerValues["ParentBasedAlwaysOn"]="parentbased_always_on";TracesSamplerValues["ParentBasedTraceIdRatio"]="parentbased_traceidratio";TracesSamplerValues["TraceIdRatio"]="traceidratio"})(TracesSamplerValues=exports.TracesSamplerValues||(exports.TracesSamplerValues={}))},{}],84:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isUrlIgnored=exports.urlMatches=void 0;function urlMatches(url,urlToMatch){if(typeof urlToMatch==="string"){return url===urlToMatch}else{return!!url.match(urlToMatch)}}exports.urlMatches=urlMatches;function isUrlIgnored(url,ignoredUrls){if(!ignoredUrls){return false}for(const ignoreUrl of ignoredUrls){if(urlMatches(url,ignoreUrl)){return true}}return false}exports.isUrlIgnored=isUrlIgnored},{}],85:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isWrapped=void 0;function isWrapped(func){return typeof func==="function"&&typeof func.__original==="function"&&typeof func.__unwrap==="function"&&func.__wrapped===true}exports.isWrapped=isWrapped},{}],86:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VERSION=void 0;exports.VERSION="1.8.0"},{}],87:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AttributeNames=void 0;var AttributeNames;(function(AttributeNames){AttributeNames["COMPONENT"]="component";AttributeNames["HTTP_ERROR_NAME"]="http.error_name";AttributeNames["HTTP_STATUS_TEXT"]="http.status_text"})(AttributeNames=exports.AttributeNames||(exports.AttributeNames={}))},{}],88:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FetchInstrumentation=void 0;const api=require("@opentelemetry/api");const instrumentation_1=require("@opentelemetry/instrumentation");const core=require("@opentelemetry/core");const web=require("@opentelemetry/sdk-trace-web");const AttributeNames_1=require("./enums/AttributeNames");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const version_1=require("./version");const core_1=require("@opentelemetry/core");const OBSERVER_WAIT_TIME_MS=300;class FetchInstrumentation extends instrumentation_1.InstrumentationBase{constructor(config){super("@opentelemetry/instrumentation-fetch",version_1.VERSION,config);this.component="fetch";this.version=version_1.VERSION;this.moduleName=this.component;this._usedResources=new WeakSet;this._tasksCount=0}init(){}_getConfig(){return this._config}_addChildSpan(span,corsPreFlightRequest){const childSpan=this.tracer.startSpan("CORS Preflight",{startTime:corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START]},api.trace.setSpan(api.context.active(),span));if(!this._getConfig().ignoreNetworkEvents){web.addSpanNetworkEvents(childSpan,corsPreFlightRequest)}childSpan.end(corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END])}_addFinalSpanAttributes(span,response){const parsedUrl=web.parseUrl(response.url);span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_STATUS_CODE,response.status);if(response.statusText!=null){span.setAttribute(AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT,response.statusText)}span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_HOST,parsedUrl.host);span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_SCHEME,parsedUrl.protocol.replace(":",""));span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_USER_AGENT,navigator.userAgent)}_addHeaders(options,spanUrl){if(!web.shouldPropagateTraceHeaders(spanUrl,this._getConfig().propagateTraceHeaderCorsUrls)){const headers={};api.propagation.inject(api.context.active(),headers);if(Object.keys(headers).length>0){this._diag.debug("headers inject skipped due to CORS policy")}return}if(options instanceof Request){api.propagation.inject(api.context.active(),options.headers,{set:(h,k,v)=>h.set(k,typeof v==="string"?v:String(v))})}else if(options.headers instanceof Headers){api.propagation.inject(api.context.active(),options.headers,{set:(h,k,v)=>h.set(k,typeof v==="string"?v:String(v))})}else{const headers={};api.propagation.inject(api.context.active(),headers);options.headers=Object.assign({},headers,options.headers||{})}}_clearResources(){if(this._tasksCount===0&&this._getConfig().clearTimingResources){performance.clearResourceTimings();this._usedResources=new WeakSet}}_createSpan(url,options={}){if(core.isUrlIgnored(url,this._getConfig().ignoreUrls)){this._diag.debug("ignoring span as url matches ignored url");return}const method=(options.method||"GET").toUpperCase();const spanName=`HTTP ${method}`;return this.tracer.startSpan(spanName,{kind:api.SpanKind.CLIENT,attributes:{[AttributeNames_1.AttributeNames.COMPONENT]:this.moduleName,[semantic_conventions_1.SemanticAttributes.HTTP_METHOD]:method,[semantic_conventions_1.SemanticAttributes.HTTP_URL]:url}})}_findResourceAndAddNetworkEvents(span,resourcesObserver,endTime){let resources=resourcesObserver.entries;if(!resources.length){if(!performance.getEntriesByType){return}resources=performance.getEntriesByType("resource")}const resource=web.getResource(resourcesObserver.spanUrl,resourcesObserver.startTime,endTime,resources,this._usedResources,"fetch");if(resource.mainRequest){const mainRequest=resource.mainRequest;this._markResourceAsUsed(mainRequest);const corsPreFlightRequest=resource.corsPreFlightRequest;if(corsPreFlightRequest){this._addChildSpan(span,corsPreFlightRequest);this._markResourceAsUsed(corsPreFlightRequest)}if(!this._getConfig().ignoreNetworkEvents){web.addSpanNetworkEvents(span,mainRequest)}}}_markResourceAsUsed(resource){this._usedResources.add(resource)}_endSpan(span,spanData,response){const endTime=core.hrTime();this._addFinalSpanAttributes(span,response);setTimeout(()=>{var _a;(_a=spanData.observer)===null||_a===void 0?void 0:_a.disconnect();this._findResourceAndAddNetworkEvents(span,spanData,endTime);this._tasksCount--;this._clearResources();span.end(endTime)},OBSERVER_WAIT_TIME_MS)}_patchConstructor(){return original=>{const plugin=this;return function patchConstructor(...args){const self=this;const url=web.parseUrl(args[0]instanceof Request?args[0].url:args[0]).href;const options=args[0]instanceof Request?args[0]:args[1]||{};const createdSpan=plugin._createSpan(url,options);if(!createdSpan){return original.apply(this,args)}const spanData=plugin._prepareSpanData(url);function endSpanOnError(span,error){plugin._applyAttributesAfterFetch(span,options,error);plugin._endSpan(span,spanData,{status:error.status||0,statusText:error.message,url:url})}function endSpanOnSuccess(span,response){plugin._applyAttributesAfterFetch(span,options,response);if(response.status>=200&&response.status<400){plugin._endSpan(span,spanData,response)}else{plugin._endSpan(span,spanData,{status:response.status,statusText:response.statusText,url:url})}}function onSuccess(span,resolve,response){try{const resClone=response.clone();const resClone4Hook=response.clone();const body=resClone.body;if(body){const reader=body.getReader();const read=()=>{reader.read().then(({done})=>{if(done){endSpanOnSuccess(span,resClone4Hook)}else{read()}},error=>{endSpanOnError(span,error)})};read()}else{endSpanOnSuccess(span,response)}}finally{resolve(response)}}function onError(span,reject,error){try{endSpanOnError(span,error)}finally{reject(error)}}return new Promise((resolve,reject)=>{return api.context.with(api.trace.setSpan(api.context.active(),createdSpan),()=>{plugin._addHeaders(options,url);plugin._tasksCount++;return original.apply(self,options instanceof Request?[options]:[url,options]).then(onSuccess.bind(self,createdSpan,resolve),onError.bind(self,createdSpan,reject))})})}}}_applyAttributesAfterFetch(span,request,result){const applyCustomAttributesOnSpan=this._getConfig().applyCustomAttributesOnSpan;if(applyCustomAttributesOnSpan){(0,instrumentation_1.safeExecuteInTheMiddle)(()=>applyCustomAttributesOnSpan(span,request,result),error=>{if(!error){return}this._diag.error("applyCustomAttributesOnSpan",error)},true)}}_prepareSpanData(spanUrl){const startTime=core.hrTime();const entries=[];if(typeof PerformanceObserver!=="function"){return{entries:entries,startTime:startTime,spanUrl:spanUrl}}const observer=new PerformanceObserver(list=>{const perfObsEntries=list.getEntries();perfObsEntries.forEach(entry=>{if(entry.initiatorType==="fetch"&&entry.name===spanUrl){entries.push(entry)}})});observer.observe({entryTypes:["resource"]});return{entries:entries,observer:observer,startTime:startTime,spanUrl:spanUrl}}enable(){if((0,instrumentation_1.isWrapped)(fetch)){this._unwrap(core_1._globalThis,"fetch");this._diag.debug("removing previous patch for constructor")}this._wrap(core_1._globalThis,"fetch",this._patchConstructor())}disable(){this._unwrap(core_1._globalThis,"fetch");this._usedResources=new WeakSet}}exports.FetchInstrumentation=FetchInstrumentation},{"./enums/AttributeNames":87,"./version":90,"@opentelemetry/api":18,"@opentelemetry/core":57,"@opentelemetry/instrumentation":98,"@opentelemetry/sdk-trace-web":149,"@opentelemetry/semantic-conventions":152}],89:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./fetch"),exports)},{"./fetch":88}],90:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.VERSION=void 0;exports.VERSION="0.34.0"},{}],91:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AttributeNames=void 0;var AttributeNames;(function(AttributeNames){AttributeNames["HTTP_STATUS_TEXT"]="http.status_text"})(AttributeNames=exports.AttributeNames||(exports.AttributeNames={}))},{}],92:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventNames=void 0;var EventNames;(function(EventNames){EventNames["METHOD_OPEN"]="open";EventNames["METHOD_SEND"]="send";EventNames["EVENT_ABORT"]="abort";EventNames["EVENT_ERROR"]="error";EventNames["EVENT_LOAD"]="loaded";EventNames["EVENT_TIMEOUT"]="timeout"})(EventNames=exports.EventNames||(exports.EventNames={}))},{}],93:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./xhr"),exports)},{"./xhr":95}],94:[function(require,module,exports){arguments[4][90][0].apply(exports,arguments)},{dup:90}],95:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.XMLHttpRequestInstrumentation=void 0;const api=require("@opentelemetry/api");const instrumentation_1=require("@opentelemetry/instrumentation");const core_1=require("@opentelemetry/core");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const sdk_trace_web_1=require("@opentelemetry/sdk-trace-web");const EventNames_1=require("./enums/EventNames");const version_1=require("./version");const AttributeNames_1=require("./enums/AttributeNames");const OBSERVER_WAIT_TIME_MS=300;class XMLHttpRequestInstrumentation extends instrumentation_1.InstrumentationBase{constructor(config){super("@opentelemetry/instrumentation-xml-http-request",version_1.VERSION,config);this.component="xml-http-request";this.version=version_1.VERSION;this.moduleName=this.component;this._tasksCount=0;this._xhrMem=new WeakMap;this._usedResources=new WeakSet}init(){}_getConfig(){return this._config}_addHeaders(xhr,spanUrl){const url=(0,sdk_trace_web_1.parseUrl)(spanUrl).href;if(!(0,sdk_trace_web_1.shouldPropagateTraceHeaders)(url,this._getConfig().propagateTraceHeaderCorsUrls)){const headers={};api.propagation.inject(api.context.active(),headers);if(Object.keys(headers).length>0){this._diag.debug("headers inject skipped due to CORS policy")}return}const headers={};api.propagation.inject(api.context.active(),headers);Object.keys(headers).forEach(key=>{xhr.setRequestHeader(key,String(headers[key]))})}_addChildSpan(span,corsPreFlightRequest){api.context.with(api.trace.setSpan(api.context.active(),span),()=>{const childSpan=this.tracer.startSpan("CORS Preflight",{startTime:corsPreFlightRequest[sdk_trace_web_1.PerformanceTimingNames.FETCH_START]});(0,sdk_trace_web_1.addSpanNetworkEvents)(childSpan,corsPreFlightRequest);childSpan.end(corsPreFlightRequest[sdk_trace_web_1.PerformanceTimingNames.RESPONSE_END])})}_addFinalSpanAttributes(span,xhrMem,spanUrl){if(typeof spanUrl==="string"){const parsedUrl=(0,sdk_trace_web_1.parseUrl)(spanUrl);if(xhrMem.status!==undefined){span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_STATUS_CODE,xhrMem.status)}if(xhrMem.statusText!==undefined){span.setAttribute(AttributeNames_1.AttributeNames.HTTP_STATUS_TEXT,xhrMem.statusText)}span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_HOST,parsedUrl.host);span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_SCHEME,parsedUrl.protocol.replace(":",""));span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_USER_AGENT,navigator.userAgent)}}_applyAttributesAfterXHR(span,xhr){const applyCustomAttributesOnSpan=this._getConfig().applyCustomAttributesOnSpan;if(typeof applyCustomAttributesOnSpan==="function"){(0,instrumentation_1.safeExecuteInTheMiddle)(()=>applyCustomAttributesOnSpan(span,xhr),error=>{if(!error){return}this._diag.error("applyCustomAttributesOnSpan",error)},true)}}_addResourceObserver(xhr,spanUrl){const xhrMem=this._xhrMem.get(xhr);if(!xhrMem||typeof PerformanceObserver!=="function"||typeof PerformanceResourceTiming!=="function"){return}xhrMem.createdResources={observer:new PerformanceObserver(list=>{const entries=list.getEntries();const parsedUrl=(0,sdk_trace_web_1.parseUrl)(spanUrl);entries.forEach(entry=>{if(entry.initiatorType==="xmlhttprequest"&&entry.name===parsedUrl.href){if(xhrMem.createdResources){xhrMem.createdResources.entries.push(entry)}}})}),entries:[]};xhrMem.createdResources.observer.observe({entryTypes:["resource"]})}_clearResources(){if(this._tasksCount===0&&this._getConfig().clearTimingResources){core_1.otperformance.clearResourceTimings();this._xhrMem=new WeakMap;this._usedResources=new WeakSet}}_findResourceAndAddNetworkEvents(xhrMem,span,spanUrl,startTime,endTime){if(!spanUrl||!startTime||!endTime||!xhrMem.createdResources){return}let resources=xhrMem.createdResources.entries;if(!resources||!resources.length){resources=core_1.otperformance.getEntriesByType("resource")}const resource=(0,sdk_trace_web_1.getResource)((0,sdk_trace_web_1.parseUrl)(spanUrl).href,startTime,endTime,resources,this._usedResources);if(resource.mainRequest){const mainRequest=resource.mainRequest;this._markResourceAsUsed(mainRequest);const corsPreFlightRequest=resource.corsPreFlightRequest;if(corsPreFlightRequest){this._addChildSpan(span,corsPreFlightRequest);this._markResourceAsUsed(corsPreFlightRequest)}(0,sdk_trace_web_1.addSpanNetworkEvents)(span,mainRequest)}}_cleanPreviousSpanInformation(xhr){const xhrMem=this._xhrMem.get(xhr);if(xhrMem){const callbackToRemoveEvents=xhrMem.callbackToRemoveEvents;if(callbackToRemoveEvents){callbackToRemoveEvents()}this._xhrMem.delete(xhr)}}_createSpan(xhr,url,method){if((0,core_1.isUrlIgnored)(url,this._getConfig().ignoreUrls)){this._diag.debug("ignoring span as url matches ignored url");return}const spanName=`HTTP ${method.toUpperCase()}`;const currentSpan=this.tracer.startSpan(spanName,{kind:api.SpanKind.CLIENT,attributes:{[semantic_conventions_1.SemanticAttributes.HTTP_METHOD]:method,[semantic_conventions_1.SemanticAttributes.HTTP_URL]:url}});currentSpan.addEvent(EventNames_1.EventNames.METHOD_OPEN);this._cleanPreviousSpanInformation(xhr);this._xhrMem.set(xhr,{span:currentSpan,spanUrl:url});return currentSpan}_markResourceAsUsed(resource){this._usedResources.add(resource)}_patchOpen(){return original=>{const plugin=this;return function patchOpen(...args){const method=args[0];const url=args[1];plugin._createSpan(this,url,method);return original.apply(this,args)}}}_patchSend(){const plugin=this;function endSpanTimeout(eventName,xhrMem,endTime){const callbackToRemoveEvents=xhrMem.callbackToRemoveEvents;if(typeof callbackToRemoveEvents==="function"){callbackToRemoveEvents()}const{span,spanUrl,sendStartTime}=xhrMem;if(span){plugin._findResourceAndAddNetworkEvents(xhrMem,span,spanUrl,sendStartTime,endTime);span.addEvent(eventName,endTime);plugin._addFinalSpanAttributes(span,xhrMem,spanUrl);span.end(endTime);plugin._tasksCount--}plugin._clearResources()}function endSpan(eventName,xhr){const xhrMem=plugin._xhrMem.get(xhr);if(!xhrMem){return}xhrMem.status=xhr.status;xhrMem.statusText=xhr.statusText;plugin._xhrMem.delete(xhr);if(xhrMem.span){plugin._applyAttributesAfterXHR(xhrMem.span,xhr)}const endTime=(0,core_1.hrTime)();setTimeout(()=>{endSpanTimeout(eventName,xhrMem,endTime)},OBSERVER_WAIT_TIME_MS)}function onError(){endSpan(EventNames_1.EventNames.EVENT_ERROR,this)}function onAbort(){endSpan(EventNames_1.EventNames.EVENT_ABORT,this)}function onTimeout(){endSpan(EventNames_1.EventNames.EVENT_TIMEOUT,this)}function onLoad(){if(this.status<299){endSpan(EventNames_1.EventNames.EVENT_LOAD,this)}else{endSpan(EventNames_1.EventNames.EVENT_ERROR,this)}}function unregister(xhr){xhr.removeEventListener("abort",onAbort);xhr.removeEventListener("error",onError);xhr.removeEventListener("load",onLoad);xhr.removeEventListener("timeout",onTimeout);const xhrMem=plugin._xhrMem.get(xhr);if(xhrMem){xhrMem.callbackToRemoveEvents=undefined}}return original=>{return function patchSend(...args){const xhrMem=plugin._xhrMem.get(this);if(!xhrMem){return original.apply(this,args)}const currentSpan=xhrMem.span;const spanUrl=xhrMem.spanUrl;if(currentSpan&&spanUrl){api.context.with(api.trace.setSpan(api.context.active(),currentSpan),()=>{plugin._tasksCount++;xhrMem.sendStartTime=(0,core_1.hrTime)();currentSpan.addEvent(EventNames_1.EventNames.METHOD_SEND);this.addEventListener("abort",onAbort);this.addEventListener("error",onError);this.addEventListener("load",onLoad);this.addEventListener("timeout",onTimeout);xhrMem.callbackToRemoveEvents=()=>{unregister(this);if(xhrMem.createdResources){xhrMem.createdResources.observer.disconnect()}};plugin._addHeaders(this,spanUrl);plugin._addResourceObserver(this,spanUrl)})}return original.apply(this,args)}}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version);if((0,instrumentation_1.isWrapped)(XMLHttpRequest.prototype.open)){this._unwrap(XMLHttpRequest.prototype,"open");this._diag.debug("removing previous patch from method open")}if((0,instrumentation_1.isWrapped)(XMLHttpRequest.prototype.send)){this._unwrap(XMLHttpRequest.prototype,"send");this._diag.debug("removing previous patch from method send")}this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen());this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version);this._unwrap(XMLHttpRequest.prototype,"open");this._unwrap(XMLHttpRequest.prototype,"send");this._tasksCount=0;this._xhrMem=new WeakMap;this._usedResources=new WeakSet}}exports.XMLHttpRequestInstrumentation=XMLHttpRequestInstrumentation},{"./enums/AttributeNames":91,"./enums/EventNames":92,"./version":94,"@opentelemetry/api":18,"@opentelemetry/core":57,"@opentelemetry/instrumentation":98,"@opentelemetry/sdk-trace-web":149,"@opentelemetry/semantic-conventions":152}],96:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.registerInstrumentations=void 0;const api_1=require("@opentelemetry/api");const autoLoaderUtils_1=require("./autoLoaderUtils");function registerInstrumentations(options){const{instrumentations}=(0,autoLoaderUtils_1.parseInstrumentationOptions)(options.instrumentations);const tracerProvider=options.tracerProvider||api_1.trace.getTracerProvider();const meterProvider=options.meterProvider||api_1.metrics.getMeterProvider();(0,autoLoaderUtils_1.enableInstrumentations)(instrumentations,tracerProvider,meterProvider);return()=>{(0,autoLoaderUtils_1.disableInstrumentations)(instrumentations)}}exports.registerInstrumentations=registerInstrumentations},{"./autoLoaderUtils":97,"@opentelemetry/api":18}],97:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.disableInstrumentations=exports.enableInstrumentations=exports.parseInstrumentationOptions=void 0;function parseInstrumentationOptions(options=[]){let instrumentations=[];for(let i=0,j=options.length;i<j;i++){const option=options[i];if(Array.isArray(option)){const results=parseInstrumentationOptions(option);instrumentations=instrumentations.concat(results.instrumentations)}else if(typeof option==="function"){instrumentations.push(new option)}else if(option.instrumentationName){instrumentations.push(option)}}return{instrumentations:instrumentations}}exports.parseInstrumentationOptions=parseInstrumentationOptions;function enableInstrumentations(instrumentations,tracerProvider,meterProvider){for(let i=0,j=instrumentations.length;i<j;i++){const instrumentation=instrumentations[i];if(tracerProvider){instrumentation.setTracerProvider(tracerProvider)}if(meterProvider){instrumentation.setMeterProvider(meterProvider)}if(!instrumentation.getConfig().enabled){instrumentation.enable()}}}exports.enableInstrumentations=enableInstrumentations;function disableInstrumentations(instrumentations){instrumentations.forEach(instrumentation=>instrumentation.disable())}exports.disableInstrumentations=disableInstrumentations},{}],98:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./autoLoader"),exports);__exportStar(require("./platform/index"),exports);__exportStar(require("./types"),exports);__exportStar(require("./types_internal"),exports);__exportStar(require("./utils"),exports)},{"./autoLoader":96,"./platform/index":100,"./types":102,"./types_internal":103,"./utils":104}],99:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.InstrumentationAbstract=void 0;const api_1=require("@opentelemetry/api");const shimmer=require("shimmer");class InstrumentationAbstract{constructor(instrumentationName,instrumentationVersion,config={}){this.instrumentationName=instrumentationName;this.instrumentationVersion=instrumentationVersion;this._wrap=shimmer.wrap;this._unwrap=shimmer.unwrap;this._massWrap=shimmer.massWrap;this._massUnwrap=shimmer.massUnwrap;this._config=Object.assign({enabled:true},config);this._diag=api_1.diag.createComponentLogger({namespace:instrumentationName});this._tracer=api_1.trace.getTracer(instrumentationName,instrumentationVersion);this._meter=api_1.metrics.getMeter(instrumentationName,instrumentationVersion)}get meter(){return this._meter}setMeterProvider(meterProvider){this._meter=meterProvider.getMeter(this.instrumentationName,this.instrumentationVersion)}getConfig(){return this._config}setConfig(config={}){this._config=Object.assign({},config)}setTracerProvider(tracerProvider){this._tracer=tracerProvider.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}}exports.InstrumentationAbstract=InstrumentationAbstract},{"@opentelemetry/api":18,shimmer:163}],100:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./instrumentation"),exports)},{"./instrumentation":101}],101:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.InstrumentationBase=void 0;const instrumentation_1=require("../../instrumentation");class InstrumentationBase extends instrumentation_1.InstrumentationAbstract{constructor(instrumentationName,instrumentationVersion,config={}){super(instrumentationName,instrumentationVersion,config);if(this._config.enabled){this.enable()}}}exports.InstrumentationBase=InstrumentationBase},{"../../instrumentation":99}],102:[function(require,module,exports){arguments[4][56][0].apply(exports,arguments)},{dup:56}],103:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],104:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isWrapped=exports.safeExecuteInTheMiddleAsync=exports.safeExecuteInTheMiddle=void 0;function safeExecuteInTheMiddle(execute,onFinish,preventThrowingError){let error;let result;try{result=execute()}catch(e){error=e}finally{onFinish(error,result);if(error&&!preventThrowingError){throw error}return result}}exports.safeExecuteInTheMiddle=safeExecuteInTheMiddle;async function safeExecuteInTheMiddleAsync(execute,onFinish,preventThrowingError){let error;let result;try{result=await execute()}catch(e){error=e}finally{onFinish(error,result);if(error&&!preventThrowingError){throw error}return result}}exports.safeExecuteInTheMiddleAsync=safeExecuteInTheMiddleAsync;function isWrapped(func){return typeof func==="function"&&typeof func.__original==="function"&&typeof func.__unwrap==="function"&&func.__wrapped===true}exports.isWrapped=isWrapped},{}],105:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Resource=void 0;const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const core_1=require("@opentelemetry/core");const platform_1=require("./platform");class Resource{constructor(attributes){this.attributes=attributes}static empty(){return Resource.EMPTY}static default(){return new Resource({[semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME]:(0,platform_1.defaultServiceName)(),[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]:core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE],[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME]:core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_NAME],[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION]:core_1.SDK_INFO[semantic_conventions_1.SemanticResourceAttributes.TELEMETRY_SDK_VERSION]})}merge(other){if(!other||!Object.keys(other.attributes).length)return this;const mergedAttributes=Object.assign({},this.attributes,other.attributes);return new Resource(mergedAttributes)}}exports.Resource=Resource;Resource.EMPTY=new Resource({})},{"./platform":117,"@opentelemetry/core":57,"@opentelemetry/semantic-conventions":152}],106:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],107:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.browserDetector=void 0;const api_1=require("@opentelemetry/api");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const __1=require("..");class BrowserDetector{async detect(config){const isBrowser=typeof navigator!=="undefined";if(!isBrowser){return __1.Resource.empty()}const browserResource={[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]:"browser",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]:"Web Browser",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]:navigator.userAgent};return this._getResourceAttributes(browserResource,config)}_getResourceAttributes(browserResource,_config){if(browserResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]===""){api_1.diag.debug("BrowserDetector failed: Unable to find required browser resources. ");return __1.Resource.empty()}else{return new __1.Resource(Object.assign({},browserResource))}}}exports.browserDetector=new BrowserDetector},{"..":112,"@opentelemetry/api":18,"@opentelemetry/semantic-conventions":152}],108:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.envDetector=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const Resource_1=require("../Resource");class EnvDetector{constructor(){this._MAX_LENGTH=255;this._COMMA_SEPARATOR=",";this._LABEL_KEY_VALUE_SPLITTER="=";this._ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";this._ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters."}async detect(_config){const attributes={};const env=(0,core_1.getEnv)();const rawAttributes=env.OTEL_RESOURCE_ATTRIBUTES;const serviceName=env.OTEL_SERVICE_NAME;if(rawAttributes){try{const parsedAttributes=this._parseResourceAttributes(rawAttributes);Object.assign(attributes,parsedAttributes)}catch(e){api_1.diag.debug(`EnvDetector failed: ${e.message}`)}}if(serviceName){attributes[semantic_conventions_1.SemanticResourceAttributes.SERVICE_NAME]=serviceName}return new Resource_1.Resource(attributes)}_parseResourceAttributes(rawEnvAttributes){if(!rawEnvAttributes)return{};const attributes={};const rawAttributes=rawEnvAttributes.split(this._COMMA_SEPARATOR,-1);for(const rawAttribute of rawAttributes){const keyValuePair=rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(keyValuePair.length!==2){continue}let[key,value]=keyValuePair;key=key.trim();value=value.trim().split(/^"|"$/).join("");if(!this._isValidAndNotEmpty(key)){throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`)}if(!this._isValid(value)){throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`)}attributes[key]=decodeURIComponent(value)}return attributes}_isValid(name){return name.length<=this._MAX_LENGTH&&this._isBaggageOctetString(name)}_isBaggageOctetString(str){for(let i=0;i<str.length;i++){const ch=str.charCodeAt(i);if(ch<33||ch===44||ch===59||ch===92||ch>126){return false}}return true}_isValidAndNotEmpty(str){return str.length>0&&this._isValid(str)}}exports.envDetector=new EnvDetector},{"../Resource":105,"@opentelemetry/api":18,"@opentelemetry/core":57,"@opentelemetry/semantic-conventions":152}],109:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noopDetector=exports.NoopDetector=void 0;const Resource_1=require("../Resource");class NoopDetector{async detect(){return new Resource_1.Resource({})}}exports.NoopDetector=NoopDetector;exports.noopDetector=new NoopDetector},{"../Resource":105}],110:[function(require,module,exports){(function(process){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.processDetector=void 0;const api_1=require("@opentelemetry/api");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const Resource_1=require("../Resource");class ProcessDetector{async detect(config){if(typeof process!=="object"){return Resource_1.Resource.empty()}const processResource={[semantic_conventions_1.SemanticResourceAttributes.PROCESS_PID]:process.pid,[semantic_conventions_1.SemanticResourceAttributes.PROCESS_EXECUTABLE_NAME]:process.title||"",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND]:process.argv[1]||"",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND_LINE]:process.argv.join(" ")||"",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]:process.versions.node,[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_NAME]:"nodejs",[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]:"Node.js"};return this._getResourceAttributes(processResource,config)}_getResourceAttributes(processResource,_config){if(processResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_EXECUTABLE_NAME]===""||processResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_EXECUTABLE_PATH]===""||processResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND]===""||processResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_COMMAND_LINE]===""||processResource[semantic_conventions_1.SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]===""){api_1.diag.debug("ProcessDetector failed: Unable to find required process resources. ");return Resource_1.Resource.empty()}else{return new Resource_1.Resource(Object.assign({},processResource))}}}exports.processDetector=new ProcessDetector}).call(this)}).call(this,require("_process"))},{"../Resource":105,"@opentelemetry/api":18,"@opentelemetry/semantic-conventions":152,_process:162}],111:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./BrowserDetector"),exports);__exportStar(require("./EnvDetector"),exports);__exportStar(require("./ProcessDetector"),exports)},{"./BrowserDetector":107,"./EnvDetector":108,"./ProcessDetector":110}],112:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./Resource"),exports);__exportStar(require("./platform"),exports);__exportStar(require("./types"),exports);__exportStar(require("./config"),exports);__exportStar(require("./detectors"),exports)},{"./Resource":105,"./config":106,"./detectors":111,"./platform":117,"./types":118}],113:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.hostDetector=void 0;const NoopDetector_1=require("../../detectors/NoopDetector");exports.hostDetector=NoopDetector_1.noopDetector},{"../../detectors/NoopDetector":109}],114:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.osDetector=void 0;const NoopDetector_1=require("../../detectors/NoopDetector");exports.osDetector=NoopDetector_1.noopDetector},{"../../detectors/NoopDetector":109}],115:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.defaultServiceName=void 0;function defaultServiceName(){return"unknown_service"}exports.defaultServiceName=defaultServiceName},{}],116:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectResources=void 0;const Resource_1=require("../../Resource");const api_1=require("@opentelemetry/api");const detectResources=async(config={})=>{const internalConfig=Object.assign(config);const resources=await Promise.all((internalConfig.detectors||[]).map(async d=>{try{const resource=await d.detect(internalConfig);api_1.diag.debug(`${d.constructor.name} found resource.`,resource);return resource}catch(e){api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`);return Resource_1.Resource.empty()}}));return resources.reduce((acc,resource)=>acc.merge(resource),Resource_1.Resource.empty())};exports.detectResources=detectResources},{"../../Resource":105,"@opentelemetry/api":18}],117:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./default-service-name"),exports);__exportStar(require("./detect-resources"),exports);__exportStar(require("./HostDetector"),exports);__exportStar(require("./OSDetector"),exports)},{"./HostDetector":113,"./OSDetector":114,"./default-service-name":115,"./detect-resources":116}],118:[function(require,module,exports){arguments[4][56][0].apply(exports,arguments)},{dup:56}],119:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicTracerProvider=exports.ForceFlushState=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const resources_1=require("@opentelemetry/resources");const _1=require(".");const config_1=require("./config");const MultiSpanProcessor_1=require("./MultiSpanProcessor");const NoopSpanProcessor_1=require("./export/NoopSpanProcessor");const platform_1=require("./platform");const utility_1=require("./utility");var ForceFlushState;(function(ForceFlushState){ForceFlushState[ForceFlushState["resolved"]=0]="resolved";ForceFlushState[ForceFlushState["timeout"]=1]="timeout";ForceFlushState[ForceFlushState["error"]=2]="error";ForceFlushState[ForceFlushState["unresolved"]=3]="unresolved"})(ForceFlushState=exports.ForceFlushState||(exports.ForceFlushState={}));class BasicTracerProvider{constructor(config={}){var _a;this._registeredSpanProcessors=[];this._tracers=new Map;const mergedConfig=(0,core_1.merge)({},(0,config_1.loadDefaultConfig)(),(0,utility_1.reconfigureLimits)(config));this.resource=(_a=mergedConfig.resource)!==null&&_a!==void 0?_a:resources_1.Resource.empty();this.resource=resources_1.Resource.default().merge(this.resource);this._config=Object.assign({},mergedConfig,{resource:this.resource});const defaultExporter=this._buildExporterFromEnv();if(defaultExporter!==undefined){const batchProcessor=new platform_1.BatchSpanProcessor(defaultExporter);this.activeSpanProcessor=batchProcessor}else{this.activeSpanProcessor=new NoopSpanProcessor_1.NoopSpanProcessor}}getTracer(name,version,options){const key=`${name}@${version||""}:${(options===null||options===void 0?void 0:options.schemaUrl)||""}`;if(!this._tracers.has(key)){this._tracers.set(key,new _1.Tracer({name:name,version:version,schemaUrl:options===null||options===void 0?void 0:options.schemaUrl},this._config,this))}return this._tracers.get(key)}addSpanProcessor(spanProcessor){if(this._registeredSpanProcessors.length===0){this.activeSpanProcessor.shutdown().catch(err=>api_1.diag.error("Error while trying to shutdown current span processor",err))}this._registeredSpanProcessors.push(spanProcessor);this.activeSpanProcessor=new MultiSpanProcessor_1.MultiSpanProcessor(this._registeredSpanProcessors)}getActiveSpanProcessor(){return this.activeSpanProcessor}register(config={}){api_1.trace.setGlobalTracerProvider(this);if(config.propagator===undefined){config.propagator=this._buildPropagatorFromEnv()}if(config.contextManager){api_1.context.setGlobalContextManager(config.contextManager)}if(config.propagator){api_1.propagation.setGlobalPropagator(config.propagator)}}forceFlush(){const timeout=this._config.forceFlushTimeoutMillis;const promises=this._registeredSpanProcessors.map(spanProcessor=>{return new Promise(resolve=>{let state;const timeoutInterval=setTimeout(()=>{resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`));state=ForceFlushState.timeout},timeout);spanProcessor.forceFlush().then(()=>{clearTimeout(timeoutInterval);if(state!==ForceFlushState.timeout){state=ForceFlushState.resolved;resolve(state)}}).catch(error=>{clearTimeout(timeoutInterval);state=ForceFlushState.error;resolve(error)})})});return new Promise((resolve,reject)=>{Promise.all(promises).then(results=>{const errors=results.filter(result=>result!==ForceFlushState.resolved);if(errors.length>0){reject(errors)}else{resolve()}}).catch(error=>reject([error]))})}shutdown(){return this.activeSpanProcessor.shutdown()}_getPropagator(name){var _a;return(_a=this.constructor._registeredPropagators.get(name))===null||_a===void 0?void 0:_a()}_getSpanExporter(name){var _a;return(_a=this.constructor._registeredExporters.get(name))===null||_a===void 0?void 0:_a()}_buildPropagatorFromEnv(){const uniquePropagatorNames=Array.from(new Set((0,core_1.getEnv)().OTEL_PROPAGATORS));const propagators=uniquePropagatorNames.map(name=>{const propagator=this._getPropagator(name);if(!propagator){api_1.diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`)}return propagator});const validPropagators=propagators.reduce((list,item)=>{if(item){list.push(item)}return list},[]);if(validPropagators.length===0){return}else if(uniquePropagatorNames.length===1){return validPropagators[0]}else{return new core_1.CompositePropagator({propagators:validPropagators})}}_buildExporterFromEnv(){const exporterName=(0,core_1.getEnv)().OTEL_TRACES_EXPORTER;if(exporterName==="none")return;const exporter=this._getSpanExporter(exporterName);if(!exporter){api_1.diag.error(`Exporter "${exporterName}" requested through environment variable is unavailable.`)}return exporter}}exports.BasicTracerProvider=BasicTracerProvider;BasicTracerProvider._registeredPropagators=new Map([["tracecontext",()=>new core_1.W3CTraceContextPropagator],["baggage",()=>new core_1.W3CBaggagePropagator]]);BasicTracerProvider._registeredExporters=new Map},{".":136,"./MultiSpanProcessor":121,"./config":127,"./export/NoopSpanProcessor":132,"./platform":139,"./utility":145,"@opentelemetry/api":18,"@opentelemetry/core":57,"@opentelemetry/resources":112}],120:[function(require,module,exports){arguments[4][69][0].apply(exports,arguments)},{dup:69}],121:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MultiSpanProcessor=void 0;const core_1=require("@opentelemetry/core");class MultiSpanProcessor{constructor(_spanProcessors){this._spanProcessors=_spanProcessors}forceFlush(){const promises=[];for(const spanProcessor of this._spanProcessors){promises.push(spanProcessor.forceFlush())}return new Promise(resolve=>{Promise.all(promises).then(()=>{resolve()}).catch(error=>{(0,core_1.globalErrorHandler)(error||new Error("MultiSpanProcessor: forceFlush failed"));resolve()})})}onStart(span,context){for(const spanProcessor of this._spanProcessors){spanProcessor.onStart(span,context)}}onEnd(span){for(const spanProcessor of this._spanProcessors){spanProcessor.onEnd(span)}}shutdown(){const promises=[];for(const spanProcessor of this._spanProcessors){promises.push(spanProcessor.shutdown())}return new Promise((resolve,reject)=>{Promise.all(promises).then(()=>{resolve()},reject)})}}exports.MultiSpanProcessor=MultiSpanProcessor},{"@opentelemetry/core":57}],122:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SamplingDecision=void 0;var SamplingDecision;(function(SamplingDecision){SamplingDecision[SamplingDecision["NOT_RECORD"]=0]="NOT_RECORD";SamplingDecision[SamplingDecision["RECORD"]=1]="RECORD";SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(SamplingDecision=exports.SamplingDecision||(exports.SamplingDecision={}))},{}],123:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Span=void 0;const api=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");const enums_1=require("./enums");class Span{constructor(parentTracer,context,spanName,spanContext,kind,parentSpanId,links=[],startTime,clock=core_1.otperformance){this.attributes={};this.links=[];this.events=[];this.status={code:api.SpanStatusCode.UNSET};this.endTime=[0,0];this._ended=false;this._duration=[-1,-1];this._clock=clock;this.name=spanName;this._spanContext=spanContext;this.parentSpanId=parentSpanId;this.kind=kind;this.links=links;this.startTime=(0,core_1.timeInputToHrTime)(startTime!==null&&startTime!==void 0?startTime:clock.now());this.resource=parentTracer.resource;this.instrumentationLibrary=parentTracer.instrumentationLibrary;this._spanLimits=parentTracer.getSpanLimits();this._spanProcessor=parentTracer.getActiveSpanProcessor();this._spanProcessor.onStart(this,context);this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0}spanContext(){return this._spanContext}setAttribute(key,value){if(value==null||this._isSpanEnded())return this;if(key.length===0){api.diag.warn(`Invalid attribute key: ${key}`);return this}if(!(0,core_1.isAttributeValue)(value)){api.diag.warn(`Invalid attribute value set for key: ${key}`);return this}if(Object.keys(this.attributes).length>=this._spanLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,key)){return this}this.attributes[key]=this._truncateToSize(value);return this}setAttributes(attributes){for(const[k,v]of Object.entries(attributes)){this.setAttribute(k,v)}return this}addEvent(name,attributesOrStartTime,startTime){if(this._isSpanEnded())return this;if(this._spanLimits.eventCountLimit===0){api.diag.warn("No events allowed.");return this}if(this.events.length>=this._spanLimits.eventCountLimit){api.diag.warn("Dropping extra events.");this.events.shift()}if((0,core_1.isTimeInput)(attributesOrStartTime)){if(typeof startTime==="undefined"){startTime=attributesOrStartTime}attributesOrStartTime=undefined}if(typeof startTime==="undefined"){startTime=this._clock.now()}const attributes=(0,core_1.sanitizeAttributes)(attributesOrStartTime);this.events.push({name:name,attributes:attributes,time:(0,core_1.timeInputToHrTime)(startTime)});return this}setStatus(status){if(this._isSpanEnded())return this;this.status=status;return this}updateName(name){if(this._isSpanEnded())return this;this.name=name;return this}end(endTime){if(this._isSpanEnded()){api.diag.error("You can only call end() on a span once.");return}this._ended=true;this.endTime=(0,core_1.timeInputToHrTime)(endTime!==null&&endTime!==void 0?endTime:this._clock.now());this._duration=(0,core_1.hrTimeDuration)(this.startTime,this.endTime);if(this._duration[0]<0){api.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime);this.endTime=this.startTime.slice();this._duration=[0,0]}this._spanProcessor.onEnd(this)}isRecording(){return this._ended===false}recordException(exception,time=this._clock.now()){const attributes={};if(typeof exception==="string"){attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE]=exception}else if(exception){if(exception.code){attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE]=exception.code.toString()}else if(exception.name){attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE]=exception.name}if(exception.message){attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE]=exception.message}if(exception.stack){attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_STACKTRACE]=exception.stack}}if(attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_TYPE]||attributes[semantic_conventions_1.SemanticAttributes.EXCEPTION_MESSAGE]){this.addEvent(enums_1.ExceptionEventName,attributes,time)}else{api.diag.warn(`Failed to record an exception ${exception}`)}}get duration(){return this._duration}get ended(){return this._ended}_isSpanEnded(){if(this._ended){api.diag.warn(`Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`)}return this._ended}_truncateToLimitUtil(value,limit){if(value.length<=limit){return value}return value.substr(0,limit)}_truncateToSize(value){const limit=this._attributeValueLengthLimit;if(limit<=0){api.diag.warn(`Attribute value limit must be positive, got ${limit}`);return value}if(typeof value==="string"){return this._truncateToLimitUtil(value,limit)}if(Array.isArray(value)){return value.map(val=>typeof val==="string"?this._truncateToLimitUtil(val,limit):val)}return value}}exports.Span=Span},{"./enums":128,"@opentelemetry/api":18,"@opentelemetry/core":57,"@opentelemetry/semantic-conventions":152}],124:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],125:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],126:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Tracer=void 0;const api=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const Span_1=require("./Span");const utility_1=require("./utility");const platform_1=require("./platform");class Tracer{constructor(instrumentationLibrary,config,_tracerProvider){this._tracerProvider=_tracerProvider;const localConfig=(0,utility_1.mergeConfig)(config);this._sampler=localConfig.sampler;this._generalLimits=localConfig.generalLimits;this._spanLimits=localConfig.spanLimits;this._idGenerator=config.idGenerator||new platform_1.RandomIdGenerator;this.resource=_tracerProvider.resource;this.instrumentationLibrary=instrumentationLibrary}startSpan(name,options={},context=api.context.active()){var _a,_b;if(options.root){context=api.trace.deleteSpan(context)}const parentSpan=api.trace.getSpan(context);if((0,core_1.isTracingSuppressed)(context)){api.diag.debug("Instrumentation suppressed, returning Noop Span");const nonRecordingSpan=api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT);return nonRecordingSpan}const parentSpanContext=parentSpan===null||parentSpan===void 0?void 0:parentSpan.spanContext();const spanId=this._idGenerator.generateSpanId();let traceId;let traceState;let parentSpanId;if(!parentSpanContext||!api.trace.isSpanContextValid(parentSpanContext)){traceId=this._idGenerator.generateTraceId()}else{traceId=parentSpanContext.traceId;traceState=parentSpanContext.traceState;parentSpanId=parentSpanContext.spanId}const spanKind=(_a=options.kind)!==null&&_a!==void 0?_a:api.SpanKind.INTERNAL;const links=((_b=options.links)!==null&&_b!==void 0?_b:[]).map(link=>{return{context:link.context,attributes:(0,core_1.sanitizeAttributes)(link.attributes)}});const attributes=(0,core_1.sanitizeAttributes)(options.attributes);const samplingResult=this._sampler.shouldSample(context,traceId,name,spanKind,attributes,links);const traceFlags=samplingResult.decision===api.SamplingDecision.RECORD_AND_SAMPLED?api.TraceFlags.SAMPLED:api.TraceFlags.NONE;const spanContext={traceId:traceId,spanId:spanId,traceFlags:traceFlags,traceState:traceState};if(samplingResult.decision===api.SamplingDecision.NOT_RECORD){api.diag.debug("Recording is off, propagating context in a non-recording span");const nonRecordingSpan=api.trace.wrapSpanContext(spanContext);return nonRecordingSpan}const span=new Span_1.Span(this,context,name,spanContext,spanKind,parentSpanId,links,options.startTime);const initAttributes=(0,core_1.sanitizeAttributes)(Object.assign(attributes,samplingResult.attributes));span.setAttributes(initAttributes);return span}startActiveSpan(name,arg2,arg3,arg4){let opts;let ctx;let fn;if(arguments.length<2){return}else if(arguments.length===2){fn=arg2}else if(arguments.length===3){opts=arg2;fn=arg3}else{opts=arg2;ctx=arg3;fn=arg4}const parentContext=ctx!==null&&ctx!==void 0?ctx:api.context.active();const span=this.startSpan(name,opts,parentContext);const contextWithSpanSet=api.trace.setSpan(parentContext,span);return api.context.with(contextWithSpanSet,fn,undefined,span)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}getActiveSpanProcessor(){return this._tracerProvider.getActiveSpanProcessor()}}exports.Tracer=Tracer},{"./Span":123,"./platform":139,"./utility":145,"@opentelemetry/api":18,"@opentelemetry/core":57}],127:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.buildSamplerFromEnv=exports.loadDefaultConfig=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const AlwaysOffSampler_1=require("./sampler/AlwaysOffSampler");const AlwaysOnSampler_1=require("./sampler/AlwaysOnSampler");const ParentBasedSampler_1=require("./sampler/ParentBasedSampler");const TraceIdRatioBasedSampler_1=require("./sampler/TraceIdRatioBasedSampler");const env=(0,core_1.getEnv)();const FALLBACK_OTEL_TRACES_SAMPLER=core_1.TracesSamplerValues.AlwaysOn;const DEFAULT_RATIO=1;function loadDefaultConfig(){return{sampler:buildSamplerFromEnv(env),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:(0,core_1.getEnv)().OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,attributeCountLimit:(0,core_1.getEnv)().OTEL_ATTRIBUTE_COUNT_LIMIT},spanLimits:{attributeValueLengthLimit:(0,core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,attributeCountLimit:(0,core_1.getEnv)().OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,linkCountLimit:(0,core_1.getEnv)().OTEL_SPAN_LINK_COUNT_LIMIT,eventCountLimit:(0,core_1.getEnv)().OTEL_SPAN_EVENT_COUNT_LIMIT}}}exports.loadDefaultConfig=loadDefaultConfig;function buildSamplerFromEnv(environment=(0,core_1.getEnv)()){switch(environment.OTEL_TRACES_SAMPLER){case core_1.TracesSamplerValues.AlwaysOn:return new AlwaysOnSampler_1.AlwaysOnSampler;case core_1.TracesSamplerValues.AlwaysOff:return new AlwaysOffSampler_1.AlwaysOffSampler;case core_1.TracesSamplerValues.ParentBasedAlwaysOn:return new ParentBasedSampler_1.ParentBasedSampler({root:new AlwaysOnSampler_1.AlwaysOnSampler});case core_1.TracesSamplerValues.ParentBasedAlwaysOff:return new ParentBasedSampler_1.ParentBasedSampler({root:new AlwaysOffSampler_1.AlwaysOffSampler});case core_1.TracesSamplerValues.TraceIdRatio:return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment));case core_1.TracesSamplerValues.ParentBasedTraceIdRatio:return new ParentBasedSampler_1.ParentBasedSampler({root:new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv(environment))});default:api_1.diag.error(`OTEL_TRACES_SAMPLER value "${environment.OTEL_TRACES_SAMPLER} invalid, defaulting to ${FALLBACK_OTEL_TRACES_SAMPLER}".`);return new AlwaysOnSampler_1.AlwaysOnSampler}}exports.buildSamplerFromEnv=buildSamplerFromEnv;function getSamplerProbabilityFromEnv(environment){if(environment.OTEL_TRACES_SAMPLER_ARG===undefined||environment.OTEL_TRACES_SAMPLER_ARG===""){api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`);return DEFAULT_RATIO}const probability=Number(environment.OTEL_TRACES_SAMPLER_ARG);if(isNaN(probability)){api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${DEFAULT_RATIO}.`);return DEFAULT_RATIO}if(probability<0||probability>1){api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`);return DEFAULT_RATIO}return probability}},{"./sampler/AlwaysOffSampler":140,"./sampler/AlwaysOnSampler":141,"./sampler/ParentBasedSampler":142,"./sampler/TraceIdRatioBasedSampler":143,"@opentelemetry/api":18,"@opentelemetry/core":57}],128:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExceptionEventName=void 0;exports.ExceptionEventName="exception"},{}],129:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BatchSpanProcessorBase=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");class BatchSpanProcessorBase{constructor(_exporter,config){this._exporter=_exporter;this._finishedSpans=[];const env=(0,core_1.getEnv)();this._maxExportBatchSize=typeof(config===null||config===void 0?void 0:config.maxExportBatchSize)==="number"?config.maxExportBatchSize:env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;this._maxQueueSize=typeof(config===null||config===void 0?void 0:config.maxQueueSize)==="number"?config.maxQueueSize:env.OTEL_BSP_MAX_QUEUE_SIZE;this._scheduledDelayMillis=typeof(config===null||config===void 0?void 0:config.scheduledDelayMillis)==="number"?config.scheduledDelayMillis:env.OTEL_BSP_SCHEDULE_DELAY;this._exportTimeoutMillis=typeof(config===null||config===void 0?void 0:config.exportTimeoutMillis)==="number"?config.exportTimeoutMillis:env.OTEL_BSP_EXPORT_TIMEOUT;this._shutdownOnce=new core_1.BindOnceFuture(this._shutdown,this);if(this._maxExportBatchSize>this._maxQueueSize){api_1.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");this._maxExportBatchSize=this._maxQueueSize}}forceFlush(){if(this._shutdownOnce.isCalled){return this._shutdownOnce.promise}return this._flushAll()}onStart(_span,_parentContext){}onEnd(span){if(this._shutdownOnce.isCalled){return}if((span.spanContext().traceFlags&api_1.TraceFlags.SAMPLED)===0){return}this._addToBuffer(span)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>{return this.onShutdown()}).then(()=>{return this._flushAll()}).then(()=>{return this._exporter.shutdown()})}_addToBuffer(span){if(this._finishedSpans.length>=this._maxQueueSize){return}this._finishedSpans.push(span);this._maybeStartTimer()}_flushAll(){return new Promise((resolve,reject)=>{const promises=[];const count=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let i=0,j=count;i<j;i++){promises.push(this._flushOneBatch())}Promise.all(promises).then(()=>{resolve()}).catch(reject)})}_flushOneBatch(){this._clearTimer();if(this._finishedSpans.length===0){return Promise.resolve()}return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{reject(new Error("Timeout"))},this._exportTimeoutMillis);api_1.context.with((0,core_1.suppressTracing)(api_1.context.active()),()=>{this._exporter.export(this._finishedSpans.splice(0,this._maxExportBatchSize),result=>{var _a;clearTimeout(timer);if(result.code===core_1.ExportResultCode.SUCCESS){resolve()}else{reject((_a=result.error)!==null&&_a!==void 0?_a:new Error("BatchSpanProcessor: span export failed"))}})})})}_maybeStartTimer(){if(this._timer!==undefined)return;this._timer=setTimeout(()=>{this._flushOneBatch().then(()=>{if(this._finishedSpans.length>0){this._clearTimer();this._maybeStartTimer()}}).catch(e=>{(0,core_1.globalErrorHandler)(e)})},this._scheduledDelayMillis);(0,core_1.unrefTimer)(this._timer)}_clearTimer(){if(this._timer!==undefined){clearTimeout(this._timer);this._timer=undefined}}}exports.BatchSpanProcessorBase=BatchSpanProcessorBase},{"@opentelemetry/api":18,"@opentelemetry/core":57}],130:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleSpanExporter=void 0;const core_1=require("@opentelemetry/core");class ConsoleSpanExporter{export(spans,resultCallback){return this._sendSpans(spans,resultCallback)}shutdown(){this._sendSpans([]);return Promise.resolve()}_exportInfo(span){return{traceId:span.spanContext().traceId,parentId:span.parentSpanId,name:span.name,id:span.spanContext().spanId,kind:span.kind,timestamp:(0,core_1.hrTimeToMicroseconds)(span.startTime),duration:(0,core_1.hrTimeToMicroseconds)(span.duration),attributes:span.attributes,status:span.status,events:span.events,links:span.links}}_sendSpans(spans,done){for(const span of spans){console.dir(this._exportInfo(span),{depth:3})}if(done){return done({code:core_1.ExportResultCode.SUCCESS})}}}exports.ConsoleSpanExporter=ConsoleSpanExporter},{"@opentelemetry/core":57}],131:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.InMemorySpanExporter=void 0;const core_1=require("@opentelemetry/core");class InMemorySpanExporter{constructor(){this._finishedSpans=[];this._stopped=false}export(spans,resultCallback){if(this._stopped)return resultCallback({code:core_1.ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...spans);setTimeout(()=>resultCallback({code:core_1.ExportResultCode.SUCCESS}),0)}shutdown(){this._stopped=true;this._finishedSpans=[];return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}exports.InMemorySpanExporter=InMemorySpanExporter},{"@opentelemetry/core":57}],132:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopSpanProcessor=void 0;class NoopSpanProcessor{onStart(_span,_context){}onEnd(_span){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}exports.NoopSpanProcessor=NoopSpanProcessor},{}],133:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],134:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleSpanProcessor=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");class SimpleSpanProcessor{constructor(_exporter){this._exporter=_exporter;this._shutdownOnce=new core_1.BindOnceFuture(this._shutdown,this)}forceFlush(){return Promise.resolve()}onStart(_span,_parentContext){}onEnd(span){if(this._shutdownOnce.isCalled){return}if((span.spanContext().traceFlags&api_1.TraceFlags.SAMPLED)===0){return}core_1.internal._export(this._exporter,[span]).then(result=>{var _a;if(result.code!==core_1.ExportResultCode.SUCCESS){(0,core_1.globalErrorHandler)((_a=result.error)!==null&&_a!==void 0?_a:new Error(`SimpleSpanProcessor: span export failed (status ${result})`))}}).catch(error=>{(0,core_1.globalErrorHandler)(error)})}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}exports.SimpleSpanProcessor=SimpleSpanProcessor},{"@opentelemetry/api":18,"@opentelemetry/core":57}],135:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true})},{}],136:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./Tracer"),exports);__exportStar(require("./BasicTracerProvider"),exports);__exportStar(require("./platform"),exports);__exportStar(require("./export/ConsoleSpanExporter"),exports);__exportStar(require("./export/InMemorySpanExporter"),exports);__exportStar(require("./export/ReadableSpan"),exports);__exportStar(require("./export/SimpleSpanProcessor"),exports);__exportStar(require("./export/SpanExporter"),exports);__exportStar(require("./export/NoopSpanProcessor"),exports);__exportStar(require("./sampler/AlwaysOffSampler"),exports);__exportStar(require("./sampler/AlwaysOnSampler"),exports);__exportStar(require("./sampler/ParentBasedSampler"),exports);__exportStar(require("./sampler/TraceIdRatioBasedSampler"),exports);__exportStar(require("./Sampler"),exports);__exportStar(require("./Span"),exports);__exportStar(require("./SpanProcessor"),exports);__exportStar(require("./TimedEvent"),exports);__exportStar(require("./types"),exports);__exportStar(require("./IdGenerator"),exports)},{"./BasicTracerProvider":119,"./IdGenerator":120,"./Sampler":122,"./Span":123,"./SpanProcessor":124,"./TimedEvent":125,"./Tracer":126,"./export/ConsoleSpanExporter":130,"./export/InMemorySpanExporter":131,"./export/NoopSpanProcessor":132,"./export/ReadableSpan":133,"./export/SimpleSpanProcessor":134,"./export/SpanExporter":135,"./platform":139,"./sampler/AlwaysOffSampler":140,"./sampler/AlwaysOnSampler":141,"./sampler/ParentBasedSampler":142,"./sampler/TraceIdRatioBasedSampler":143,"./types":144}],137:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RandomIdGenerator=void 0;const SPAN_ID_BYTES=8;const TRACE_ID_BYTES=16;class RandomIdGenerator{constructor(){this.generateTraceId=getIdGenerator(TRACE_ID_BYTES);this.generateSpanId=getIdGenerator(SPAN_ID_BYTES)}}exports.RandomIdGenerator=RandomIdGenerator;const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(bytes){return function generateId(){for(let i=0;i<bytes*2;i++){SHARED_CHAR_CODES_ARRAY[i]=Math.floor(Math.random()*16)+48;if(SHARED_CHAR_CODES_ARRAY[i]>=58){SHARED_CHAR_CODES_ARRAY[i]+=39}}return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,bytes*2))}}},{}],138:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BatchSpanProcessor=void 0;const BatchSpanProcessorBase_1=require("../../../export/BatchSpanProcessorBase");class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase{constructor(_exporter,config){super(_exporter,config);this.onInit(config)}onInit(config){if((config===null||config===void 0?void 0:config.disableAutoFlushOnDocumentHide)!==true&&typeof document!=="undefined"){this._visibilityChangeListener=()=>{if(document.visibilityState==="hidden"){void this.forceFlush()}};this._pageHideListener=()=>{void this.forceFlush()};document.addEventListener("visibilitychange",this._visibilityChangeListener);document.addEventListener("pagehide",this._pageHideListener)}}onShutdown(){if(typeof document!=="undefined"){if(this._visibilityChangeListener){document.removeEventListener("visibilitychange",this._visibilityChangeListener)}if(this._pageHideListener){document.removeEventListener("pagehide",this._pageHideListener)}}}}exports.BatchSpanProcessor=BatchSpanProcessor},{"../../../export/BatchSpanProcessorBase":129}],139:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./export/BatchSpanProcessor"),exports);__exportStar(require("./RandomIdGenerator"),exports)},{"./RandomIdGenerator":137,"./export/BatchSpanProcessor":138}],140:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AlwaysOffSampler=void 0;const Sampler_1=require("../Sampler");class AlwaysOffSampler{shouldSample(){return{decision:Sampler_1.SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}exports.AlwaysOffSampler=AlwaysOffSampler},{"../Sampler":122}],141:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AlwaysOnSampler=void 0;const Sampler_1=require("../Sampler");class AlwaysOnSampler{shouldSample(){return{decision:Sampler_1.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}exports.AlwaysOnSampler=AlwaysOnSampler},{"../Sampler":122}],142:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ParentBasedSampler=void 0;const api_1=require("@opentelemetry/api");const core_1=require("@opentelemetry/core");const AlwaysOffSampler_1=require("./AlwaysOffSampler");const AlwaysOnSampler_1=require("./AlwaysOnSampler");class ParentBasedSampler{constructor(config){var _a,_b,_c,_d;this._root=config.root;if(!this._root){(0,core_1.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new AlwaysOnSampler_1.AlwaysOnSampler}this._remoteParentSampled=(_a=config.remoteParentSampled)!==null&&_a!==void 0?_a:new AlwaysOnSampler_1.AlwaysOnSampler;this._remoteParentNotSampled=(_b=config.remoteParentNotSampled)!==null&&_b!==void 0?_b:new AlwaysOffSampler_1.AlwaysOffSampler;this._localParentSampled=(_c=config.localParentSampled)!==null&&_c!==void 0?_c:new AlwaysOnSampler_1.AlwaysOnSampler;this._localParentNotSampled=(_d=config.localParentNotSampled)!==null&&_d!==void 0?_d:new AlwaysOffSampler_1.AlwaysOffSampler}shouldSample(context,traceId,spanName,spanKind,attributes,links){const parentContext=api_1.trace.getSpanContext(context);if(!parentContext||!(0,api_1.isSpanContextValid)(parentContext)){return this._root.shouldSample(context,traceId,spanName,spanKind,attributes,links)}if(parentContext.isRemote){if(parentContext.traceFlags&api_1.TraceFlags.SAMPLED){return this._remoteParentSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}return this._remoteParentNotSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}if(parentContext.traceFlags&api_1.TraceFlags.SAMPLED){return this._localParentSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}return this._localParentNotSampled.shouldSample(context,traceId,spanName,spanKind,attributes,links)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}exports.ParentBasedSampler=ParentBasedSampler},{"./AlwaysOffSampler":140,"./AlwaysOnSampler":141,"@opentelemetry/api":18,"@opentelemetry/core":57}],143:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TraceIdRatioBasedSampler=void 0;const api_1=require("@opentelemetry/api");const Sampler_1=require("../Sampler");class TraceIdRatioBasedSampler{constructor(_ratio=0){this._ratio=_ratio;this._ratio=this._normalize(_ratio);this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(context,traceId){return{decision:(0,api_1.isValidTraceId)(traceId)&&this._accumulate(traceId)<this._upperBound?Sampler_1.SamplingDecision.RECORD_AND_SAMPLED:Sampler_1.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(ratio){if(typeof ratio!=="number"||isNaN(ratio))return 0;return ratio>=1?1:ratio<=0?0:ratio}_accumulate(traceId){let accumulation=0;for(let i=0;i<traceId.length/8;i++){const pos=i*8;const part=parseInt(traceId.slice(pos,pos+8),16);accumulation=(accumulation^part)>>>0}return accumulation}}exports.TraceIdRatioBasedSampler=TraceIdRatioBasedSampler},{"../Sampler":122,"@opentelemetry/api":18}],144:[function(require,module,exports){arguments[4][56][0].apply(exports,arguments)},{dup:56}],145:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.reconfigureLimits=exports.mergeConfig=void 0;const config_1=require("./config");const core_1=require("@opentelemetry/core");function mergeConfig(userConfig){const perInstanceDefaults={sampler:(0,config_1.buildSamplerFromEnv)()};const DEFAULT_CONFIG=(0,config_1.loadDefaultConfig)();const target=Object.assign({},DEFAULT_CONFIG,perInstanceDefaults,userConfig);target.generalLimits=Object.assign({},DEFAULT_CONFIG.generalLimits,userConfig.generalLimits||{});target.spanLimits=Object.assign({},DEFAULT_CONFIG.spanLimits,userConfig.spanLimits||{});return target}exports.mergeConfig=mergeConfig;function reconfigureLimits(userConfig){var _a,_b,_c,_d,_e,_f,_g,_h,_j,_k,_l,_m;const spanLimits=Object.assign({},userConfig.spanLimits);const parsedEnvConfig=(0,core_1.getEnvWithoutDefaults)();spanLimits.attributeCountLimit=(_f=(_e=(_d=(_b=(_a=userConfig.spanLimits)===null||_a===void 0?void 0:_a.attributeCountLimit)!==null&&_b!==void 0?_b:(_c=userConfig.generalLimits)===null||_c===void 0?void 0:_c.attributeCountLimit)!==null&&_d!==void 0?_d:parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT)!==null&&_e!==void 0?_e:parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT)!==null&&_f!==void 0?_f:core_1.DEFAULT_ATTRIBUTE_COUNT_LIMIT;spanLimits.attributeValueLengthLimit=(_m=(_l=(_k=(_h=(_g=userConfig.spanLimits)===null||_g===void 0?void 0:_g.attributeValueLengthLimit)!==null&&_h!==void 0?_h:(_j=userConfig.generalLimits)===null||_j===void 0?void 0:_j.attributeValueLengthLimit)!==null&&_k!==void 0?_k:parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT)!==null&&_l!==void 0?_l:parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT)!==null&&_m!==void 0?_m:core_1.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;return Object.assign({},userConfig,{spanLimits:spanLimits})}exports.reconfigureLimits=reconfigureLimits},{"./config":127,"@opentelemetry/core":57}],146:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StackContextManager=void 0;const api_1=require("@opentelemetry/api");class StackContextManager{constructor(){this._enabled=false;this._currentContext=api_1.ROOT_CONTEXT}_bindFunction(context=api_1.ROOT_CONTEXT,target){const manager=this;const contextWrapper=function(...args){return manager.with(context,()=>target.apply(this,args))};Object.defineProperty(contextWrapper,"length",{enumerable:false,configurable:true,writable:false,value:target.length});return contextWrapper}active(){return this._currentContext}bind(context,target){if(context===undefined){context=this.active()}if(typeof target==="function"){return this._bindFunction(context,target)}return target}disable(){this._currentContext=api_1.ROOT_CONTEXT;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=api_1.ROOT_CONTEXT;return this}with(context,fn,thisArg,...args){const previousContext=this._currentContext;this._currentContext=context||api_1.ROOT_CONTEXT;try{return fn.call(thisArg,...args)}finally{this._currentContext=previousContext}}}exports.StackContextManager=StackContextManager},{"@opentelemetry/api":18}],147:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WebTracerProvider=void 0;const sdk_trace_base_1=require("@opentelemetry/sdk-trace-base");const StackContextManager_1=require("./StackContextManager");class WebTracerProvider extends sdk_trace_base_1.BasicTracerProvider{constructor(config={}){super(config);if(config.contextManager){throw"contextManager should be defined in register method not in"+" constructor"}if(config.propagator){throw"propagator should be defined in register method not in constructor"}}register(config={}){if(config.contextManager===undefined){config.contextManager=new StackContextManager_1.StackContextManager}if(config.contextManager){config.contextManager.enable()}super.register(config)}}exports.WebTracerProvider=WebTracerProvider},{"./StackContextManager":146,"@opentelemetry/sdk-trace-base":136}],148:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PerformanceTimingNames=void 0;var PerformanceTimingNames;(function(PerformanceTimingNames){PerformanceTimingNames["CONNECT_END"]="connectEnd";PerformanceTimingNames["CONNECT_START"]="connectStart";PerformanceTimingNames["DECODED_BODY_SIZE"]="decodedBodySize";PerformanceTimingNames["DOM_COMPLETE"]="domComplete";PerformanceTimingNames["DOM_CONTENT_LOADED_EVENT_END"]="domContentLoadedEventEnd";PerformanceTimingNames["DOM_CONTENT_LOADED_EVENT_START"]="domContentLoadedEventStart";PerformanceTimingNames["DOM_INTERACTIVE"]="domInteractive";PerformanceTimingNames["DOMAIN_LOOKUP_END"]="domainLookupEnd";PerformanceTimingNames["DOMAIN_LOOKUP_START"]="domainLookupStart";PerformanceTimingNames["ENCODED_BODY_SIZE"]="encodedBodySize";PerformanceTimingNames["FETCH_START"]="fetchStart";PerformanceTimingNames["LOAD_EVENT_END"]="loadEventEnd";PerformanceTimingNames["LOAD_EVENT_START"]="loadEventStart";PerformanceTimingNames["NAVIGATION_START"]="navigationStart";PerformanceTimingNames["REDIRECT_END"]="redirectEnd";PerformanceTimingNames["REDIRECT_START"]="redirectStart";PerformanceTimingNames["REQUEST_START"]="requestStart";PerformanceTimingNames["RESPONSE_END"]="responseEnd";PerformanceTimingNames["RESPONSE_START"]="responseStart";PerformanceTimingNames["SECURE_CONNECTION_START"]="secureConnectionStart";PerformanceTimingNames["UNLOAD_EVENT_END"]="unloadEventEnd";PerformanceTimingNames["UNLOAD_EVENT_START"]="unloadEventStart"})(PerformanceTimingNames=exports.PerformanceTimingNames||(exports.PerformanceTimingNames={}))},{}],149:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./WebTracerProvider"),exports);__exportStar(require("./StackContextManager"),exports);__exportStar(require("./enums/PerformanceTimingNames"),exports);__exportStar(require("./types"),exports);__exportStar(require("./utils"),exports);__exportStar(require("@opentelemetry/sdk-trace-base"),exports)},{"./StackContextManager":146,"./WebTracerProvider":147,"./enums/PerformanceTimingNames":148,"./types":150,"./utils":151,"@opentelemetry/sdk-trace-base":136}],150:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const PerformanceTimingNames_1=require("./enums/PerformanceTimingNames")},{"./enums/PerformanceTimingNames":148}],151:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.shouldPropagateTraceHeaders=exports.getElementXPath=exports.normalizeUrl=exports.parseUrl=exports.getResource=exports.sortResources=exports.addSpanNetworkEvents=exports.addSpanNetworkEvent=exports.hasKey=void 0;const PerformanceTimingNames_1=require("./enums/PerformanceTimingNames");const core_1=require("@opentelemetry/core");const semantic_conventions_1=require("@opentelemetry/semantic-conventions");let urlNormalizingAnchor;function getUrlNormalizingAnchor(){if(!urlNormalizingAnchor){urlNormalizingAnchor=document.createElement("a")}return urlNormalizingAnchor}function hasKey(obj,key){return key in obj}exports.hasKey=hasKey;function addSpanNetworkEvent(span,performanceName,entries){if(hasKey(entries,performanceName)&&typeof entries[performanceName]==="number"){span.addEvent(performanceName,entries[performanceName]);return span}return undefined}exports.addSpanNetworkEvent=addSpanNetworkEvent;function addSpanNetworkEvents(span,resource){addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.DOMAIN_LOOKUP_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.DOMAIN_LOOKUP_END,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.CONNECT_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.SECURE_CONNECTION_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.CONNECT_END,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.REQUEST_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_START,resource);addSpanNetworkEvent(span,PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_END,resource);const encodedLength=resource[PerformanceTimingNames_1.PerformanceTimingNames.ENCODED_BODY_SIZE];if(encodedLength!==undefined){span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH,encodedLength)}const decodedLength=resource[PerformanceTimingNames_1.PerformanceTimingNames.DECODED_BODY_SIZE];if(decodedLength!==undefined&&encodedLength!==decodedLength){span.setAttribute(semantic_conventions_1.SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,decodedLength)}}exports.addSpanNetworkEvents=addSpanNetworkEvents;function sortResources(filteredResources){return filteredResources.slice().sort((a,b)=>{const valueA=a[PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START];const valueB=b[PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START];if(valueA>valueB){return 1}else if(valueA<valueB){return-1}return 0})}exports.sortResources=sortResources;function getResource(spanUrl,startTimeHR,endTimeHR,resources,ignoredResources=new WeakSet,initiatorType){const parsedSpanUrl=parseUrl(spanUrl);spanUrl=parsedSpanUrl.toString();const filteredResources=filterResourcesForSpan(spanUrl,startTimeHR,endTimeHR,resources,ignoredResources,initiatorType);if(filteredResources.length===0){return{mainRequest:undefined}}if(filteredResources.length===1){return{mainRequest:filteredResources[0]}}const sorted=sortResources(filteredResources);if(parsedSpanUrl.origin!==location.origin&&sorted.length>1){let corsPreFlightRequest=sorted[0];let mainRequest=findMainRequest(sorted,corsPreFlightRequest[PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_END],endTimeHR);const responseEnd=corsPreFlightRequest[PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_END];const fetchStart=mainRequest[PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START];if(fetchStart<responseEnd){mainRequest=corsPreFlightRequest;corsPreFlightRequest=undefined}return{corsPreFlightRequest:corsPreFlightRequest,mainRequest:mainRequest}}else{return{mainRequest:filteredResources[0]}}}exports.getResource=getResource;function findMainRequest(resources,corsPreFlightRequestEndTime,spanEndTimeHR){const spanEndTime=(0,core_1.hrTimeToNanoseconds)(spanEndTimeHR);const minTime=(0,core_1.hrTimeToNanoseconds)((0,core_1.timeInputToHrTime)(corsPreFlightRequestEndTime));let mainRequest=resources[1];let bestGap;const length=resources.length;for(let i=1;i<length;i++){const resource=resources[i];const resourceStartTime=(0,core_1.hrTimeToNanoseconds)((0,core_1.timeInputToHrTime)(resource[PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START]));const resourceEndTime=(0,core_1.hrTimeToNanoseconds)((0,core_1.timeInputToHrTime)(resource[PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_END]));const currentGap=spanEndTime-resourceEndTime;if(resourceStartTime>=minTime&&(!bestGap||currentGap<bestGap)){bestGap=currentGap;mainRequest=resource}}return mainRequest}function filterResourcesForSpan(spanUrl,startTimeHR,endTimeHR,resources,ignoredResources,initiatorType){const startTime=(0,core_1.hrTimeToNanoseconds)(startTimeHR);const endTime=(0,core_1.hrTimeToNanoseconds)(endTimeHR);let filteredResources=resources.filter(resource=>{const resourceStartTime=(0,core_1.hrTimeToNanoseconds)((0,core_1.timeInputToHrTime)(resource[PerformanceTimingNames_1.PerformanceTimingNames.FETCH_START]));const resourceEndTime=(0,core_1.hrTimeToNanoseconds)((0,core_1.timeInputToHrTime)(resource[PerformanceTimingNames_1.PerformanceTimingNames.RESPONSE_END]));return resource.initiatorType.toLowerCase()===(initiatorType||"xmlhttprequest")&&resource.name===spanUrl&&resourceStartTime>=startTime&&resourceEndTime<=endTime});if(filteredResources.length>0){filteredResources=filteredResources.filter(resource=>{return!ignoredResources.has(resource)})}return filteredResources}function parseUrl(url){if(typeof URL==="function"){return new URL(url,location.href)}const element=getUrlNormalizingAnchor();element.href=url;return element}exports.parseUrl=parseUrl;function normalizeUrl(url){const urlLike=parseUrl(url);return urlLike.href}exports.normalizeUrl=normalizeUrl;function getElementXPath(target,optimised){if(target.nodeType===Node.DOCUMENT_NODE){return"/"}const targetValue=getNodeValue(target,optimised);if(optimised&&targetValue.indexOf("@id")>0){return targetValue}let xpath="";if(target.parentNode){xpath+=getElementXPath(target.parentNode,false)}xpath+=targetValue;return xpath}exports.getElementXPath=getElementXPath;function getNodeIndex(target){if(!target.parentNode){return 0}const allowedTypes=[target.nodeType];if(target.nodeType===Node.CDATA_SECTION_NODE){allowedTypes.push(Node.TEXT_NODE)}let elements=Array.from(target.parentNode.childNodes);elements=elements.filter(element=>{const localName=element.localName;return allowedTypes.indexOf(element.nodeType)>=0&&localName===target.localName});if(elements.length>=1){return elements.indexOf(target)+1}return 0}function getNodeValue(target,optimised){const nodeType=target.nodeType;const index=getNodeIndex(target);let nodeValue="";if(nodeType===Node.ELEMENT_NODE){const id=target.getAttribute("id");if(optimised&&id){return`//*[@id="${id}"]`}nodeValue=target.localName}else if(nodeType===Node.TEXT_NODE||nodeType===Node.CDATA_SECTION_NODE){nodeValue="text()"}else if(nodeType===Node.COMMENT_NODE){nodeValue="comment()"}else{return""}if(nodeValue&&index>1){return`/${nodeValue}[${index}]`}return`/${nodeValue}`}function shouldPropagateTraceHeaders(spanUrl,propagateTraceHeaderCorsUrls){let propagateTraceHeaderUrls=propagateTraceHeaderCorsUrls||[];if(typeof propagateTraceHeaderUrls==="string"||propagateTraceHeaderUrls instanceof RegExp){propagateTraceHeaderUrls=[propagateTraceHeaderUrls]}const parsedSpanUrl=parseUrl(spanUrl);if(parsedSpanUrl.origin===location.origin){return true}else{return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl=>(0,core_1.urlMatches)(spanUrl,propagateTraceHeaderUrl))}}exports.shouldPropagateTraceHeaders=shouldPropagateTraceHeaders},{"./enums/PerformanceTimingNames":148,"@opentelemetry/core":57,"@opentelemetry/semantic-conventions":152}],152:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./trace"),exports);__exportStar(require("./resource"),exports)},{"./resource":154,"./trace":156}],153:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TelemetrySdkLanguageValues=exports.OsTypeValues=exports.HostArchValues=exports.AwsEcsLaunchtypeValues=exports.CloudPlatformValues=exports.CloudProviderValues=exports.SemanticResourceAttributes=void 0;exports.SemanticResourceAttributes={CLOUD_PROVIDER:"cloud.provider",CLOUD_ACCOUNT_ID:"cloud.account.id",CLOUD_REGION:"cloud.region",CLOUD_AVAILABILITY_ZONE:"cloud.availability_zone",CLOUD_PLATFORM:"cloud.platform",AWS_ECS_CONTAINER_ARN:"aws.ecs.container.arn",AWS_ECS_CLUSTER_ARN:"aws.ecs.cluster.arn",AWS_ECS_LAUNCHTYPE:"aws.ecs.launchtype",AWS_ECS_TASK_ARN:"aws.ecs.task.arn",AWS_ECS_TASK_FAMILY:"aws.ecs.task.family",AWS_ECS_TASK_REVISION:"aws.ecs.task.revision",AWS_EKS_CLUSTER_ARN:"aws.eks.cluster.arn",AWS_LOG_GROUP_NAMES:"aws.log.group.names",AWS_LOG_GROUP_ARNS:"aws.log.group.arns",AWS_LOG_STREAM_NAMES:"aws.log.stream.names",AWS_LOG_STREAM_ARNS:"aws.log.stream.arns",CONTAINER_NAME:"container.name",CONTAINER_ID:"container.id",CONTAINER_RUNTIME:"container.runtime",CONTAINER_IMAGE_NAME:"container.image.name",CONTAINER_IMAGE_TAG:"container.image.tag",DEPLOYMENT_ENVIRONMENT:"deployment.environment",DEVICE_ID:"device.id",DEVICE_MODEL_IDENTIFIER:"device.model.identifier",DEVICE_MODEL_NAME:"device.model.name",FAAS_NAME:"faas.name",FAAS_ID:"faas.id",FAAS_VERSION:"faas.version",FAAS_INSTANCE:"faas.instance",FAAS_MAX_MEMORY:"faas.max_memory",HOST_ID:"host.id",HOST_NAME:"host.name",HOST_TYPE:"host.type",HOST_ARCH:"host.arch",HOST_IMAGE_NAME:"host.image.name",HOST_IMAGE_ID:"host.image.id",HOST_IMAGE_VERSION:"host.image.version",K8S_CLUSTER_NAME:"k8s.cluster.name",K8S_NODE_NAME:"k8s.node.name",K8S_NODE_UID:"k8s.node.uid",K8S_NAMESPACE_NAME:"k8s.namespace.name",K8S_POD_UID:"k8s.pod.uid",K8S_POD_NAME:"k8s.pod.name",K8S_CONTAINER_NAME:"k8s.container.name",K8S_REPLICASET_UID:"k8s.replicaset.uid",K8S_REPLICASET_NAME:"k8s.replicaset.name",K8S_DEPLOYMENT_UID:"k8s.deployment.uid",K8S_DEPLOYMENT_NAME:"k8s.deployment.name",K8S_STATEFULSET_UID:"k8s.statefulset.uid",K8S_STATEFULSET_NAME:"k8s.statefulset.name",K8S_DAEMONSET_UID:"k8s.daemonset.uid",K8S_DAEMONSET_NAME:"k8s.daemonset.name",K8S_JOB_UID:"k8s.job.uid",K8S_JOB_NAME:"k8s.job.name",K8S_CRONJOB_UID:"k8s.cronjob.uid",K8S_CRONJOB_NAME:"k8s.cronjob.name",OS_TYPE:"os.type",OS_DESCRIPTION:"os.description",OS_NAME:"os.name",OS_VERSION:"os.version",PROCESS_PID:"process.pid",PROCESS_EXECUTABLE_NAME:"process.executable.name",PROCESS_EXECUTABLE_PATH:"process.executable.path",PROCESS_COMMAND:"process.command",PROCESS_COMMAND_LINE:"process.command_line",PROCESS_COMMAND_ARGS:"process.command_args",PROCESS_OWNER:"process.owner",PROCESS_RUNTIME_NAME:"process.runtime.name",PROCESS_RUNTIME_VERSION:"process.runtime.version",PROCESS_RUNTIME_DESCRIPTION:"process.runtime.description",SERVICE_NAME:"service.name",SERVICE_NAMESPACE:"service.namespace",SERVICE_INSTANCE_ID:"service.instance.id",SERVICE_VERSION:"service.version",TELEMETRY_SDK_NAME:"telemetry.sdk.name",TELEMETRY_SDK_LANGUAGE:"telemetry.sdk.language",TELEMETRY_SDK_VERSION:"telemetry.sdk.version",TELEMETRY_AUTO_VERSION:"telemetry.auto.version",WEBENGINE_NAME:"webengine.name",WEBENGINE_VERSION:"webengine.version",WEBENGINE_DESCRIPTION:"webengine.description"};exports.CloudProviderValues={ALIBABA_CLOUD:"alibaba_cloud",AWS:"aws",AZURE:"azure",GCP:"gcp"};exports.CloudPlatformValues={ALIBABA_CLOUD_ECS:"alibaba_cloud_ecs",ALIBABA_CLOUD_FC:"alibaba_cloud_fc",AWS_EC2:"aws_ec2",AWS_ECS:"aws_ecs",AWS_EKS:"aws_eks",AWS_LAMBDA:"aws_lambda",AWS_ELASTIC_BEANSTALK:"aws_elastic_beanstalk",AZURE_VM:"azure_vm",AZURE_CONTAINER_INSTANCES:"azure_container_instances",AZURE_AKS:"azure_aks",AZURE_FUNCTIONS:"azure_functions",AZURE_APP_SERVICE:"azure_app_service",GCP_COMPUTE_ENGINE:"gcp_compute_engine",GCP_CLOUD_RUN:"gcp_cloud_run",GCP_KUBERNETES_ENGINE:"gcp_kubernetes_engine",GCP_CLOUD_FUNCTIONS:"gcp_cloud_functions",GCP_APP_ENGINE:"gcp_app_engine"};exports.AwsEcsLaunchtypeValues={EC2:"ec2",FARGATE:"fargate"};exports.HostArchValues={AMD64:"amd64",ARM32:"arm32",ARM64:"arm64",IA64:"ia64",PPC32:"ppc32",PPC64:"ppc64",X86:"x86"};exports.OsTypeValues={WINDOWS:"windows",LINUX:"linux",DARWIN:"darwin",FREEBSD:"freebsd",NETBSD:"netbsd",OPENBSD:"openbsd",DRAGONFLYBSD:"dragonflybsd",HPUX:"hpux",AIX:"aix",SOLARIS:"solaris",Z_OS:"z_os"};exports.TelemetrySdkLanguageValues={CPP:"cpp",DOTNET:"dotnet",ERLANG:"erlang",GO:"go",JAVA:"java",NODEJS:"nodejs",PHP:"php",PYTHON:"python",RUBY:"ruby",WEBJS:"webjs"}},{}],154:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./SemanticResourceAttributes"),exports)},{"./SemanticResourceAttributes":153}],155:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MessageTypeValues=exports.RpcGrpcStatusCodeValues=exports.MessagingOperationValues=exports.MessagingDestinationKindValues=exports.HttpFlavorValues=exports.NetHostConnectionSubtypeValues=exports.NetHostConnectionTypeValues=exports.NetTransportValues=exports.FaasInvokedProviderValues=exports.FaasDocumentOperationValues=exports.FaasTriggerValues=exports.DbCassandraConsistencyLevelValues=exports.DbSystemValues=exports.SemanticAttributes=void 0;exports.SemanticAttributes={AWS_LAMBDA_INVOKED_ARN:"aws.lambda.invoked_arn",DB_SYSTEM:"db.system",DB_CONNECTION_STRING:"db.connection_string",DB_USER:"db.user",DB_JDBC_DRIVER_CLASSNAME:"db.jdbc.driver_classname",DB_NAME:"db.name",DB_STATEMENT:"db.statement",DB_OPERATION:"db.operation",DB_MSSQL_INSTANCE_NAME:"db.mssql.instance_name",DB_CASSANDRA_KEYSPACE:"db.cassandra.keyspace",DB_CASSANDRA_PAGE_SIZE:"db.cassandra.page_size",DB_CASSANDRA_CONSISTENCY_LEVEL:"db.cassandra.consistency_level",DB_CASSANDRA_TABLE:"db.cassandra.table",DB_CASSANDRA_IDEMPOTENCE:"db.cassandra.idempotence",DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT:"db.cassandra.speculative_execution_count",DB_CASSANDRA_COORDINATOR_ID:"db.cassandra.coordinator.id",DB_CASSANDRA_COORDINATOR_DC:"db.cassandra.coordinator.dc",DB_HBASE_NAMESPACE:"db.hbase.namespace",DB_REDIS_DATABASE_INDEX:"db.redis.database_index",DB_MONGODB_COLLECTION:"db.mongodb.collection",DB_SQL_TABLE:"db.sql.table",EXCEPTION_TYPE:"exception.type",EXCEPTION_MESSAGE:"exception.message",EXCEPTION_STACKTRACE:"exception.stacktrace",EXCEPTION_ESCAPED:"exception.escaped",FAAS_TRIGGER:"faas.trigger",FAAS_EXECUTION:"faas.execution",FAAS_DOCUMENT_COLLECTION:"faas.document.collection",FAAS_DOCUMENT_OPERATION:"faas.document.operation",FAAS_DOCUMENT_TIME:"faas.document.time",FAAS_DOCUMENT_NAME:"faas.document.name",FAAS_TIME:"faas.time",FAAS_CRON:"faas.cron",FAAS_COLDSTART:"faas.coldstart",FAAS_INVOKED_NAME:"faas.invoked_name",FAAS_INVOKED_PROVIDER:"faas.invoked_provider",FAAS_INVOKED_REGION:"faas.invoked_region",NET_TRANSPORT:"net.transport",NET_PEER_IP:"net.peer.ip",NET_PEER_PORT:"net.peer.port",NET_PEER_NAME:"net.peer.name",NET_HOST_IP:"net.host.ip",NET_HOST_PORT:"net.host.port",NET_HOST_NAME:"net.host.name",NET_HOST_CONNECTION_TYPE:"net.host.connection.type",NET_HOST_CONNECTION_SUBTYPE:"net.host.connection.subtype",NET_HOST_CARRIER_NAME:"net.host.carrier.name",NET_HOST_CARRIER_MCC:"net.host.carrier.mcc",NET_HOST_CARRIER_MNC:"net.host.carrier.mnc",NET_HOST_CARRIER_ICC:"net.host.carrier.icc",PEER_SERVICE:"peer.service",ENDUSER_ID:"enduser.id",ENDUSER_ROLE:"enduser.role",ENDUSER_SCOPE:"enduser.scope",THREAD_ID:"thread.id",THREAD_NAME:"thread.name",CODE_FUNCTION:"code.function",CODE_NAMESPACE:"code.namespace",CODE_FILEPATH:"code.filepath",CODE_LINENO:"code.lineno",HTTP_METHOD:"http.method",HTTP_URL:"http.url",HTTP_TARGET:"http.target",HTTP_HOST:"http.host",HTTP_SCHEME:"http.scheme",HTTP_STATUS_CODE:"http.status_code",HTTP_FLAVOR:"http.flavor",HTTP_USER_AGENT:"http.user_agent",HTTP_REQUEST_CONTENT_LENGTH:"http.request_content_length",HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED:"http.request_content_length_uncompressed",HTTP_RESPONSE_CONTENT_LENGTH:"http.response_content_length",HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED:"http.response_content_length_uncompressed",HTTP_SERVER_NAME:"http.server_name",HTTP_ROUTE:"http.route",HTTP_CLIENT_IP:"http.client_ip",AWS_DYNAMODB_TABLE_NAMES:"aws.dynamodb.table_names",AWS_DYNAMODB_CONSUMED_CAPACITY:"aws.dynamodb.consumed_capacity",AWS_DYNAMODB_ITEM_COLLECTION_METRICS:"aws.dynamodb.item_collection_metrics",AWS_DYNAMODB_PROVISIONED_READ_CAPACITY:"aws.dynamodb.provisioned_read_capacity",AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY:"aws.dynamodb.provisioned_write_capacity",AWS_DYNAMODB_CONSISTENT_READ:"aws.dynamodb.consistent_read",AWS_DYNAMODB_PROJECTION:"aws.dynamodb.projection",AWS_DYNAMODB_LIMIT:"aws.dynamodb.limit",AWS_DYNAMODB_ATTRIBUTES_TO_GET:"aws.dynamodb.attributes_to_get",AWS_DYNAMODB_INDEX_NAME:"aws.dynamodb.index_name",AWS_DYNAMODB_SELECT:"aws.dynamodb.select",AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES:"aws.dynamodb.global_secondary_indexes",AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES:"aws.dynamodb.local_secondary_indexes",AWS_DYNAMODB_EXCLUSIVE_START_TABLE:"aws.dynamodb.exclusive_start_table",AWS_DYNAMODB_TABLE_COUNT:"aws.dynamodb.table_count",AWS_DYNAMODB_SCAN_FORWARD:"aws.dynamodb.scan_forward",AWS_DYNAMODB_SEGMENT:"aws.dynamodb.segment",AWS_DYNAMODB_TOTAL_SEGMENTS:"aws.dynamodb.total_segments",AWS_DYNAMODB_COUNT:"aws.dynamodb.count",AWS_DYNAMODB_SCANNED_COUNT:"aws.dynamodb.scanned_count",AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS:"aws.dynamodb.attribute_definitions",AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES:"aws.dynamodb.global_secondary_index_updates",MESSAGING_SYSTEM:"messaging.system",MESSAGING_DESTINATION:"messaging.destination",MESSAGING_DESTINATION_KIND:"messaging.destination_kind",MESSAGING_TEMP_DESTINATION:"messaging.temp_destination",MESSAGING_PROTOCOL:"messaging.protocol",MESSAGING_PROTOCOL_VERSION:"messaging.protocol_version",MESSAGING_URL:"messaging.url",MESSAGING_MESSAGE_ID:"messaging.message_id",MESSAGING_CONVERSATION_ID:"messaging.conversation_id",MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES:"messaging.message_payload_size_bytes",MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES:"messaging.message_payload_compressed_size_bytes",MESSAGING_OPERATION:"messaging.operation",MESSAGING_CONSUMER_ID:"messaging.consumer_id",MESSAGING_RABBITMQ_ROUTING_KEY:"messaging.rabbitmq.routing_key",MESSAGING_KAFKA_MESSAGE_KEY:"messaging.kafka.message_key",MESSAGING_KAFKA_CONSUMER_GROUP:"messaging.kafka.consumer_group",MESSAGING_KAFKA_CLIENT_ID:"messaging.kafka.client_id",MESSAGING_KAFKA_PARTITION:"messaging.kafka.partition",MESSAGING_KAFKA_TOMBSTONE:"messaging.kafka.tombstone",RPC_SYSTEM:"rpc.system",RPC_SERVICE:"rpc.service",RPC_METHOD:"rpc.method",RPC_GRPC_STATUS_CODE:"rpc.grpc.status_code",RPC_JSONRPC_VERSION:"rpc.jsonrpc.version",RPC_JSONRPC_REQUEST_ID:"rpc.jsonrpc.request_id",RPC_JSONRPC_ERROR_CODE:"rpc.jsonrpc.error_code",RPC_JSONRPC_ERROR_MESSAGE:"rpc.jsonrpc.error_message",MESSAGE_TYPE:"message.type",MESSAGE_ID:"message.id",MESSAGE_COMPRESSED_SIZE:"message.compressed_size",MESSAGE_UNCOMPRESSED_SIZE:"message.uncompressed_size"};exports.DbSystemValues={OTHER_SQL:"other_sql",MSSQL:"mssql",MYSQL:"mysql",ORACLE:"oracle",DB2:"db2",POSTGRESQL:"postgresql",REDSHIFT:"redshift",HIVE:"hive",CLOUDSCAPE:"cloudscape",HSQLDB:"hsqldb",PROGRESS:"progress",MAXDB:"maxdb",HANADB:"hanadb",INGRES:"ingres",FIRSTSQL:"firstsql",EDB:"edb",CACHE:"cache",ADABAS:"adabas",FIREBIRD:"firebird",DERBY:"derby",FILEMAKER:"filemaker",INFORMIX:"informix",INSTANTDB:"instantdb",INTERBASE:"interbase",MARIADB:"mariadb",NETEZZA:"netezza",PERVASIVE:"pervasive",POINTBASE:"pointbase",SQLITE:"sqlite",SYBASE:"sybase",TERADATA:"teradata",VERTICA:"vertica",H2:"h2",COLDFUSION:"coldfusion",CASSANDRA:"cassandra",HBASE:"hbase",MONGODB:"mongodb",REDIS:"redis",COUCHBASE:"couchbase",COUCHDB:"couchdb",COSMOSDB:"cosmosdb",DYNAMODB:"dynamodb",NEO4J:"neo4j",GEODE:"geode",ELASTICSEARCH:"elasticsearch",MEMCACHED:"memcached",COCKROACHDB:"cockroachdb"};exports.DbCassandraConsistencyLevelValues={ALL:"all",EACH_QUORUM:"each_quorum",QUORUM:"quorum",LOCAL_QUORUM:"local_quorum",ONE:"one",TWO:"two",THREE:"three",LOCAL_ONE:"local_one",ANY:"any",SERIAL:"serial",LOCAL_SERIAL:"local_serial"};exports.FaasTriggerValues={DATASOURCE:"datasource",HTTP:"http",PUBSUB:"pubsub",TIMER:"timer",OTHER:"other"};exports.FaasDocumentOperationValues={INSERT:"insert",EDIT:"edit",DELETE:"delete"};exports.FaasInvokedProviderValues={ALIBABA_CLOUD:"alibaba_cloud",AWS:"aws",AZURE:"azure",GCP:"gcp"};exports.NetTransportValues={IP_TCP:"ip_tcp",IP_UDP:"ip_udp",IP:"ip",UNIX:"unix",PIPE:"pipe",INPROC:"inproc",OTHER:"other"};exports.NetHostConnectionTypeValues={WIFI:"wifi",WIRED:"wired",CELL:"cell",UNAVAILABLE:"unavailable",UNKNOWN:"unknown"};exports.NetHostConnectionSubtypeValues={GPRS:"gprs",EDGE:"edge",UMTS:"umts",CDMA:"cdma",EVDO_0:"evdo_0",EVDO_A:"evdo_a",CDMA2000_1XRTT:"cdma2000_1xrtt",HSDPA:"hsdpa",HSUPA:"hsupa",HSPA:"hspa",IDEN:"iden",EVDO_B:"evdo_b",LTE:"lte",EHRPD:"ehrpd",HSPAP:"hspap",GSM:"gsm",TD_SCDMA:"td_scdma",IWLAN:"iwlan",NR:"nr",NRNSA:"nrnsa",LTE_CA:"lte_ca"};exports.HttpFlavorValues={HTTP_1_0:"1.0",HTTP_1_1:"1.1",HTTP_2_0:"2.0",SPDY:"SPDY",QUIC:"QUIC"};exports.MessagingDestinationKindValues={QUEUE:"queue",TOPIC:"topic"};exports.MessagingOperationValues={RECEIVE:"receive",PROCESS:"process"};exports.RpcGrpcStatusCodeValues={OK:0,CANCELLED:1,UNKNOWN:2,INVALID_ARGUMENT:3,DEADLINE_EXCEEDED:4,NOT_FOUND:5,ALREADY_EXISTS:6,PERMISSION_DENIED:7,RESOURCE_EXHAUSTED:8,FAILED_PRECONDITION:9,ABORTED:10,OUT_OF_RANGE:11,UNIMPLEMENTED:12,INTERNAL:13,UNAVAILABLE:14,DATA_LOSS:15,UNAUTHENTICATED:16};exports.MessageTypeValues={SENT:"SENT",RECEIVED:"RECEIVED"}},{}],156:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./SemanticAttributes"),exports)},{"./SemanticAttributes":155}],157:[function(require,module,exports){},{}],158:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],159:[function(require,module,exports){"use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols;var hasOwnProperty=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(val)}function shouldUseNative(){try{if(!Object.assign){return false}var test1=new String("abc");test1[5]="de";if(Object.getOwnPropertyNames(test1)[0]==="5"){return false}var test2={};for(var i=0;i<10;i++){test2["_"+String.fromCharCode(i)]=i}var order2=Object.getOwnPropertyNames(test2).map(function(n){return test2[n]});if(order2.join("")!=="0123456789"){return false}var test3={};"abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter});if(Object.keys(Object.assign({},test3)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(err){return false}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s<arguments.length;s++){from=Object(arguments[s]);for(var key in from){if(hasOwnProperty.call(from,key)){to[key]=from[key]}}if(getOwnPropertySymbols){symbols=getOwnPropertySymbols(from);for(var i=0;i<symbols.length;i++){if(propIsEnumerable.call(from,symbols[i])){to[symbols[i]]=from[symbols[i]]}}}}return to}},{}],160:[function(require,module,exports){exports.endianness=function(){return"LE"};exports.hostname=function(){if(typeof location!=="undefined"){return location.hostname}else return""};exports.loadavg=function(){return[]};exports.uptime=function(){return 0};exports.freemem=function(){return Number.MAX_VALUE};exports.totalmem=function(){return Number.MAX_VALUE};exports.cpus=function(){return[]};exports.type=function(){return"Browser"};exports.release=function(){if(typeof navigator!=="undefined"){return navigator.appVersion}return""};exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}};exports.arch=function(){return"javascript"};exports.platform=function(){return"browser"};exports.tmpdir=exports.tmpDir=function(){return"/tmp"};exports.EOL="\n"},{}],161:[function(require,module,exports){(function(process){(function(){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){if(typeof path!=="string")path=path+"";if(path.length===0)return".";var code=path.charCodeAt(0);var hasRoot=code===47;var end=-1;var matchedSlash=true;for(var i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){return"/"}return path.slice(0,end)};function basename(path){if(typeof path!=="string")path=path+"";var start=0;var end=-1;var matchedSlash=true;var i;for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}exports.basename=function(path,ext){var f=basename(path);if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){if(typeof path!=="string")path=path+"";var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this)}).call(this,require("_process"))},{_process:162}],162:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[]};process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],163:[function(require,module,exports){"use strict";function isFunction(funktion){return typeof funktion==="function"}var logger=console.error.bind(console);function defineProperty(obj,name,value){var enumerable=!!obj[name]&&obj.propertyIsEnumerable(name);Object.defineProperty(obj,name,{configurable:true,enumerable:enumerable,writable:true,value:value})}function shimmer(options){if(options&&options.logger){if(!isFunction(options.logger))logger("new logger isn't a function, not replacing");else logger=options.logger}}function wrap(nodule,name,wrapper){if(!nodule||!nodule[name]){logger("no original function "+name+" to wrap");return}if(!wrapper){logger("no wrapper function");logger((new Error).stack);return}if(!isFunction(nodule[name])||!isFunction(wrapper)){logger("original object and wrapper must be functions");return}var original=nodule[name];var wrapped=wrapper(original,name);defineProperty(wrapped,"__original",original);defineProperty(wrapped,"__unwrap",function(){if(nodule[name]===wrapped)defineProperty(nodule,name,original)});defineProperty(wrapped,"__wrapped",true);defineProperty(nodule,name,wrapped);return wrapped}function massWrap(nodules,names,wrapper){if(!nodules){logger("must provide one or more modules to patch");logger((new Error).stack);return}else if(!Array.isArray(nodules)){nodules=[nodules]}if(!(names&&Array.isArray(names))){logger("must provide one or more functions to wrap on modules");return}nodules.forEach(function(nodule){names.forEach(function(name){wrap(nodule,name,wrapper)})})}function unwrap(nodule,name){if(!nodule||!nodule[name]){logger("no function to unwrap.");logger((new Error).stack);return}if(!nodule[name].__unwrap){logger("no original to unwrap to -- has "+name+" already been unwrapped?")}else{return nodule[name].__unwrap()}}function massUnwrap(nodules,names){if(!nodules){logger("must provide one or more modules to patch");logger((new Error).stack);return}else if(!Array.isArray(nodules)){nodules=[nodules]}if(!(names&&Array.isArray(names))){logger("must provide one or more functions to unwrap on modules");return}nodules.forEach(function(nodule){names.forEach(function(name){unwrap(nodule,name)})})}shimmer.wrap=wrap;shimmer.massWrap=massWrap;shimmer.unwrap=unwrap;shimmer.massUnwrap=massUnwrap;module.exports=shimmer},{}],164:[function(require,module,exports){var util=require("./util");var has=Object.prototype.hasOwnProperty;var hasNativeMap=typeof Map!=="undefined";function ArraySet(){this._array=[];this._set=hasNativeMap?new Map:Object.create(null)}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.size=function ArraySet_size(){return hasNativeMap?this._set.size:Object.getOwnPropertyNames(this._set).length};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var sStr=hasNativeMap?aStr:util.toSetString(aStr);var isDuplicate=hasNativeMap?this.has(aStr):has.call(this._set,sStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){if(hasNativeMap){this._set.set(aStr,idx)}else{this._set[sStr]=idx}}};ArraySet.prototype.has=function ArraySet_has(aStr){if(hasNativeMap){return this._set.has(aStr)}else{var sStr=util.toSetString(aStr);return has.call(this._set,sStr)}};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(hasNativeMap){var idx=this._set.get(aStr);if(idx>=0){return idx}}else{var sStr=util.toSetString(aStr);if(has.call(this._set,sStr)){return this._set[sStr]}}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet},{"./util":173}],165:[function(require,module,exports){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aIndex,aOutParam){var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(aIndex>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charCodeAt(aIndex++));if(digit===-1){throw new Error("Invalid base64 digit: "+aStr.charAt(aIndex-1))}continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aIndex}},{"./base64":166}],166:[function(require,module,exports){var intToCharMap="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");exports.encode=function(number){if(0<=number&&number<intToCharMap.length){return intToCharMap[number]}throw new TypeError("Must be between 0 and 63: "+number)};exports.decode=function(charCode){var bigA=65;var bigZ=90;var littleA=97;var littleZ=122;var zero=48;var nine=57;var plus=43;var slash=47;var littleOffset=26;var numberOffset=52;if(bigA<=charCode&&charCode<=bigZ){return charCode-bigA}if(littleA<=charCode&&charCode<=littleZ){return charCode-littleA+littleOffset}if(zero<=charCode&&charCode<=nine){return charCode-zero+numberOffset}if(charCode==plus){return 62}if(charCode==slash){return 63}return-1}},{}],167:[function(require,module,exports){exports.GREATEST_LOWER_BOUND=1;exports.LEAST_UPPER_BOUND=2;function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare,aBias){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare,aBias)}if(aBias==exports.LEAST_UPPER_BOUND){return aHigh<aHaystack.length?aHigh:-1}else{return mid}}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare,aBias)}if(aBias==exports.LEAST_UPPER_BOUND){return mid}else{return aLow<0?-1:aLow}}}exports.search=function search(aNeedle,aHaystack,aCompare,aBias){if(aHaystack.length===0){return-1}var index=recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare,aBias||exports.GREATEST_LOWER_BOUND);if(index<0){return-1}while(index-1>=0){if(aCompare(aHaystack[index],aHaystack[index-1],true)!==0){break}--index}return index}},{}],168:[function(require,module,exports){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine;var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositionsInflated(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositionsInflated);this._sorted=true}return this._array};exports.MappingList=MappingList},{"./util":173}],169:[function(require,module,exports){function swap(ary,x,y){var temp=ary[x];ary[x]=ary[y];ary[y]=temp}function randomIntInRange(low,high){return Math.round(low+Math.random()*(high-low))}function doQuickSort(ary,comparator,p,r){if(p<r){var pivotIndex=randomIntInRange(p,r);var i=p-1;swap(ary,pivotIndex,r);var pivot=ary[r];for(var j=p;j<r;j++){if(comparator(ary[j],pivot)<=0){i+=1;swap(ary,i,j)}}swap(ary,i+1,j);var q=i+1;doQuickSort(ary,comparator,p,q-1);doQuickSort(ary,comparator,q+1,r)}}exports.quickSort=function(ary,comparator){doQuickSort(ary,comparator,0,ary.length-1)}},{}],170:[function(require,module,exports){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");var quickSort=require("./quick-sort").quickSort;function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}return sourceMap.sections!=null?new IndexedSourceMapConsumer(sourceMap):new BasicSourceMapConsumer(sourceMap)}SourceMapConsumer.fromSourceMap=function(aSourceMap){return BasicSourceMapConsumer.fromSourceMap(aSourceMap)};SourceMapConsumer.prototype._version=3;SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._charIsMappingSeparator=function SourceMapConsumer_charIsMappingSeparator(aStr,index){var c=aStr.charAt(index);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){throw new Error("Subclasses must implement _parseMappings")};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.GREATEST_LOWER_BOUND=1;SourceMapConsumer.LEAST_UPPER_BOUND=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source===null?null:this._sources.at(mapping.source);if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name===null?null:this._names.at(mapping.name)}},this).forEach(aCallback,context)};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var line=util.getArg(aArgs,"line");var needle={source:util.getArg(aArgs,"source"),originalLine:line,originalColumn:util.getArg(aArgs,"column",0)};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}if(!this._sources.has(needle.source)){return[]}needle.source=this._sources.indexOf(needle.source);var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions,binarySearch.LEAST_UPPER_BOUND);if(index>=0){var mapping=this._originalMappings[index];if(aArgs.column===undefined){var originalLine=mapping.originalLine;while(mapping&&mapping.originalLine===originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[++index]}}else{var originalColumn=mapping.originalColumn;while(mapping&&mapping.originalLine===line&&mapping.originalColumn==originalColumn){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[++index]}}}return mappings};exports.SourceMapConsumer=SourceMapConsumer;function BasicSourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(String).map(util.normalize).map(function(source){return sourceRoot&&util.isAbsolute(sourceRoot)&&util.isAbsolute(source)?util.relative(sourceRoot,source):source});this._names=ArraySet.fromArray(names.map(String),true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}BasicSourceMapConsumer.prototype=Object.create(SourceMapConsumer.prototype);BasicSourceMapConsumer.prototype.consumer=SourceMapConsumer;BasicSourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(BasicSourceMapConsumer.prototype);var names=smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);var sources=smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;var generatedMappings=aSourceMap._mappings.toArray().slice();var destGeneratedMappings=smc.__generatedMappings=[];var destOriginalMappings=smc.__originalMappings=[];for(var i=0,length=generatedMappings.length;i<length;i++){var srcMapping=generatedMappings[i];var destMapping=new Mapping;destMapping.generatedLine=srcMapping.generatedLine;destMapping.generatedColumn=srcMapping.generatedColumn;if(srcMapping.source){destMapping.source=sources.indexOf(srcMapping.source);destMapping.originalLine=srcMapping.originalLine;destMapping.originalColumn=srcMapping.originalColumn;if(srcMapping.name){destMapping.name=names.indexOf(srcMapping.name)}destOriginalMappings.push(destMapping)}destGeneratedMappings.push(destMapping)}quickSort(smc.__originalMappings,util.compareByOriginalPositions);return smc};BasicSourceMapConsumer.prototype._version=3;Object.defineProperty(BasicSourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});function Mapping(){this.generatedLine=0;this.generatedColumn=0;this.source=null;this.originalLine=null;this.originalColumn=null;this.name=null}BasicSourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var length=aStr.length;var index=0;var cachedSegments={};var temp={};var originalMappings=[];var generatedMappings=[];var mapping,str,segment,end,value;while(index<length){if(aStr.charAt(index)===";"){generatedLine++;index++;previousGeneratedColumn=0}else if(aStr.charAt(index)===","){index++}else{mapping=new Mapping;mapping.generatedLine=generatedLine;for(end=index;end<length;end++){if(this._charIsMappingSeparator(aStr,end)){break}}str=aStr.slice(index,end);segment=cachedSegments[str];if(segment){index+=str.length}else{segment=[];while(index<end){base64VLQ.decode(aStr,index,temp);value=temp.value;index=temp.rest;segment.push(value)}if(segment.length===2){throw new Error("Found a source, but no line and column")}if(segment.length===3){throw new Error("Found a source and line, but no column")}cachedSegments[str]=segment}mapping.generatedColumn=previousGeneratedColumn+segment[0];previousGeneratedColumn=mapping.generatedColumn;if(segment.length>1){mapping.source=previousSource+segment[1];previousSource+=segment[1];mapping.originalLine=previousOriginalLine+segment[2];previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;mapping.originalColumn=previousOriginalColumn+segment[3];previousOriginalColumn=mapping.originalColumn;if(segment.length>4){mapping.name=previousName+segment[4];previousName+=segment[4]}}generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){originalMappings.push(mapping)}}}quickSort(generatedMappings,util.compareByGeneratedPositionsDeflated);this.__generatedMappings=generatedMappings;quickSort(originalMappings,util.compareByOriginalPositions);this.__originalMappings=originalMappings};BasicSourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator,aBias){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator,aBias)};BasicSourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};BasicSourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositionsDeflated,util.getArg(aArgs,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND));if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!==null){source=this._sources.at(source);if(this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}}var name=util.getArg(mapping,"name",null);if(name!==null){name=this._names.at(name)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:name}}}return{source:null,line:null,column:null,name:null}};BasicSourceMapConsumer.prototype.hasContentsOfAllSources=function BasicSourceMapConsumer_hasContentsOfAllSources(){if(!this.sourcesContent){return false}return this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(sc){return sc==null})};BasicSourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource,nullOnMissing){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}if(nullOnMissing){return null}else{throw new Error('"'+aSource+'" is not in the SourceMap.')}};BasicSourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var source=util.getArg(aArgs,"source");if(this.sourceRoot!=null){source=util.relative(this.sourceRoot,source)}if(!this._sources.has(source)){return{line:null,column:null,lastColumn:null}}source=this._sources.indexOf(source);var needle={source:source,originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions,util.getArg(aArgs,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND));if(index>=0){var mapping=this._originalMappings[index];if(mapping.source===needle.source){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}}return{line:null,column:null,lastColumn:null}};exports.BasicSourceMapConsumer=BasicSourceMapConsumer;function IndexedSourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sections=util.getArg(sourceMap,"sections");if(version!=this._version){throw new Error("Unsupported version: "+version)}this._sources=new ArraySet;this._names=new ArraySet;var lastOffset={line:-1,column:0};this._sections=sections.map(function(s){if(s.url){throw new Error("Support for url field in sections not implemented.")}var offset=util.getArg(s,"offset");var offsetLine=util.getArg(offset,"line");var offsetColumn=util.getArg(offset,"column");if(offsetLine<lastOffset.line||offsetLine===lastOffset.line&&offsetColumn<lastOffset.column){throw new Error("Section offsets must be ordered and non-overlapping.")}lastOffset=offset;return{generatedOffset:{generatedLine:offsetLine+1,generatedColumn:offsetColumn+1},consumer:new SourceMapConsumer(util.getArg(s,"map"))}})}IndexedSourceMapConsumer.prototype=Object.create(SourceMapConsumer.prototype);IndexedSourceMapConsumer.prototype.constructor=SourceMapConsumer;IndexedSourceMapConsumer.prototype._version=3;Object.defineProperty(IndexedSourceMapConsumer.prototype,"sources",{get:function(){var sources=[];for(var i=0;i<this._sections.length;i++){for(var j=0;j<this._sections[i].consumer.sources.length;j++){sources.push(this._sections[i].consumer.sources[j])}}return sources}});IndexedSourceMapConsumer.prototype.originalPositionFor=function IndexedSourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var sectionIndex=binarySearch.search(needle,this._sections,function(needle,section){var cmp=needle.generatedLine-section.generatedOffset.generatedLine;if(cmp){return cmp}return needle.generatedColumn-section.generatedOffset.generatedColumn});var section=this._sections[sectionIndex];if(!section){return{source:null,line:null,column:null,name:null}}return section.consumer.originalPositionFor({line:needle.generatedLine-(section.generatedOffset.generatedLine-1),column:needle.generatedColumn-(section.generatedOffset.generatedLine===needle.generatedLine?section.generatedOffset.generatedColumn-1:0),bias:aArgs.bias})};IndexedSourceMapConsumer.prototype.hasContentsOfAllSources=function IndexedSourceMapConsumer_hasContentsOfAllSources(){return this._sections.every(function(s){return s.consumer.hasContentsOfAllSources()})};IndexedSourceMapConsumer.prototype.sourceContentFor=function IndexedSourceMapConsumer_sourceContentFor(aSource,nullOnMissing){for(var i=0;i<this._sections.length;i++){var section=this._sections[i];var content=section.consumer.sourceContentFor(aSource,true);if(content){return content}}if(nullOnMissing){return null}else{throw new Error('"'+aSource+'" is not in the SourceMap.')}};IndexedSourceMapConsumer.prototype.generatedPositionFor=function IndexedSourceMapConsumer_generatedPositionFor(aArgs){for(var i=0;i<this._sections.length;i++){var section=this._sections[i];if(section.consumer.sources.indexOf(util.getArg(aArgs,"source"))===-1){continue}var generatedPosition=section.consumer.generatedPositionFor(aArgs);if(generatedPosition){var ret={line:generatedPosition.line+(section.generatedOffset.generatedLine-1),column:generatedPosition.column+(section.generatedOffset.generatedLine===generatedPosition.line?section.generatedOffset.generatedColumn-1:0)};return ret}}return{line:null,column:null}};IndexedSourceMapConsumer.prototype._parseMappings=function IndexedSourceMapConsumer_parseMappings(aStr,aSourceRoot){this.__generatedMappings=[];this.__originalMappings=[];for(var i=0;i<this._sections.length;i++){var section=this._sections[i];var sectionMappings=section.consumer._generatedMappings;for(var j=0;j<sectionMappings.length;j++){var mapping=sectionMappings[j];var source=section.consumer._sources.at(mapping.source);if(section.consumer.sourceRoot!==null){source=util.join(section.consumer.sourceRoot,source)}this._sources.add(source);source=this._sources.indexOf(source);var name=section.consumer._names.at(mapping.name);this._names.add(name);name=this._names.indexOf(name);var adjustedMapping={source:source,generatedLine:mapping.generatedLine+(section.generatedOffset.generatedLine-1),generatedColumn:mapping.generatedColumn+(section.generatedOffset.generatedLine===mapping.generatedLine?section.generatedOffset.generatedColumn-1:0),originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:name};this.__generatedMappings.push(adjustedMapping);if(typeof adjustedMapping.originalLine==="number"){this.__originalMappings.push(adjustedMapping)}}}quickSort(this.__generatedMappings,util.compareByGeneratedPositionsDeflated);quickSort(this.__originalMappings,util.compareByOriginalPositions)};exports.IndexedSourceMapConsumer=IndexedSourceMapConsumer},{"./array-set":164,"./base64-vlq":165,"./binary-search":167,"./quick-sort":169,"./util":173}],171:[function(require,module,exports){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null){source=String(source);if(!this._sources.has(source)){this._sources.add(source)}}if(name!=null){name=String(name);if(!this._names.has(name)){this._names.add(name)}}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents=Object.create(null)}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aOriginal&&typeof aOriginal.line!=="number"&&typeof aOriginal.column!=="number"){throw new Error("original.line and original.column are not numbers -- you probably meant to omit "+"the original mapping entirely and only map the generated position. If so, pass "+"null for the original mapping instead of an object with empty or null values.")}if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var next;var mapping;var nameIdx;var sourceIdx;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];next="";if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){next+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositionsInflated(mapping,mappings[i-1])){continue}next+=","}}next+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){sourceIdx=this._sources.indexOf(mapping.source);next+=base64VLQ.encode(sourceIdx-previousSource);previousSource=sourceIdx;next+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;next+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){nameIdx=this._names.indexOf(mapping.name);next+=base64VLQ.encode(nameIdx-previousName);previousName=nameIdx}}result+=next}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this.toJSON())};exports.SourceMapGenerator=SourceMapGenerator},{"./array-set":164,"./base64-vlq":165,"./mapping-list":168,"./util":173}],172:[function(require,module,exports){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var remainingLinesIndex=0;var shiftNextLine=function(){var lineContents=getNextLine();var newLine=getNextLine()||"";return lineContents+newLine;function getNextLine(){return remainingLinesIndex<remainingLines.length?remainingLines[remainingLinesIndex++]:undefined}};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[remainingLinesIndex];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[remainingLinesIndex]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[remainingLinesIndex];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[remainingLinesIndex]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLinesIndex<remainingLines.length){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.splice(remainingLinesIndex).join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk[isSourceNode]||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode},{"./source-map-generator":171,"./util":173}],173:[function(require,module,exports){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=exports.isAbsolute(path);var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;exports.isAbsolute=function(aPath){return aPath.charAt(0)==="/"||!!aPath.match(urlRegexp)};function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var level=0;while(aPath.indexOf(aRoot+"/")!==0){var index=aRoot.lastIndexOf("/");if(index<0){return aPath}aRoot=aRoot.slice(0,index);if(aRoot.match(/^([^\/]+:\/)?\/*$/)){return aPath}++level}return Array(level+1).join("../")+aPath.substr(aRoot.length+1)}exports.relative=relative;var supportsNullProto=function(){var obj=Object.create(null);return!("__proto__"in obj)}();function identity(s){return s}function toSetString(aStr){if(isProtoString(aStr)){return"$"+aStr}return aStr}exports.toSetString=supportsNullProto?identity:toSetString;function fromSetString(aStr){if(isProtoString(aStr)){return aStr.slice(1)}return aStr}exports.fromSetString=supportsNullProto?identity:fromSetString;function isProtoString(s){if(!s){return false}var length=s.length;if(length<9){return false}if(s.charCodeAt(length-1)!==95||s.charCodeAt(length-2)!==95||s.charCodeAt(length-3)!==111||s.charCodeAt(length-4)!==116||s.charCodeAt(length-5)!==111||s.charCodeAt(length-6)!==114||s.charCodeAt(length-7)!==112||s.charCodeAt(length-8)!==95||s.charCodeAt(length-9)!==95){return false}for(var i=length-10;i>=0;i--){if(s.charCodeAt(i)!==36){return false}}return true}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp=mappingA.source-mappingB.source;if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0||onlyCompareOriginal){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}return mappingA.name-mappingB.name}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositionsDeflated(mappingA,mappingB,onlyCompareGenerated){var cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0||onlyCompareGenerated){return cmp}cmp=mappingA.source-mappingB.source;if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0){return cmp}return mappingA.name-mappingB.name}exports.compareByGeneratedPositionsDeflated=compareByGeneratedPositionsDeflated;function strcmp(aStr1,aStr2){if(aStr1===aStr2){return 0}if(aStr1>aStr2){return 1}return-1}function compareByGeneratedPositionsInflated(mappingA,mappingB){var cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp!==0){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp!==0){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp!==0){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp!==0){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp!==0){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositionsInflated=compareByGeneratedPositionsInflated},{}],174:[function(require,module,exports){exports.SourceMapGenerator=require("./lib/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./lib/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./lib/source-node").SourceNode},{"./lib/source-map-consumer":170,"./lib/source-map-generator":171,"./lib/source-node":172}],175:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./lib/feature-detection","./lib/config","./lib/browser-agent","./lib/configuration-override","./lib/events-bridge","./lib/logger/log-factory","./lib/events-bridge/context-message-manager"],factory)}})(function(require,exports){"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:true});const feature_detection_1=require("./lib/feature-detection");const config_1=require("./lib/config");const browser_agent_1=require("./lib/browser-agent");const configuration_override_1=require("./lib/configuration-override");const events_bridge_1=require("./lib/events-bridge");const log_factory_1=require("./lib/logger/log-factory");const context_message_manager_1=require("./lib/events-bridge/context-message-manager");const SEALIGHTS_WINDOW_OBJECT="$Sealights";const COMPONENTS="components";let featureDetection=null;try{featureDetection=new feature_detection_1.FeatureDetection(window);if((window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT])&&!((_a=window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT])===null||_a===void 0?void 0:_a.ctxPropagationOnly)){window[SEALIGHTS_WINDOW_OBJECT].configuration=configuration_override_1.ConfigurationOverride.create(window[SEALIGHTS_WINDOW_OBJECT].configuration);const browserAgent=new browser_agent_1.BrowserAgent(window,featureDetection);window["$SealightsAgent"]=browserAgent;window[SEALIGHTS_WINDOW_OBJECT].agentVersion=config_1.SL_AGENT_VERSION;if(window[SEALIGHTS_WINDOW_OBJECT]&&window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]){Object.keys(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS]).forEach(buildSessionId=>{browserAgent.createInstance(window[SEALIGHTS_WINDOW_OBJECT][COMPONENTS][buildSessionId])})}else{browserAgent.createInstance(window[SEALIGHTS_WINDOW_OBJECT])}let enableOpenTelemetry=false;Object.keys(window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT].components).forEach(instanceBSID=>{if(window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT].components[instanceBSID].enableOpenTelemetry){return enableOpenTelemetry=true}});let allowCORS=undefined;Object.keys(window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT].components).forEach(instanceBSID=>{const instanceCORSConfig=window===null||window===void 0?void 0:window[SEALIGHTS_WINDOW_OBJECT].components[instanceBSID].allowCORS;if(instanceCORSConfig===null||instanceCORSConfig===void 0?void 0:instanceCORSConfig.length){return allowCORS=instanceCORSConfig}});const logger=log_factory_1.LogFactory.createLogger("EventsBridgeLogger");(0,events_bridge_1.registerEventsBridge)(logger,enableOpenTelemetry,true,allowCORS);const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();Object.keys(window["$SealightsAgent"].instanceAddedForBsid).forEach(bsid=>{if(window["$SealightsAgent"].instanceAddedForBsid[bsid]){contextMessageManager.addSource({buildSessionId:bsid})}})}else if(window){window[SEALIGHTS_WINDOW_OBJECT]={configuration:undefined,enableContextPropagation:function(){const logger=log_factory_1.LogFactory.createLogger("SL-Agent");logger.info("Enabaling context propagation only");(0,events_bridge_1.registerEventsBridge)(logger,true,false)},ctxPropagationOnly:true}}}catch(e){if(featureDetection&&featureDetection.hasConsoleLogAPI()){console.log("Sealights browser listener failed to start. Error: ",e)}}})},{"./lib/browser-agent":179,"./lib/config":186,"./lib/configuration-override":188,"./lib/events-bridge":201,"./lib/events-bridge/context-message-manager":196,"./lib/feature-detection":204,"./lib/logger/log-factory":209}],176:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker","../../common/state-tracker-fpv6","../../common/no-op-state-tracker","./test-state-helper","./entities/environment-data","./services/http/http-client","./services/json/json-client","./istanbul-to-footprints-convertor","./istanbul-to-footprints-convertor-v3","./services/light-backend-proxy","./footprints-queue-sender","./watchdog","./code-coverage-manager","./queues/footprints-items-queue","./configuration-manager","./logger/log-factory","./basic-uuid-generator","./window-timers-wrapper","./queues/queue","./delegate","./services/json/json-client-adapter","./browser-events-process","./browser-hits-converter","./browser-agent-instance-fpv6","./browser-hits-collector","./sl-mapping-loader","./services/json/noop-json-client","../../common/agent-instance-data","../../common/agent-events/agent-events-contracts","../../common/agent-events/cockpit-notifier","../../common/http/backend-proxy","../../common/config-process/config-loader","../../common/footprints-process-v6/relative-path-resolver","../../common/footprints-process-v6/collector-footprints-buffer","../../common/footprints-process-v6/index","../../common/footprints-process-v6/collector-footprints-process","../../common/config-process","../../common/config-process/no-op-config-process","../../common/system-date","./browser-footprints-buffer","./color-context-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentFactory=void 0;const state_tracker_1=require("./state-tracker");const state_tracker_fpv6_1=require("../../common/state-tracker-fpv6");const no_op_state_tracker_1=require("../../common/no-op-state-tracker");const test_state_helper_1=require("./test-state-helper");const environment_data_1=require("./entities/environment-data");const http_client_1=require("./services/http/http-client");const json_client_1=require("./services/json/json-client");const istanbul_to_footprints_convertor_1=require("./istanbul-to-footprints-convertor");const istanbul_to_footprints_convertor_v3_1=require("./istanbul-to-footprints-convertor-v3");const light_backend_proxy_1=require("./services/light-backend-proxy");const footprints_queue_sender_1=require("./footprints-queue-sender");const watchdog_1=require("./watchdog");const code_coverage_manager_1=require("./code-coverage-manager");const footprints_items_queue_1=require("./queues/footprints-items-queue");const configuration_manager_1=require("./configuration-manager");const log_factory_1=require("./logger/log-factory");const basic_uuid_generator_1=require("./basic-uuid-generator");const window_timers_wrapper_1=require("./window-timers-wrapper");const queue_1=require("./queues/queue");const delegate_1=require("./delegate");const json_client_adapter_1=require("./services/json/json-client-adapter");const browser_events_process_1=require("./browser-events-process");const browser_hits_converter_1=require("./browser-hits-converter");const browser_agent_instance_fpv6_1=require("./browser-agent-instance-fpv6");const browser_hits_collector_1=require("./browser-hits-collector");const sl_mapping_loader_1=require("./sl-mapping-loader");const noop_json_client_1=require("./services/json/noop-json-client");const agent_instance_data_1=require("../../common/agent-instance-data");const agent_events_contracts_1=require("../../common/agent-events/agent-events-contracts");const cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");const backend_proxy_1=require("../../common/http/backend-proxy");const config_loader_1=require("../../common/config-process/config-loader");const relative_path_resolver_1=require("../../common/footprints-process-v6/relative-path-resolver");const collector_footprints_buffer_1=require("../../common/footprints-process-v6/collector-footprints-buffer");const index_1=require("../../common/footprints-process-v6/index");const collector_footprints_process_1=require("../../common/footprints-process-v6/collector-footprints-process");const config_process_1=require("../../common/config-process");const no_op_config_process_1=require("../../common/config-process/no-op-config-process");const system_date_1=require("../../common/system-date");const browser_footprints_buffer_1=require("./browser-footprints-buffer");const color_context_manager_1=require("./color-context-manager");const FOOTPRINTS_SENDER_WATCHDOG="FootPrintsSenderWatchdog";const FOOTPRINTS_FLUSH_WATCHDOG="FootprintsFlushWatchdog";const ACTIVE_EXECUTION_WATCHDOG="ActiveExecutionWatchdog";const KEEP_ALIVE_WATCHDOG="KeepaliveWatchdog";const CONFIGURATION_WATCHDOG="getConfigFromServerWatchdog";class AgentFactory{static createBrowserAgent(window,featureDetection,basicConfiguration){const configurationManager=AgentFactory.createConfigurationManager(basicConfiguration,window);const configuration=configurationManager.getConfiguration();if(!configurationManager.isValidConfiguration()){return null}const agentInstanceData=new agent_instance_data_1.AgentInstanceData(agent_events_contracts_1.AgentTypes.TEST_LISTENER,agent_events_contracts_1.AgentTechnologies.BROWSER);const logger=AgentFactory.createLogger("BrowserAgent",configuration,window);const agentConfiguration=this.createAgentConfiguration(configuration);const backendProxy=this.createBackendProxy(agentConfiguration,agentInstanceData,window,featureDetection,configuration);const eventProcess=this.createEventProcess(window,featureDetection,configuration,agentConfiguration,agentInstanceData,backendProxy);AgentFactory.notifyAgentStart(agentConfiguration,agentInstanceData,logger,backendProxy,basicConfiguration);if(basicConfiguration.collectorUrl){return this.createFootprintsOnlyInstance(window,featureDetection,configuration,agentInstanceData,logger,agentConfiguration,backendProxy,eventProcess)}return this.createBrowserAgentInstanceFPV6(window,featureDetection,configuration,agentInstanceData,logger,agentConfiguration,backendProxy,eventProcess)}static notifyAgentStart(agentConfiguration,agentInstanceData,logger,backendProxy,basicConfiguration){if(basicConfiguration.collectorUrl){cockpit_notifier_1.CockpitNotifier.notifyStartNoOp(agentConfiguration,agentInstanceData,logger,backendProxy,{})}else{cockpit_notifier_1.CockpitNotifier.notifyStart(agentConfiguration,agentInstanceData,logger,backendProxy,{},undefined,undefined,this.getColorContextManager())}}static createBrowserAgentInstanceFPV6(window,featureDetection,configuration,agentInstanceData,logger,agentConfig,backendProxy,eventsProcess){const configProcess=this.createConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy);const stateTracker=this.createStateTrackerInfra(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess);const footprintsProcessV6=this.getCreateFootprintsProcessV6(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker);const slMappingLoader=this.createSlMappingLoader(window,backendProxy,configuration);const flushFootprintsWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_FLUSH_WATCHDOG,agentConfig.footprintsCollectIntervalSecs.value);return new browser_agent_instance_fpv6_1.BrowserAgentInstanceFpv6(logger,footprintsProcessV6,configuration,window,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader)}static createFootprintsOnlyInstance(window,featureDetection,configuration,agentInstanceData,logger,agentConfig,backendProxy,eventsProcess){const configProcess=this.createNoOpConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy);const stateTracker=this.createNoopStateTracker(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess);const footprintsProcessV6=this.createCollectorFootprintsProcess(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker);const slMappingLoader=this.createSlMappingLoader(window,backendProxy,configuration);const flushFootprintsWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_FLUSH_WATCHDOG,agentConfig.footprintsCollectIntervalSecs.value);return new browser_agent_instance_fpv6_1.BrowserAgentInstanceFpv6(logger,footprintsProcessV6,configuration,window,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader)}static createFootprintsQueueSender(window,featureDetection,configuration,stateTracker,agentInstanceData,backendProxy){const watchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG);const lightBackendProxy=AgentFactory.createLightBackendProxy(window,featureDetection,configuration,agentInstanceData);const codeCoverageManager=AgentFactory.createCodeCoverageManager(window,configuration);const testStateHelper=AgentFactory.createTestStateHelper();const environmentData=AgentFactory.createEnvironmentData(window,configuration);const footprintsItemsQueue=AgentFactory.createFootprintsItemsQueue(configuration);const logger=AgentFactory.createLogger("FootprintsQueueSender",configuration,window);const slMappingLoader=this.createSlMappingLoader(window,backendProxy,configuration);const footprintsQueueSender=new footprints_queue_sender_1.FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsItemsQueue,window,logger,slMappingLoader);return footprintsQueueSender}static createWatchdog(window,configuration,classname,intervalSec){const intervalMS=(intervalSec||configuration.interval||10)*1e3;const logger=AgentFactory.createLogger(classname,configuration,window);const windowTimeoutWrapper=AgentFactory.createWindowTimersWrapper(window);const watchdog=new watchdog_1.Watchdog(intervalMS,windowTimeoutWrapper,{autoReset:true},logger);return watchdog}static createCodeCoverageManager(window,configuration){const istanbulToFootprintsConvertor=AgentFactory.createInstanbulToFootprintsConvertor(window,configuration);const codeCoverageManager=new code_coverage_manager_1.CodeCoverageManager(istanbulToFootprintsConvertor,configuration);return codeCoverageManager}static createLightBackendProxy(window,featureDetection,configuration,agentInstanceData){const jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration,agentInstanceData);const logger=AgentFactory.createLogger("FootprintsServiceProxy",configuration,window);const lightBackendProxy=new light_backend_proxy_1.LightBackendProxy(configuration,jsonClient,logger);return lightBackendProxy}static createSlMappingLoader(window,backendProxy,configuration){const logger=AgentFactory.createLogger("slMappingLoader",configuration,window);return new sl_mapping_loader_1.SlMappingLoader(backendProxy,window,logger,configuration)}static createJsonClient(window,featureDetection,configuration,agentInstanceData){const httpClient=AgentFactory.createHttpClient(window,featureDetection,configuration);return configuration.blockBrowserHttpTraffic?new noop_json_client_1.NoopJsonClient(httpClient,configuration,agentInstanceData):new json_client_1.JsonClient(httpClient,configuration,agentInstanceData)}static createHttpClient(window,featureDetection,configuration){const logger=AgentFactory.createLogger("HttpClient",configuration,window);const httpClient=new http_client_1.HttpClient(window,featureDetection,logger);return httpClient}static createStateTracker(configuration,window,featureDetection,agentInstanceData){const watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG);const logger=AgentFactory.createLogger("StateTracker",configuration,window);const jsonClient=AgentFactory.createJsonClient(window,featureDetection,configuration,agentInstanceData);const stateTracker=new state_tracker_1.StateTracker(configuration,jsonClient,watchdog,logger);return stateTracker}static createTestStateHelper(){const testStateHelper=new test_state_helper_1.TestStateHelper;return testStateHelper}static createWindowTimersWrapper(window){const windowTimersWrapper=new window_timers_wrapper_1.WindowTimersWrapper(window);return windowTimersWrapper}static createEnvironmentData(window,configuration){if(!environment_data_1.EnvironmentData.constantAgentId)environment_data_1.EnvironmentData.constantAgentId=basic_uuid_generator_1.BasicUuidGenerator.createUuid()+"<|>"+this.getTime(window);const environmentData=environment_data_1.EnvironmentData.create(configuration);return environmentData}static createInstanbulToFootprintsConvertor(window,configuration){let instanbulToFootprintsConvertor=null;if(configuration.resolveWithoutHash){instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_v3_1.IstanbulToFootprintsConvertorV3(window,configuration)}else{instanbulToFootprintsConvertor=new istanbul_to_footprints_convertor_1.IstanbulToFootprintsConverter(window,configuration)}return instanbulToFootprintsConvertor}static createFootprintsItemsQueue(configuration){const footprintsItemsQueue=new footprints_items_queue_1.FootprintsItemsQueue(configuration);return footprintsItemsQueue}static createEventProcess(window,featureDetection,configurationData,agentConfiguration,agentInstanceData,backendProxy){const sendToServerWatchdog=this.createWatchdog(window,configurationData,"sendToServer");const keepAliveWatchdog=this.createWatchdog(window,configurationData,"keepAlive");const environmentData=this.createEnvironmentData(window,configurationData);environmentData.testStage=agentConfiguration.testStage.value;const logger=AgentFactory.createLogger("BrowserAgent",configurationData,window);const queue=new queue_1.Queue(new delegate_1.Delegate);const colorContextManager=this.getColorContextManager();const eventsProcess=new browser_events_process_1.BrowserEventsProcess(agentConfiguration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentData,backendProxy,queue,logger,colorContextManager);return eventsProcess}static getColorContextManager(){if(this.colorContextManager){return this.colorContextManager}this.colorContextManager=new color_context_manager_1.ColorContextManager;return this.colorContextManager}static createBackendProxy(agentConfiguration,agentInstanceData,window,featureDetection,configurationData){const logger=this.createLogger("BackendProxy",configurationData,window);const httpClientConfig=this.createHttpClientConfig(agentConfiguration);const jsonClientAdapter=this.createJsonClientAdapter(window,featureDetection,configurationData,agentInstanceData);const backendProxy=new backend_proxy_1.BackendProxy(agentInstanceData,httpClientConfig,logger,jsonClientAdapter);return backendProxy}static createHttpClientConfig(agentConfig){return{token:agentConfig.token.value,proxy:agentConfig.proxy.value,server:agentConfig.server.value,compressRequests:agentConfig.gzip.value}}static createConfigurationManager(basicConfiguration,window){const logger=AgentFactory.createLogger("ConfigurationManager",basicConfiguration,window);const configurationManager=new configuration_manager_1.ConfigurationManager(logger,basicConfiguration,window);return configurationManager}static createLogger(className,basicConfiguration,window){var _a,_b;return log_factory_1.LogFactory.createLogger(className,basicConfiguration.logLevel||((_b=(_a=window===null||window===void 0?void 0:window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.logLevel))}static getTime(window){if(window&&window.performance&&typeof window.performance.now==="function"){return performance.now()}return(0,system_date_1.getSystemDateValueOf)()}static createAgentConfiguration(configuration){const configLoader=new config_loader_1.ConfigLoader;const configObject=configuration;if(!configObject.build){configObject.build=configObject.buildName}if(!configObject.branch){configObject.branch=configObject.branchName}return configLoader.loadAgentConfiguration(configuration)}static createJsonClientAdapter(window,featureDetection,config,agentInstanceData){const jsonClient=this.createJsonClient(window,featureDetection,config,agentInstanceData);return new json_client_adapter_1.JsonClientAdapter(jsonClient,config.server,config.collectorUrl)}static getCreateFootprintsProcessV6(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker){const sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG,agentConfig.footprintsSendIntervalSecs.value);const keepaliveWatchdog=AgentFactory.createWatchdog(window,configuration,KEEP_ALIVE_WATCHDOG);const relativePathResolver=new relative_path_resolver_1.RelativePathResolver;const hitsCollector=new browser_hits_collector_1.BrowserHitsCollector(configuration.buildSessionId,this.createLogger("browserHitsCollector",configuration,window));const hitsConverter=new browser_hits_converter_1.BrowserHitsConverter(relativePathResolver,window,agentConfig.buildSessionId.value,this.createLogger("HitsConverter",configuration,window));const footprintsBuffer=new browser_footprints_buffer_1.BrowserFootprintsBuffer(agentInstanceData,agentConfig);return new index_1.FootprintsProcess(agentConfig,sendToServerWatchdog,keepaliveWatchdog,this.createLogger("footprintsProcess",configuration,window),hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker)}static createCollectorFootprintsProcess(window,configuration,agentInstanceData,agentConfig,backendProxy,stateTracker){const sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,FOOTPRINTS_SENDER_WATCHDOG,agentConfig.footprintsSendIntervalSecs.value);const keepaliveWatchdog=AgentFactory.createWatchdog(window,configuration,KEEP_ALIVE_WATCHDOG);const relativePathResolver=new relative_path_resolver_1.RelativePathResolver;const hitsCollector=new browser_hits_collector_1.BrowserHitsCollector(configuration.buildSessionId,this.createLogger("browserHitsCollector",configuration,window));const hitsConverter=new browser_hits_converter_1.BrowserHitsConverter(relativePathResolver,window,agentConfig.buildSessionId.value,this.createLogger("HitsConverter",configuration,window));const footprintsBuffer=new collector_footprints_buffer_1.CollectorFootprintsBuffer(agentInstanceData,agentConfig,configuration.footprintsMapping);return new collector_footprints_process_1.CollectorFootprintsProcess(agentConfig,sendToServerWatchdog,keepaliveWatchdog,this.createLogger("footprintsProcess",configuration,window),hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker)}static createConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy){const sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,CONFIGURATION_WATCHDOG,30);return new config_process_1.ConfigProcess(agentConfig,sendToServerWatchdog,backendProxy,this.createLogger("configProcess",configuration,window))}static createNoOpConfigProcess(window,configuration,agentInstanceData,agentConfig,backendProxy){const sendToServerWatchdog=AgentFactory.createWatchdog(window,configuration,CONFIGURATION_WATCHDOG,30);return new no_op_config_process_1.NoopConfigProcess(agentConfig,sendToServerWatchdog,backendProxy,this.createLogger("configProcess",configuration,window))}static createStateTrackerInfra(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess){const watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG,agentConfig.executionQueryIntervalSecs.value);return new state_tracker_fpv6_1.StateTrackerFpv6(agentConfig,configProcess,watchdog,backendProxy,this.createLogger("stateTracker",configuration,window))}static createNoopStateTracker(window,configuration,agentInstanceData,agentConfig,backendProxy,configProcess){const watchdog=AgentFactory.createWatchdog(window,configuration,ACTIVE_EXECUTION_WATCHDOG,agentConfig.executionQueryIntervalSecs.value);return new no_op_state_tracker_1.NoopStateTracker(agentConfig,configProcess,watchdog,backendProxy,this.createLogger("stateTracker",configuration,window))}}exports.AgentFactory=AgentFactory})},{"../../common/agent-events/agent-events-contracts":227,"../../common/agent-events/cockpit-notifier":234,"../../common/agent-instance-data":240,"../../common/config-process":244,"../../common/config-process/config-loader":241,"../../common/config-process/no-op-config-process":245,"../../common/footprints-process-v6/collector-footprints-buffer":258,"../../common/footprints-process-v6/collector-footprints-process":259,"../../common/footprints-process-v6/index":263,"../../common/footprints-process-v6/relative-path-resolver":265,"../../common/http/backend-proxy":267,"../../common/no-op-state-tracker":271,"../../common/state-tracker-fpv6":273,"../../common/system-date":275,"./basic-uuid-generator":177,"./browser-agent-instance-fpv6":178,"./browser-events-process":180,"./browser-footprints-buffer":181,"./browser-hits-collector":182,"./browser-hits-converter":183,"./code-coverage-manager":184,"./color-context-manager":185,"./configuration-manager":187,"./delegate":190,"./entities/environment-data":193,"./footprints-queue-sender":205,"./istanbul-to-footprints-convertor":207,"./istanbul-to-footprints-convertor-v3":206,"./logger/log-factory":209,"./queues/footprints-items-queue":211,"./queues/queue":212,"./services/http/http-client":213,"./services/json/json-client":217,"./services/json/json-client-adapter":216,"./services/json/noop-json-client":218,"./services/light-backend-proxy":219,"./sl-mapping-loader":220,"./state-tracker":221,"./test-state-helper":222,"./watchdog":224,"./window-timers-wrapper":225}],177:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicUuidGenerator=void 0;class BasicUuidGenerator{static createUuid(){const uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){const r=Math.random()*16|0,v=c=="x"?r:r&3|8;return v.toString(16)});return uuid}}exports.BasicUuidGenerator=BasicUuidGenerator})},{}],178:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./feature-detection","../../common/http/sl-routes","./config","./basic-uuid-generator","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgentInstanceFpv6=void 0;const feature_detection_1=require("./feature-detection");const sl_routes_1=require("../../common/http/sl-routes");const config_1=require("./config");const basic_uuid_generator_1=require("./basic-uuid-generator");const cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");class BrowserAgentInstanceFpv6{constructor(logger,footprintsProcess,configuration,window,stateTracker,eventsProcess,agentConfig,flushFootprintsWatchdog,slMappingLoader){this.logger=logger;this.configuration=configuration;this.window=window;this.stateTracker=stateTracker;this.eventsProcess=eventsProcess;this._isStarted=false;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(eventsProcess==null)throw new Error("'eventsProcess' cannot be null or undefined");if(agentConfig==null)throw new Error("'agentConfig' cannot be null or undefined");logger.info("Sealights "+config_1.SL_AGENT_TYPE+" version "+config_1.SL_AGENT_VERSION+" has been loaded");this.footprintsProcess=footprintsProcess;this.flushFootprintsWatchdog=flushFootprintsWatchdog;this.slMappingLoader=slMappingLoader;this.stateTracker.on("test_identifier_changed",this.footprintsProcess.handleTestIdChanged.bind(this.footprintsProcess))}startFootprintsProcess(){this.flushFootprintsWatchdog.addOnAlarmListener(this.footprintsProcess.flushCurrentFootprints.bind(this.footprintsProcess));this.flushFootprintsWatchdog.start();this.footprintsProcess.start();this.stateTracker.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId)}stopFootprintsProcess(){return __awaiter(this,void 0,void 0,function*(){this.flushFootprintsWatchdog.stop();yield this.footprintsProcess.stop()})}submitFootprints(){return __awaiter(this,void 0,void 0,function*(){yield this.footprintsProcess.submitQueuedFootprints(this.stateTracker.currentExecution)})}submitFootprintsSync(){return __awaiter(this,void 0,void 0,function*(){try{yield this.footprintsProcess.flushCurrentFootprints();yield this.footprintsProcess.submitQueuedFootprints(this.stateTracker.currentExecution)}catch(e){this.logger.error(`Failed to submit footprint sync '${e.message}'`)}})}static getExecutionId(){if(!BrowserAgentInstanceFpv6.executionId){const execId=basic_uuid_generator_1.BasicUuidGenerator.createUuid();BrowserAgentInstanceFpv6.executionId=execId}return BrowserAgentInstanceFpv6.executionId}registerShutdownHook(){const context=this;const oldUnload=this.window.onunload;this.window.onunload=function(){if(oldUnload){oldUnload.call(arguments)}context.beaconSendAllFootprints();context.stop()};const oldBeforeUnload=this.window.onbeforeunload;this.window.onbeforeunload=function(){if(oldBeforeUnload){oldBeforeUnload.call(arguments)}context.beaconSendAllFootprints();context.stop()}}setCurrentTestIdentifier(testIdentifier){this.logger.info("Agent is setting current test identifier. testIdentifier:'"+testIdentifier+"'.");this.stateTracker.setCurrentTestIdentifier(testIdentifier)}stop(){return __awaiter(this,void 0,void 0,function*(){if(!this._isStarted)return;this.logger.info("Agent is stopping.");yield this.eventsProcess.stop();this.stopFootprintsProcess();yield cockpit_notifier_1.CockpitNotifier.notifyShutdown();this._isStarted=false})}start(){if(this._isStarted)return;this.logger.info("Agent is starting. registerShutdownHook:"+this.configuration.registerShutdownHook);if(this.configuration.registerShutdownHook){this.registerShutdownHook()}this.eventsProcess.start();this.startFootprintsProcess();this._isStarted=true}getInstanceBSID(){return this.configuration.buildSessionId}getAllRemainingFootprints(){return __awaiter(this,void 0,void 0,function*(){let footprintsData=undefined;const packet=yield this.getCurrentFootprints();if(typeof packet==="object"&&packet!==null&&Object.keys(packet).length){footprintsData={bsid:this.getInstanceBSID(),packet:packet}}return footprintsData})}beaconSendAllFootprints(){return __awaiter(this,void 0,void 0,function*(){const featureDetection=new feature_detection_1.FeatureDetection(this.window);const footprintsData=yield this.getAllRemainingFootprints();if(featureDetection.hasBeaconAPI()&&footprintsData){const url=sl_routes_1.SLRoutes.footprintsToCollector(footprintsData.bsid);this.window.navigator.sendBeacon(url,JSON.stringify(footprintsData.packet))}})}getCurrentFootprints(){return __awaiter(this,void 0,void 0,function*(){return yield this.footprintsProcess.getBufferPacket()})}}exports.BrowserAgentInstanceFpv6=BrowserAgentInstanceFpv6})},{"../../common/agent-events/cockpit-notifier":234,"../../common/http/sl-routes":270,"./basic-uuid-generator":177,"./config":186,"./feature-detection":204}],179:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-factory","./logger/log-factory","./events-bridge/context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserAgent=void 0;const agent_factory_1=require("./agent-factory");const log_factory_1=require("./logger/log-factory");const context_message_manager_1=require("./events-bridge/context-message-manager");class BrowserAgent{constructor(window,featureDetection){this.instances=[];this.running=false;this.logger=log_factory_1.LogFactory.createLogger("BrowserAgent");this.instanceAddedForBsid={};this.window=window;this.featureDetection=featureDetection}addInstance(instance){this.instances.push(instance)}createInstance(configuration){if(this.instanceAddedForBsid[configuration.buildSessionId]){this.logger.info(`Already has instance for bsid '${configuration.buildSessionId}'`);return}try{this.instanceAddedForBsid[configuration.buildSessionId]=true;const browserAgent=agent_factory_1.AgentFactory.createBrowserAgent(this.window,this.featureDetection,configuration);if(browserAgent){browserAgent.start();this.instances.push(browserAgent)}else{this.logger.error(`Invalid configuration for app: ${configuration.appName},
2
2
  build: ${configuration.buildName}, branch: ${configuration.branchName}
3
3
  Sealights agent disabled`)}}catch(e){this.logger.error(`Error while creating agent for app: ${configuration.appName}, build: ${configuration.buildName},
4
- branch: ${configuration.branchName}. Error ${e}`)}}start(){if(this.instances.length==0){return}this.instances.forEach(instance=>instance.start());this.running=true}stop(){return __awaiter(this,void 0,void 0,function*(){yield Promise.all(this.instances.map(instance=>instance.stop()));this.running=false})}isRunning(){return this.running}setCurrentTestIdentifier(identifier){this.instances.forEach(instance=>instance.setCurrentTestIdentifier(identifier))}sendAllFootprints(){return __awaiter(this,void 0,void 0,function*(){context_message_manager_1.ContextMessageManager.getInstance().sendAllEvents();yield Promise.all(this.instances.map(instance=>instance.submitFootprintsSync()))})}}exports.BrowserAgent=BrowserAgent})},{"./agent-factory":176,"./events-bridge/context-message-manager":196,"./logger/log-factory":209}],180:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/events-process"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserEventsProcess=void 0;const events_process_1=require("../../common/events-process");class BrowserEventsProcess extends events_process_1.EventsProcess{stop(){return __awaiter(this,void 0,void 0,function*(){this.isRunning=false;this.sendToServerWatchdog.stop();if(this.configuration.enabled.value===false||this.configuration.sendEvents.value===false){return}const callback=err=>{if(err){this.logger.error(`Failed to submit final events, Error : '${err}'`)}};while(this.eventsQueue.getQueueSize()>0){const items=this.eventsQueue.dequeue(events_process_1.EventsProcess.ITEMS_TO_DEQUE);const packet=this.createEventsPacket(items);this.backendProxy.submitEvents(packet,callback,false)}})}}exports.BrowserEventsProcess=BrowserEventsProcess})},{"../../common/events-process":255}],181:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/footprints-buffer","../../common/contracts","./events-bridge/context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserFootprintsBuffer=void 0;const footprints_buffer_1=require("../../common/footprints-process-v6/footprints-buffer");const contracts_1=require("../../common/contracts");const context_message_manager_1=require("./events-bridge/context-message-manager");class BrowserFootprintsBuffer extends footprints_buffer_1.FootprintsBuffer{constructor(agentInstanceData,agentConfig,footprintsMapping){super(agentInstanceData,agentConfig);this.contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();this.meta.footprintsMapping=footprintsMapping===contracts_1.FootprintsMapping.SERVER?footprintsMapping:contracts_1.FootprintsMapping.AGENT}createPacket(){var _a;const packet=super.createPacket();(_a=packet===null||packet===void 0?void 0:packet.executions)===null||_a===void 0?void 0:_a.forEach(execution=>{var _a;(_a=execution===null||execution===void 0?void 0:execution.hits)===null||_a===void 0?void 0:_a.forEach(hit=>{if(hit.testName){this.contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED,1)}else{this.contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON,1)}})});return packet}}exports.BrowserFootprintsBuffer=BrowserFootprintsBuffer})},{"../../common/contracts":248,"../../common/footprints-process-v6/footprints-buffer":260,"./events-bridge/context-message-manager":196}],182:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/hits-collector"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsCollector=void 0;const hits_collector_1=require("../../common/footprints-process-v6/hits-collector");class BrowserHitsCollector extends hits_collector_1.HitsCollector{constructor(buildSessionId,logger,globalCoverageObject){super(logger,globalCoverageObject);this.buildSessionId=buildSessionId}getGlobalCoverageObject(){if(!this.globalCoverageObject){const coverageObject="$SealightsCoverage";const coverageObjectForBSID=`${coverageObject}_${this.buildSessionId}`;this.globalCoverageObject=window[coverageObjectForBSID]||window[coverageObject]}return this.globalCoverageObject}}exports.BrowserHitsCollector=BrowserHitsCollector})},{"../../common/footprints-process-v6/hits-collector":261}],183:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/base-browser-hits-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsConverter=void 0;const base_browser_hits_converter_1=require("../../common/footprints-process-v6/base-browser-hits-converter");class BrowserHitsConverter extends base_browser_hits_converter_1.BaseBrowserHitsConverter{constructor(relativePathResolver,window,buildSessionId,logger){super(relativePathResolver,buildSessionId,logger);this.window=window}getSlMapping(){return this.window.slMappings[this.buildSessionId]||{}}}exports.BrowserHitsConverter=BrowserHitsConverter})},{"../../common/footprints-process-v6/base-browser-hits-converter":256}],184:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CodeCoverageManager=void 0;class CodeCoverageManager{constructor(convertor,configuration){this.convertor=convertor;this.configuration=configuration;this.aggregatedCoverage={};this.isDestroyed=false}findCoverageContainer(){const coverageObject="$SealightsCoverage";const coverageObjectForBSID=`${coverageObject}_${this.configuration.buildSessionId}`;return window[coverageObjectForBSID]||window[coverageObject]}getFootprints(testInfo){const counters=this.getCounters(true);return this.convertor.convert(counters,testInfo.testName,testInfo.executionId)}_clearCounters(istanbulCoverageObject){if(!istanbulCoverageObject)return;if(this.isDestroyed)return;const context=this;this.forEachProp(istanbulCoverageObject,function(moduleName,m){context.aggregatedCoverage[moduleName]=context.aggregatedCoverage[moduleName]||{s:{},b:{},f:{}};const am=context.aggregatedCoverage[moduleName];context.forEachProp(m.s,function(sid,s){am.s[sid]=(am.s[sid]||0)+m.s[sid];m.s[sid]=0});context.forEachProp(m.b,function(bid,b){am.b[bid]=am.b[bid]||Array.apply(null,Array(m.b[bid].length)).map(Number.prototype.valueOf,0);for(let idx=0;idx<am.b[bid].length;idx++){am.b[bid][idx]+=m.b[bid][idx];m.b[bid][idx]=0}});context.forEachProp(m.f,function(fid,f){am.f[fid]=(am.f[fid]||0)+m.f[fid];m.f[fid]=0})})}cloneCodeMetrics(o){const cloned={};for(const i in o){cloned[i]=this.cloneModule(o[i])}return cloned}cloneModule(m){const cm={b:{},f:{},s:{}};for(const i in m.s){cm.s[i]=m.s[i]}for(const i in m.f){cm.f[i]=m.f[i]}for(const i in m.b){cm.b[i]=m.b[i].slice()}cm.metadata=m.metadata;cm.path=m.path;cm.fnMap=m.fnMap;cm.fnToBranch=m.fnToBranch;cm.branchMap=m.branchMap;cm.inputSourceMap=m.inputSourceMap;return cm}forEachProp(obj,func){Object.keys(obj).forEach(function(k){func(k,obj[k])})}clearCounters(){if(this.isDestroyed)return;const ct=this.findCoverageContainer();if(ct){this._clearCounters(ct)}}getCounters(clearAfterwards){if(this.isDestroyed)return{};const ct=this.findCoverageContainer();if(ct){const ret=this.cloneCodeMetrics(ct);if(clearAfterwards)this._clearCounters(ct);return ret}}}exports.CodeCoverageManager=CodeCoverageManager})},{}],185:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ColorContextManager=void 0;class ColorContextManager{constructor(){this.windowObj=window;this.testName=null;this.executionId=null}setTestName(testName){this.testName=testName}setExecutionId(executionId){if(!(executionId===null||executionId===void 0?void 0:executionId.length)){return this.executionId=null}const isValid=executionId.indexOf("/")===-1;if(!isValid){throw new Error(`Invalid executionId received: ${executionId}. executionId cannot contain backslash('/') character.`)}this.executionId=executionId}setCurrentTestIdentifier(testName,executionId){var _a;this.setExecutionId(executionId);this.setTestName(testName);(_a=this.windowObj.$SealightsAgent)===null||_a===void 0?void 0:_a.setCurrentTestIdentifier(this.getCurrentTestIdentifier())}getCurrentTestIdentifier(){var _a,_b;if(!((_a=this.testName)===null||_a===void 0?void 0:_a.length)||!((_b=this.executionId)===null||_b===void 0?void 0:_b.length))return null;return`${this.executionId}/${this.testName}`}getTestName(){return this.testName}getExecutionId(){return this.executionId}}exports.ColorContextManager=ColorContextManager})},{}],186:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SL_AGENT_TYPE=exports.SL_AGENT_VERSION=void 0;exports.SL_AGENT_VERSION="6.1.625";exports.SL_AGENT_TYPE="browser"})},{}],187:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/configuration-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationManager=void 0;const configuration_data_1=require("./entities/configuration-data");class ConfigurationManager{constructor(logger,basicConfiguration,window){this.logger=logger;this.basicConfiguration=basicConfiguration;this.window=window;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(basicConfiguration==null)throw new Error("'basicConfiguration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined")}getConfiguration(){if(this.currentConfiguration)return this.currentConfiguration;const configurationData=this.getDefaults();this.overrideConfiguration(configurationData);configurationData.labId=this.resolveLabId();this.currentConfiguration=configurationData;this.printConfiguration(configurationData);this.validateConfiguration(configurationData);return configurationData}getDefaults(){const config=new configuration_data_1.ConfigurationData;config.appName=this.basicConfiguration.appName;config.branchName=this.basicConfiguration.branchName;config.buildName=this.basicConfiguration.buildName;config.buildSessionId=this.basicConfiguration.buildSessionId;config.customerId=this.basicConfiguration.customerId;config.token=this.basicConfiguration.token;config.server=this.basicConfiguration.server;config.interval=this.basicConfiguration.interval||10;config.maxItemsInQueue=this.basicConfiguration.maxItemsInQueue||500;config.workspacepath=this.basicConfiguration.workspacepath;return config}resolveLabId(){let labId=this.readLabIdFromWindow();if(labId){this.logger.info("Using labId from the 'window' object. LabId:"+labId);return labId}labId=this.basicConfiguration.labId;if(labId){this.logger.info("Using labId from basic configuration. LabId:"+labId);return labId}labId=this.readLabIdFromSessionStorage();if(labId){this.logger.info("Using labId from session storage. LabId:"+labId);return labId}labId=this.basicConfiguration.buildSessionId;if(labId){this.logger.info("Using buildSessionId as labId. LabId:"+labId);return labId}labId=this.basicConfiguration.appName;if(labId){this.logger.info("Using appName as labId. LabId:"+labId);return labId}return"DefaultLabId"}overrideConfiguration(configurationData){for(const p in this.basicConfiguration){configurationData[p]=this.basicConfiguration[p]}this.logger.info("[TO CS] - TODO: Send request to server to get the configuration.")}printConfiguration(configurationData){this.logger.info("***********************************************************");this.logger.info("Current configuration:");this.logger.info("------------------------------------------------");for(const prop in configurationData){this.logger.info(prop+": '"+configurationData[prop])+"'"}this.logger.info("***********************************************************")}validateConfiguration(configurationData){const fieldsWithError=[];if(!configurationData.customerId||configurationData.customerId=="")fieldsWithError.push("customerId");if(!configurationData.server||configurationData.server=="")fieldsWithError.push("server");if(!configurationData.appName||configurationData.appName=="")fieldsWithError.push("appName");if(!configurationData.branchName||configurationData.branchName=="")fieldsWithError.push("branchName");if(!configurationData.buildName||configurationData.buildName=="")fieldsWithError.push("buildName");if(!configurationData.token||configurationData.token=="")fieldsWithError.push("token");if(fieldsWithError.length>0){this.logger.warn("------------------------------------------------");this.logger.warn("Detected an invalid configuration:");fieldsWithError.forEach(field=>{this.logger.warn("'"+field+"' is required but it had a 'null' or empty value.")});this.logger.warn("Please fix the configuration prior to using SeaLights.");this.logger.warn("------------------------------------------------")}this._isValidConfiguration=fieldsWithError.length==0}isValidConfiguration(){return this._isValidConfiguration}readLabIdFromSessionStorage(){let labId=null;if(this.window.sessionStorage&&typeof this.window.sessionStorage==="function"){labId=this.window.sessionStorage.getItem(ConfigurationManager.LAB_ID_KEY)}return labId}readLabIdFromWindow(){return this.window[ConfigurationManager.LAB_ID_KEY]}}exports.ConfigurationManager=ConfigurationManager;ConfigurationManager.LAB_ID_KEY="__sl.labId__"})},{"./entities/configuration-data":192}],188:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./logger/console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationOverride=exports.ConfigChangedEvents=void 0;const EventEmitter=require("events");const console_logger_1=require("./logger/console-logger");var ConfigChangedEvents;(function(ConfigChangedEvents){ConfigChangedEvents["LOG_LEVEL_CHANGED"]="logLevelChanged"})(ConfigChangedEvents=exports.ConfigChangedEvents||(exports.ConfigChangedEvents={}));class ConfigurationOverride extends EventEmitter{constructor(initialConfig){super();this._logLevel=console_logger_1.LogLevels.INFO;this.setMaxListeners(500);this.loadInitialConfig(initialConfig)}get logLevel(){return this._logLevel}set logLevel(value){this._logLevel=value;this.emit(ConfigChangedEvents.LOG_LEVEL_CHANGED,value)}loadInitialConfig(initialConfig={}){for(const prop in initialConfig){const descriptor=Object.getOwnPropertyDescriptor(this.constructor.prototype,prop);if(descriptor&&typeof descriptor.set==="function"){this[prop]=initialConfig[prop]}}}static create(configuration){if(configuration instanceof ConfigurationOverride){return configuration}return new ConfigurationOverride(configuration)}}exports.ConfigurationOverride=ConfigurationOverride})},{"./logger/console-logger":208,events:158}],189:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExecutionStatus=void 0;var ExecutionStatus;(function(ExecutionStatus){ExecutionStatus["InProgress"]="created";ExecutionStatus["Ending"]="pendingDelete"})(ExecutionStatus=exports.ExecutionStatus||(exports.ExecutionStatus={}))})},{}],190:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Delegate=void 0;class Delegate{constructor(){this.functions=new Array}addListener(func){if(!func)return;if(this.functions)this.functions.push(func)}fire(){if(!this.functions)return;for(let i=0;i<this.functions.length;i++){this.functions[i]()}}}exports.Delegate=Delegate})},{}],191:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicConfigurationData=void 0;class BasicConfigurationData{}exports.BasicConfigurationData=BasicConfigurationData})},{}],192:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./basic-configuation-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationData=void 0;const basic_configuation_data_1=require("./basic-configuation-data");class ConfigurationData extends basic_configuation_data_1.BasicConfigurationData{constructor(){super(...arguments);this.registerShutdownHook=true;this.enabled=true}}exports.ConfigurationData=ConfigurationData})},{"./basic-configuation-data":191}],193:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvironmentData=void 0;const config_1=require("../config");class EnvironmentData{static create(configuration){const data=new EnvironmentData;data.agentType=config_1.SL_AGENT_TYPE;data.agentVersion=config_1.SL_AGENT_VERSION;data.agentId=EnvironmentData.constantAgentId;data.labId=configuration.labId||"";data.meta={navigator:window.navigator,userAgent:window.navigator&&window.navigator.userAgent,location:window.location};return data}}exports.EnvironmentData=EnvironmentData})},{"../config":186}],194:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemData=void 0;class FootprintsItemData{}exports.FootprintsItemData=FootprintsItemData})},{}],195:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.relativePathRegex=exports.EVENTS=exports.EVENT_TYPES=exports.SL_CONTEXT_DIAGNOSIS=exports.SL_SESSION_CONTEXT=exports.CONTEXT=exports.SL_EVENTS_BRIDGE=exports.SL_EXECUTION_ID=exports.SL_TEST_NAME=exports.SL_SESSION_ID=exports.SL_CONTEXT_KEY=exports.SL_BAGGAGE_HEADER=void 0;exports.SL_BAGGAGE_HEADER="baggage";exports.SL_CONTEXT_KEY="sl-context";exports.SL_SESSION_ID="x-sl-test-session-id";exports.SL_TEST_NAME="x-sl-test-name";exports.SL_EXECUTION_ID="x-sl-execution-id";exports.SL_EVENTS_BRIDGE="sl-events-bridge";exports.CONTEXT="context";exports.SL_SESSION_CONTEXT="sl-session-ctx";exports.SL_CONTEXT_DIAGNOSIS="sl-ctx-test";exports.EVENT_TYPES={SET:"set",ACK:"ack",DELETE:"delete",READY:"ready",REQUEST:"request",RESPONSE:"response"};exports.EVENTS={SET_BAGGAGE:`${exports.EVENT_TYPES.SET}:${exports.SL_BAGGAGE_HEADER}`,SET_CONTEXT:`${exports.EVENT_TYPES.SET}:${exports.CONTEXT}`,ACK_BAGGAGE:`${exports.EVENT_TYPES.ACK}:${exports.SL_BAGGAGE_HEADER}`,ACK_CONTEXT:`${exports.EVENT_TYPES.ACK}:${exports.CONTEXT}`,DELETE_BAGGAGE:`${exports.EVENT_TYPES.DELETE}:${exports.SL_BAGGAGE_HEADER}`,DELETE_CONTEXT:`${exports.EVENT_TYPES.DELETE}:${exports.CONTEXT}`,READY_EVENTS_BRIDGE:`${exports.EVENT_TYPES.READY}:${exports.SL_EVENTS_BRIDGE}`,REQUEST_AGENT_CONTEXT:`${exports.EVENT_TYPES.REQUEST}:${exports.SL_CONTEXT_KEY}`,RESPONSE_AGENT_CONTEXT:`${exports.EVENT_TYPES.RESPONSE}:${exports.SL_CONTEXT_KEY}`};exports.relativePathRegex=new RegExp("^(?!www\\.|(?:http|ftp)s?://|[A-Za-z]:\\\\|//).*")})},{}],196:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/agent-events/cockpit-notifier","../../../common/agent-events/agent-events-contracts","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ContextMessageManager=exports.CONTEXT_EVENTS_KEYS=void 0;const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const agent_events_contracts_1=require("../../../common/agent-events/agent-events-contracts");const system_date_1=require("../../../common/system-date");var CONTEXT_EVENTS_KEYS;(function(CONTEXT_EVENTS_KEYS){CONTEXT_EVENTS_KEYS["SET_EVENTS_RECEIVED"]="setEventsReceived";CONTEXT_EVENTS_KEYS["DELETE_EVENTS_RECEIVED"]="deleteEventsReceived";CONTEXT_EVENTS_KEYS["EVENTS_WITH_PERSIST"]="eventsWithPersist";CONTEXT_EVENTS_KEYS["WITH_BAGGAGE"]="withBaggage";CONTEXT_EVENTS_KEYS["WITHOUT_BAGGAGE"]="withoutBaggage";CONTEXT_EVENTS_KEYS["FOOTPRINTS_LAST_SUBMISSION_COLORED"]="footprintsLastSubmissionColored";CONTEXT_EVENTS_KEYS["FOOTPRINTS_LAST_SUBMISSION_ANON"]="footprintsLastSubmissionAnon";CONTEXT_EVENTS_KEYS["FOOTPRINTS_COLORED"]="footprintsColored";CONTEXT_EVENTS_KEYS["FOOTPRINTS_ANON"]="footprintsAnon"})(CONTEXT_EVENTS_KEYS=exports.CONTEXT_EVENTS_KEYS||(exports.CONTEXT_EVENTS_KEYS={}));class ContextMessageManager{constructor(sendCockpitEvents){this.sendCockpitEvents=sendCockpitEvents;this.sources=[];this.contextDataTracking={[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED]:0,[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED]:0,[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]:0,[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE]:0,[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]:0}}static getInstance(sendCockpitEvents=true){return this._instance||(this._instance=new this(sendCockpitEvents))}startContextManager(){if(this.sendCockpitEvents){setInterval(()=>{this.sendAllEvents()},ContextMessageManager.DEFAULT_SEND_INTERVAL)}}incrementContextEventValue(eventKey,incrementBy){if(incrementBy<=0){return}this.contextDataTracking[eventKey]+=incrementBy;switch(eventKey){case CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED:{this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]=(0,system_date_1.getSystemDateValueOf)();break}case CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON:{this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]=(0,system_date_1.getSystemDateValueOf)();break}case CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:case CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE:{this.sources=this.sources.map(source=>{var _a;source.firstSpanDate=(_a=source.firstSpanDate)!==null&&_a!==void 0?_a:(0,system_date_1.getSystemDateValueOf)();source.lastSpanDate=(0,system_date_1.getSystemDateValueOf)();source.count++;return source});break}}}sendAllEvents(){cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_contracts_1.AgentEventCode.CONTEXT_PROPAGATION_TELEMETRY,{contextPropagation:this.getState()})}addSource(source){const sourceIndex=this.sources.findIndex(existingSource=>{return existingSource.agentId&&existingSource.agentId===source.agentId||existingSource.buildSessionId&&existingSource.buildSessionId===source.buildSessionId||existingSource.appName&&existingSource.appName===source.appName});if(sourceIndex>-1){return}this.sources.push(Object.assign(Object.assign({},source),{count:0,firstSpanDate:undefined,lastSpanDate:undefined}))}getState(){return{internalEvents:{[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED],[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED],[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]},spans:{opened:{withBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE],withoutBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]},closed:{withBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE],withoutBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]}},footprintsRequests:{colored:{count:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED],lastSubmission:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]},anon:{count:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON],lastSubmission:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]}},sources:this.sources}}getSources(){return this.sources}}exports.ContextMessageManager=ContextMessageManager;ContextMessageManager.DEFAULT_SEND_INTERVAL=60*1e3})},{"../../../common/agent-events/agent-events-contracts":227,"../../../common/agent-events/cockpit-notifier":234,"../../../common/system-date":275}],197:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deleteCookie=exports.setCookie=exports.getCookie=void 0;function getCookie(cookieName){const name=cookieName.trim()+"=";const decodedCookie=decodeURIComponent(document.cookie);const cookieArray=decodedCookie.split(";");for(let i=0;i<cookieArray.length;i++){const cookie=cookieArray[i].trim();if(cookie.indexOf(name)===0){const cookieValue=cookie.substring(name.length,cookie.length);return(cookieValue===null||cookieValue===void 0?void 0:cookieValue.length)?cookieValue:null}}return null}exports.getCookie=getCookie;function setCookie(cookieKey,cookieValue){document.cookie=cookieKey+"="+encodeURIComponent(cookieValue)}exports.setCookie=setCookie;function deleteCookie(cookieKey){const expiration="expires=Thu, 01 Jan 1970 00:00:00 UTC";document.cookie=cookieKey+"=;"+expiration}exports.deleteCookie=deleteCookie})},{}],198:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./const","@opentelemetry/api","../../../common/agent-events/cockpit-notifier","./context-message-manager","./utils","./cookie-utils","../agent-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deleteBaggageHandler=exports.deleteContextHandler=exports.setContextHandler=exports.setBaggageHandler=exports.checkExistingCookies=exports.checkExistingContext=exports.registerEvents=void 0;const SlConst=require("./const");const api=require("@opentelemetry/api");const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const context_message_manager_1=require("./context-message-manager");const utils_1=require("./utils");const cookie_utils_1=require("./cookie-utils");const agent_factory_1=require("../agent-factory");let SlContext;const registerEvents=(logger,withOpenTelemetry,sendCockpitEvents=false)=>{try{const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance(sendCockpitEvents);contextMessageManager.startContextManager();const colorContextManager=agent_factory_1.AgentFactory.getColorContextManager();window.$Sealights.eventsBridge={loaded:false,otel:false};if(withOpenTelemetry){SlContext=api.ROOT_CONTEXT.setValue(api.createContextKey(SlConst.SL_CONTEXT_KEY),true);window.$Sealights.eventsBridge.getBaggage=()=>SlContext.getValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));window.$Sealights.eventsBridge.getContext=()=>SlContext.getValue(api.createContextKey(SlConst.CONTEXT));window.$Sealights.eventsBridge.otel=true}addEventListener(SlConst.EVENTS.SET_BAGGAGE,({detail})=>{const incrementSetEvents=(detail===null||detail===void 0?void 0:detail.incrementSetEvents)!==false;setBaggageHandler(detail,contextMessageManager,colorContextManager,withOpenTelemetry,logger,incrementSetEvents)});addEventListener(SlConst.EVENTS.SET_CONTEXT,({detail})=>setContextHandler(detail,contextMessageManager,withOpenTelemetry,logger));addEventListener(SlConst.EVENTS.REQUEST_AGENT_CONTEXT,()=>{dispatchEvent(new CustomEvent(SlConst.EVENTS.RESPONSE_AGENT_CONTEXT,{detail:{components:window.$Sealights.components||{}}}))});addEventListener(SlConst.EVENTS.DELETE_BAGGAGE,()=>deleteBaggageHandler(contextMessageManager,colorContextManager));addEventListener(SlConst.EVENTS.DELETE_CONTEXT,()=>deleteContextHandler(contextMessageManager,colorContextManager));window.$Sealights.eventsBridge.loaded=true;logger.info(`Events Bridge integration loaded. All events registered successfully. OpenTelemetry status: ${withOpenTelemetry}`);const sessionContext=checkExistingContext(logger);if(!sessionContext){checkExistingCookies(logger)}}catch(error){logger.error(`An error occurred while registering OpenTelemetry integration events.`,error);window.$Sealights.eventsBridge.error=error;cockpit_notifier_1.CockpitNotifier.sendError(JSON.stringify(error,Object.getOwnPropertyNames(error)))}};exports.registerEvents=registerEvents;function checkExistingContext(logger){const existingContext=sessionStorage.getItem(SlConst.SL_SESSION_CONTEXT);if(!(existingContext===null||existingContext===void 0?void 0:existingContext.length)){return false}const parsedContext=JSON.parse(existingContext);logger.info(`Found existing context in session storage. Dispatching event with data: ${existingContext}`);const storedContextEvent=new CustomEvent(SlConst.EVENTS.SET_CONTEXT,{detail:parsedContext});dispatchEvent(storedContextEvent);return true}exports.checkExistingContext=checkExistingContext;function checkExistingCookies(logger){const testNameCookieValue=(0,cookie_utils_1.getCookie)(SlConst.SL_TEST_NAME);const executionIdCookieValue=(0,cookie_utils_1.getCookie)(SlConst.SL_EXECUTION_ID);if(!(testNameCookieValue===null||testNameCookieValue===void 0?void 0:testNameCookieValue.length)||!(executionIdCookieValue===null||executionIdCookieValue===void 0?void 0:executionIdCookieValue.length)){return false}logger.info(`Found existing test name and executionId cookies. Dispatching event with data: ${testNameCookieValue}/${executionIdCookieValue}`);dispatchEvent(new CustomEvent(SlConst.EVENTS.SET_BAGGAGE,{detail:{[SlConst.SL_SESSION_ID]:executionIdCookieValue,[SlConst.SL_TEST_NAME]:testNameCookieValue}}));return true}exports.checkExistingCookies=checkExistingCookies;function setBaggageHandler(detail,contextMessageManager,colorContextManager,withOpenTelemetry,logger,incrementSetEvents=true){if(incrementSetEvents){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED,1)}logger.info(`setBaggage: Received event "detail": ${JSON.stringify(detail,null,4)}`);if(!detail){logger.warn(`Received setBaggage event with no detail, not changing baggage.`);return}const executionId=detail[SlConst.SL_SESSION_ID];const testName=detail[SlConst.SL_TEST_NAME];if(!(executionId===null||executionId===void 0?void 0:executionId.length)||!(testName===null||testName===void 0?void 0:testName.length)){logger.warn(`Received setBaggage event with with missing testName/executionId: testName=${testName} executionId=${executionId}`);return}if((0,utils_1.checkIsDiagnosisBaggage)(detail)){return(0,utils_1.sendAckEvent)(detail)}if(withOpenTelemetry){SlContext=SlContext.setValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER),{[SlConst.SL_SESSION_ID]:executionId,[SlConst.SL_TEST_NAME]:encodeURIComponent(testName)})}colorContextManager.setCurrentTestIdentifier(testName,executionId);(0,cookie_utils_1.setCookie)(SlConst.SL_EXECUTION_ID,executionId);(0,cookie_utils_1.setCookie)(SlConst.SL_TEST_NAME,testName);(0,utils_1.sendAckEvent)(detail)}exports.setBaggageHandler=setBaggageHandler;function setContextHandler(detail,contextMessageManager,withOpenTelemetry,logger){var _a;logger.info(`setContext: Received event "detail": ${JSON.stringify(detail,null,4)}`);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED,1);if(!detail){logger.info(`Received setContext event with no detail, not changing context.`);return}if((0,utils_1.checkIsDiagnosisBaggage)(detail[SlConst.SL_BAGGAGE_HEADER])){return(0,utils_1.sendAckEvent)(detail)}detail.persist=detail.persist!==false;if(detail.persist){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST,1);sessionStorage.setItem(SlConst.SL_SESSION_CONTEXT,JSON.stringify(detail))}dispatchEvent(new CustomEvent(SlConst.EVENTS.SET_BAGGAGE,{detail:Object.assign(Object.assign({},(_a=detail[SlConst.SL_BAGGAGE_HEADER])!==null&&_a!==void 0?_a:{}),{incrementSetEvents:false})}));delete detail[SlConst.SL_BAGGAGE_HEADER];if(withOpenTelemetry){SlContext=SlContext.setValue(api.createContextKey(SlConst.CONTEXT),detail)}(0,utils_1.sendAckEvent)(detail)}exports.setContextHandler=setContextHandler;function deleteContextHandler(contextMessageManager,colorContextManager){SlContext=SlContext.deleteValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));SlContext=SlContext.deleteValue(api.createContextKey(SlConst.CONTEXT));colorContextManager.setCurrentTestIdentifier(null,null);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED,1);(0,cookie_utils_1.deleteCookie)(SlConst.SL_TEST_NAME);(0,cookie_utils_1.deleteCookie)(SlConst.SL_EXECUTION_ID)}exports.deleteContextHandler=deleteContextHandler;function deleteBaggageHandler(contextMessageManager,colorContextManager){SlContext=SlContext.deleteValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));colorContextManager.setCurrentTestIdentifier(null,null);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED,1);(0,cookie_utils_1.deleteCookie)(SlConst.SL_TEST_NAME);(0,cookie_utils_1.deleteCookie)(SlConst.SL_EXECUTION_ID)}exports.deleteBaggageHandler=deleteBaggageHandler})},{"../../../common/agent-events/cockpit-notifier":234,"../agent-factory":176,"./const":195,"./context-message-manager":196,"./cookie-utils":197,"./utils":203,"@opentelemetry/api":18}],199:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation-fetch","../utils","../context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CustomFetchInstrumentation=exports.handleAddHeaders=void 0;const instrumentation_fetch_1=require("@opentelemetry/instrumentation-fetch");const utils_1=require("../utils");const context_message_manager_1=require("../context-message-manager");const setPropagationHeaders=(options,contextPropagationHeaders)=>{for(const[key,value]of Object.entries(contextPropagationHeaders)){if(value){options.headers.set(key,typeof value==="string"?value:String(value))}}};function handleAddHeaders(options,spanUrl,allowCORS,logger){const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();const allowHeadersPropagation=(0,utils_1.shouldAddHeaders)(window.location.origin,spanUrl,allowCORS);if(!allowHeadersPropagation){if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}const originLog={current:window.location.origin,target:spanUrl};logger.warn(`Not adding header in CustomFetchInstrumentation because of origin difference: ${JSON.stringify(originLog,null,4)}`);return}const contextPropagationHeaders=Object.assign(Object.assign({},(0,utils_1.constructBaggageHeader)()),(0,utils_1.constructContextHeaders)());if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(Object.keys(contextPropagationHeaders).length?context_message_manager_1.CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}if(options instanceof Request&&contextPropagationHeaders){setPropagationHeaders(options,contextPropagationHeaders)}else if(options.headers instanceof Headers&&contextPropagationHeaders){setPropagationHeaders(options,contextPropagationHeaders)}else if(typeof options.headers==="object"&&options.headers!==null){for(const[key,value]of Object.entries(contextPropagationHeaders)){options.headers[key]=value}}else{options.headers=Object.assign({},contextPropagationHeaders,options.headers||{})}}exports.handleAddHeaders=handleAddHeaders;class CustomFetchInstrumentation extends instrumentation_fetch_1.FetchInstrumentation{constructor(config){super(config);this["_addHeaders"]=(options,spanUrl)=>{handleAddHeaders(options,spanUrl,config.allowCORS,config.logger)}}}exports.CustomFetchInstrumentation=CustomFetchInstrumentation})},{"../context-message-manager":196,"../utils":203,"@opentelemetry/instrumentation-fetch":89}],200:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation-xml-http-request","../utils","../context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CustomXMLHttpRequestInstrumentation=exports.handleAddHeaders=void 0;const instrumentation_xml_http_request_1=require("@opentelemetry/instrumentation-xml-http-request");const utils_1=require("../utils");const context_message_manager_1=require("../context-message-manager");function handleAddHeaders(xhr,spanUrl,allowCORS,logger){const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();const allowHeadersPropagation=(0,utils_1.shouldAddHeaders)(window.location.origin,spanUrl,allowCORS);if(!allowHeadersPropagation){if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}const originLog={current:window.location.origin,target:spanUrl};logger.warn(`Not adding header in CustomXMLHttpRequestInstrumentation because of origin difference: ${JSON.stringify(originLog,null,4)}`);return}const headers=Object.assign(Object.assign({},(0,utils_1.constructBaggageHeader)()),(0,utils_1.constructContextHeaders)());if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(Object.keys(headers).length?context_message_manager_1.CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}Object.keys(headers).forEach(headerKey=>{xhr.setRequestHeader(headerKey,headers[headerKey])})}exports.handleAddHeaders=handleAddHeaders;class CustomXMLHttpRequestInstrumentation extends instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation{constructor(config){super(config);this["_addHeaders"]=(xhr,spanUrl)=>{handleAddHeaders(xhr,spanUrl,config.allowCORS,config.logger)}}}exports.CustomXMLHttpRequestInstrumentation=CustomXMLHttpRequestInstrumentation})},{"../context-message-manager":196,"../utils":203,"@opentelemetry/instrumentation-xml-http-request":93}],201:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./otel","./events","./const"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.registerEventsBridge=void 0;const otel_1=require("./otel");const events_1=require("./events");const const_1=require("./const");const registerEventsBridge=(logger,enableOpenTelemetry,sendCockpitEvents=true,allowCORS)=>{var _a,_b,_c,_d;const eventsBridgeRegistered=(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)===null||_b===void 0?void 0:_b.loaded;const otelRegistered=(_d=(_c=window.$Sealights)===null||_c===void 0?void 0:_c.eventsBridge)===null||_d===void 0?void 0:_d.otel;if(!eventsBridgeRegistered){(0,events_1.registerEvents)(logger,enableOpenTelemetry,sendCockpitEvents)}if(enableOpenTelemetry&&!otelRegistered){(0,otel_1.registerOpenTelemetry)(logger,allowCORS)}const event=new Event(const_1.EVENTS.READY_EVENTS_BRIDGE);window.dispatchEvent(event)};exports.registerEventsBridge=registerEventsBridge})},{"./const":195,"./events":198,"./otel":202}],202:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation","./implementations/CustomFetchInstrumentation","./implementations/CustomXMLHttpRequestInstrumentation","../../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.registerOpenTelemetry=void 0;const instrumentation_1=require("@opentelemetry/instrumentation");const CustomFetchInstrumentation_1=require("./implementations/CustomFetchInstrumentation");const CustomXMLHttpRequestInstrumentation_1=require("./implementations/CustomXMLHttpRequestInstrumentation");const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const registerOpenTelemetry=(logger,allowCORS)=>{try{(0,instrumentation_1.registerInstrumentations)({instrumentations:[new CustomFetchInstrumentation_1.CustomFetchInstrumentation({allowCORS:allowCORS,logger:logger}),new CustomXMLHttpRequestInstrumentation_1.CustomXMLHttpRequestInstrumentation({allowCORS:allowCORS,logger:logger})]})}catch(error){logger.error(`An error occurred while registering OpenTelemetry Fetch/XMLHttp instrumentation.`,error);window.$Sealights.eventsBridge.error=error;cockpit_notifier_1.CockpitNotifier.sendError(JSON.stringify(error,Object.getOwnPropertyNames(error)))}};exports.registerOpenTelemetry=registerOpenTelemetry})},{"../../../common/agent-events/cockpit-notifier":234,"./implementations/CustomFetchInstrumentation":199,"./implementations/CustomXMLHttpRequestInstrumentation":200,"@opentelemetry/instrumentation":98}],203:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./const","./const"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSealightsAPI=exports.shouldAddHeaders=exports.sendAckEvent=exports.checkIsDiagnosisBaggage=exports.constructContextHeaders=exports.constructBaggageHeader=exports.mapHeaderValuesToString=void 0;const const_1=require("./const");const SlConst=require("./const");const mapHeaderValuesToString=headerValues=>{return Object.keys(headerValues!==null&&headerValues!==void 0?headerValues:{}).map(key=>{return`${key}=${headerValues[key]}`}).join()};exports.mapHeaderValuesToString=mapHeaderValuesToString;const constructBaggageHeader=()=>{var _a,_b;const{getBaggage}=((_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)||{};const baggage=(_b=getBaggage===null||getBaggage===void 0?void 0:getBaggage())!==null&&_b!==void 0?_b:{};if(!Object.keys(baggage).length){return{}}return{baggage:(0,exports.mapHeaderValuesToString)(baggage)}};exports.constructBaggageHeader=constructBaggageHeader;const constructContextHeaders=()=>{var _a,_b;const{getContext}=((_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)||{};const contextHeaders=(_b=getContext===null||getContext===void 0?void 0:getContext())!==null&&_b!==void 0?_b:{};if(!Object.keys(contextHeaders).length){return{}}const headers={};Object.entries(contextHeaders).forEach(entry=>{const[key,value]=entry;if(typeof value==="string"){headers[key]=value}else{headers[key]=(0,exports.mapHeaderValuesToString)(value)}});return headers};exports.constructContextHeaders=constructContextHeaders;const checkIsDiagnosisBaggage=baggage=>{const testName=baggage===null||baggage===void 0?void 0:baggage[const_1.SL_TEST_NAME];return testName===null||testName===void 0?void 0:testName.includes(const_1.SL_CONTEXT_DIAGNOSIS)};exports.checkIsDiagnosisBaggage=checkIsDiagnosisBaggage;const sendAckEvent=detail=>{dispatchEvent(new CustomEvent(SlConst.EVENTS.ACK_CONTEXT,{detail:detail}))};exports.sendAckEvent=sendAckEvent;const shouldAddHeaders=(origin,spanUrl,allowCORS)=>{if((allowCORS===null||allowCORS===void 0?void 0:allowCORS.trim())==="*")return true;const isRelativeUrl=const_1.relativePathRegex.test(spanUrl);if(isRelativeUrl){spanUrl=`${origin}${spanUrl.startsWith("/")?"":"/"}${spanUrl}`}const allowCORSArray=!(allowCORS===null||allowCORS===void 0?void 0:allowCORS.length)?[origin]:allowCORS===null||allowCORS===void 0?void 0:allowCORS.split(",");return allowCORSArray.some(propagationOrigin=>spanUrl===null||spanUrl===void 0?void 0:spanUrl.startsWith(propagationOrigin.trim()))};exports.shouldAddHeaders=shouldAddHeaders;const isSealightsAPI=spanUrl=>{try{const url=new URL(spanUrl);return url.origin.includes("sealights")}catch(error){return false}};exports.isSealightsAPI=isSealightsAPI})},{"./const":195}],204:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FeatureDetection=void 0;class FeatureDetection{constructor(window){this.window=window;if(!window)throw new Error("'window' cannot be null or undefined")}hasBeaconAPI(){const result=window.navigator&&this.isFunction(window.navigator["sendBeacon"]);return result}hasConsoleLogAPI(){const result=window.console&&this.isFunction(window.console.log);return result}hasJsonAPI(){const result=JSON&&this.isFunction(JSON.stringify)&&this.isFunction(JSON.parse);return result}isFunction(o){return o&&typeof o==="function"}}exports.FeatureDetection=FeatureDetection})},{}],205:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/footprints-item-data","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsQueueSender=void 0;const footprints_item_data_1=require("./entities/footprints-item-data");const system_date_1=require("../../common/system-date");class FootprintsQueueSender{constructor(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsQueue,window,logger,slMappingLoader){this.watchdog=watchdog;this.lightBackendProxy=lightBackendProxy;this.codeCoverageManager=codeCoverageManager;this.stateTracker=stateTracker;this.testStateHelper=testStateHelper;this.environmentData=environmentData;this.configuration=configuration;this.footprintsQueue=footprintsQueue;this.window=window;this.logger=logger;this.slMappingLoader=slMappingLoader;this.isStarted=false;if(watchdog==null)throw new Error("'watchdog' cannot be null or undefined");if(lightBackendProxy==null)throw new Error("'lightBackendProxy' cannot be null or undefined");if(codeCoverageManager==null)throw new Error("'codeCoverageManager' cannot be null or undefined");if(stateTracker==null)throw new Error("'stateTracker' cannot be null or undefined");if(testStateHelper==null)throw new Error("'testStateHelper' cannot be null or undefined");if(environmentData==null)throw new Error("'environmentData' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(footprintsQueue==null)throw new Error("'footprintsQueue' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(logger==null)throw new Error("'logger' cannot be null or undefined");this.context=this;this.watchdog.addOnAlarmListener(()=>{this.context.onTimerTick()})}onTimerTick(){if(!this.stateTracker.shouldCollectFootprints()){return}const footprints=this.getCurrentFootprints();this.send(footprints)}start(){if(this.isStarted)return;this.watchdog.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId);this.isStarted=true}stop(){if(!this.isStarted)return;this.watchdog.stop();this.isStarted=false}send(footprintsData,async=true,shouldRequeue=true){if(!footprintsData){this.logger.info("No need to send footprints as the 'footprintsData' is null or undefined.");return}const request=this.createRequest(footprintsData);if(request==null){this.logger.info("No need to send footprints as the request is empty.");return}const context=this;const onSuccess=function(){context.logger.info("Sent footprints successfully")};const onError=function(response){context.logger.error("Failed while trying to send footprints. response.responseText: '"+response.responseText+"'. response.statusCode:"+response.statusCode);if(shouldRequeue){context.logger.info("Requeuing footprints again");context.footprintsQueue.requeueItems(footprintsData)}};this.lightBackendProxy.submitRequest(request,onSuccess,onError,async)}sendAllSync(){if(!this.stateTracker.shouldCollectFootprints()){return}this.logger.info("Sending all remaining footprints synchronously.");this.delayIfHasRequestsInProgress();const async=false;const footprints=this.getCurrentFootprints();this.send(footprints,async)}sendAll(){const footprints=this.getCurrentFootprints();this.send(footprints)}delayIfHasRequestsInProgress(){let counter=this.configuration.delayShutdownInSeconds||30;while(this.lightBackendProxy.hasRequestsInProgress()&&counter-- >0){this.logger.info("Has other requests in progress. Sleeping.. # of requests: "+this.lightBackendProxy.getRequestsInProgressCount()+". Remaining retries: "+counter);this.sleep(1e3)}}pushCurrentFootprints(){if(!this.stateTracker.shouldCollectFootprints()){return}const testId=this.stateTracker.getCurrentTestIdentifier();const testInfo=this.testStateHelper.splitTestIdToExecutionAndTestName(testId);const footprints=this.codeCoverageManager.getFootprints(testInfo);if(this.configuration.resolveWithoutHash){this.enqueueV5Footprints(footprints)}else{this.enqueueV2Footprints(footprints,testInfo)}}enqueueV2Footprints(appsAndFootprintsArray,testInfo){if(appsAndFootprintsArray&&appsAndFootprintsArray.length){const queueItem=new footprints_item_data_1.FootprintsItemData;queueItem.testName=testInfo.testName;queueItem.executionId=testInfo.executionId;queueItem.apps=appsAndFootprintsArray;this.footprintsQueue.enqueueItem(queueItem)}}enqueueV5Footprints(footprintsRequest){if(!footprintsRequest)return;if(!footprintsRequest.apps||footprintsRequest.apps.length==0)return;if(!footprintsRequest.tests||footprintsRequest.tests.length==0)return;this.footprintsQueue.enqueueItem(footprintsRequest)}getCurrentFootprints(){this.pushCurrentFootprints();return this.footprintsQueue.getQueueContentsAndEmptyQueue()}createRequest(data){if(this.configuration.resolveWithoutHash){return this.createV5FootprintsRequest(data)}return this.createV2FootprintsRequest(data)}createV5FootprintsRequest(footprintsData){const originalRequest=footprintsData[0];if(!originalRequest){return null}if(!this.hasApps(originalRequest)||!this.hasTests(originalRequest)){return null}const request={};request.customerId=this.configuration.customerId;request.environment=this.environmentData;request.configurationData=this.configuration;request.apps=originalRequest.apps;request.tests=originalRequest.tests;request.meta=originalRequest.meta;return request}createV2FootprintsRequest(appsAndFootprintsArray){if(!appsAndFootprintsArray||!appsAndFootprintsArray.length){return null}const request={};request.customerId=this.configuration.customerId;request.items=appsAndFootprintsArray;request.environment=this.environmentData;request.configurationData=this.configuration;return request}sleep(millis){const start=(0,system_date_1.getSystemDateValueOf)();let end=null;do{end=(0,system_date_1.getSystemDateValueOf)()}while(end-start<millis)}hasApps(request){return request.apps&&request.apps.length>0}hasTests(request){return request.tests&&request.tests.length>0}}exports.FootprintsQueueSender=FootprintsQueueSender})},{"../../common/system-date":275,"./entities/footprints-item-data":194}],206:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./logger/log-factory","../../common/footprints-process-v6/location-formatter","../../common/footprints-process/collection-interval","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConvertorV3=void 0;const log_factory_1=require("./logger/log-factory");const location_formatter_1=require("../../common/footprints-process-v6/location-formatter");const collection_interval_1=require("../../common/footprints-process/collection-interval");const system_date_1=require("../../common/system-date");class IstanbulToFootprintsConvertorV3{constructor(window,cfg){this.window=window;this.cfg=cfg;this.totalTests=0;if(!window)throw new Error("window is required");if(!cfg)throw new Error("cfg is required");this.collectionInterval=new collection_interval_1.CollectionInterval(this.cfg.interval*1e3);this.logger=log_factory_1.LogFactory.createLogger("IstanbulToFootprintsConvertor")}resetState(){this.totalTests=0;this.eidToHitsIndex={};this.uniqueIdToElement={};this.testNameToTestData={};this.fileNameToAppFile={};this.collectionInterval.next()}convert(istanbulFootprints,testName,executionId,mockTime){this.resetState();const result=this.createFootprintsFile();const app=result.apps[0];const localTime=mockTime?mockTime:(0,system_date_1.getSystemDateValueOf)();const test=this.getOrCreateTestData(testName,executionId,localTime,result);for(const moduleName in istanbulFootprints){const istanbulModule=istanbulFootprints[moduleName];if(!istanbulModule){continue}const scopeData={test:test,app:app,modulePath:istanbulModule.path.replace(/\\/g,"/"),istanbulModule:istanbulModule};if(istanbulModule.f){this.addMethodsWithHits(scopeData)}if(istanbulModule.b){this.addBranchesWithHits(scopeData)}}result.apps=this.filterAppsWithoutHits(result.apps);return result}filterAppsWithoutHits(apps){if(!apps)return apps;return apps.filter(app=>this.filterFilesWithoutHits(app))}filterFilesWithoutHits(app){let hasFiles=false;if(!app||!app.files){return hasFiles}app.files=app.files.filter(file=>this.filterElementsWithoutHits(file));hasFiles=app.files.length>0;return hasFiles}filterElementsWithoutHits(file){const hasMethodHits=this.filterElementWithoutHits(file,"methods");const hasBranchHits=this.filterElementWithoutHits(file,"branches");const hasLineHits=this.filterElementWithoutHits(file,"lines");const hasHits=hasMethodHits||hasBranchHits||hasLineHits;return hasHits}filterElementWithoutHits(file,coverageType){const fileObject=file;let arrayOfCodeElements=fileObject[coverageType]||[];arrayOfCodeElements=arrayOfCodeElements.filter(ce=>this.hasHit(ce));fileObject[coverageType]=arrayOfCodeElements;const hasHits=arrayOfCodeElements.length>0;return hasHits}hasHit(element){const hasHitInAnyTest=element.hits.some(hitToTest=>hitToTest[1]>0);return hasHitInAnyTest}addMethodsWithHits(scopeData){const istanbulModule=scopeData.istanbulModule;for(const methodId in istanbulModule.f){const hits=istanbulModule.f[methodId];if(hits>0){const methodData=istanbulModule.fnMap[methodId];this.addOrUpdateMethodElement(scopeData,methodData,hits)}}}addBranchesWithHits(scopeData){const istanbulModule=scopeData.istanbulModule;for(const branchId in istanbulModule.b){const probesArray=istanbulModule.b[branchId];for(let idx=0;idx<probesArray.length;idx++){const hits=probesArray[idx];if(hits>0){const branchData=istanbulModule.branchMap[branchId];this.addOrUpdateBranchElement(scopeData,branchData,idx,hits)}}}}addOrUpdateMethodElement(scopeData,methodData,hits){const loc=methodData.loc||methodData.lc;const decl=methodData.decl||methodData.d;this.addOrUpdateElement(scopeData,loc,hits,this.getOrCreateMethodElement,false);if(decl){this.addOrUpdateElement(scopeData,decl,hits,this.getOrCreateMethodElement,false)}}addOrUpdateBranchElement(scopeData,branchData,probeIndex,hits){const locations=branchData.locations||branchData.lcs;const probePositionData=locations[probeIndex];this.addOrUpdateElement(scopeData,probePositionData,hits,this.getOrCreateBranchElement,true,probeIndex)}addOrUpdateElement(scopeData,startPositionData,hits,getOrCreateElement,isBranch,probIndex){const file=this.getOrCreateFootprintsAppFile(scopeData.modulePath,scopeData.app);const startPosition=startPositionData.start||startPositionData.st;const uniqueId=this.createUniqueId(startPosition,scopeData.modulePath,isBranch,probIndex);if(!uniqueId){return}const element=getOrCreateElement.call(this,uniqueId,file);this.addOrUpdateElementHits(scopeData.test,uniqueId,element,hits)}createUniqueId(startPosition,fullFilePath,isBranch,probIndex){const delimiter=isBranch?"|":"@";let uniqueId=fullFilePath+delimiter+this.formatLoc(startPosition);if(probIndex!=null){uniqueId+="|"+probIndex}const mapping=this.window.slMappings[this.cfg.buildSessionId];if(mapping){uniqueId=mapping[uniqueId]||uniqueId}return uniqueId}addOrUpdateElementHits(testData,elementUniqueId,element,hits){const HITS_INDEX=1;const eid=elementUniqueId+"|"+testData.index;const index=this.eidToHitsIndex[eid];if(index!=null){const testIndexAndHits=element.hits[index];let elementHits=testIndexAndHits[HITS_INDEX];elementHits=elementHits+hits;testIndexAndHits[HITS_INDEX]=elementHits}else{const testIndexAndHits=new Array;testIndexAndHits.push(testData.index);testIndexAndHits.push(hits);const length=element.hits.push(testIndexAndHits);this.eidToHitsIndex[eid]=length-1}}getOrCreateTestData(testName,executionId,localTime,result){if(!this.testNameToTestData[testName]){const test={executionId:executionId,localTime:localTime,testName:testName,collectionInterval:this.collectionInterval.toJson()};result.tests.push(test);this.testNameToTestData[testName]={index:this.totalTests++,test:test}}return this.testNameToTestData[testName]}getOrCreateMethodElement(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){const x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;file.methods.push(x)}return this.uniqueIdToElement[uniqueId]}getOrCreateBranchElement(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){const x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;if(file.branches)file.branches.push(x)}return this.uniqueIdToElement[uniqueId]}getOrCreateFootprintsAppFile(fileName,app){if(this.fileNameToAppFile[fileName]){return this.fileNameToAppFile[fileName]}const file={methods:new Array,branches:new Array,lines:new Array,path:fileName};app.files.push(file);this.fileNameToAppFile[fileName]=file;return file}createFootprintsFile(){const result={configurationData:{},customerId:this.cfg.customerId,environment:{},tests:[],apps:[],meta:{}};this.fileNameToAppFile={};this.testNameToTestData={};const app={appName:this.cfg.appName,branchName:this.cfg.branchName,buildName:this.cfg.buildName,moduleName:"",buildSessionId:this.cfg.buildSessionId,files:new Array};result.apps.push(app);return result}formatLoc(loc){return(0,location_formatter_1.formatLocation)(loc,this.logger)}}exports.IstanbulToFootprintsConvertorV3=IstanbulToFootprintsConvertorV3})},{"../../common/footprints-process-v6/location-formatter":264,"../../common/footprints-process/collection-interval":266,"../../common/system-date":275,"./logger/log-factory":209}],207:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConverter=void 0;const utils_1=require("./utils");class IstanbulToFootprintsConverter{constructor(window,configuration){this.window=window;this.configuration=configuration;if(configuration==null)throw new Error("'configuration' cannot be null or undefined")}convert(istanbulFootprints){const apps={};const appsArray=new Array;if(istanbulFootprints){const context=this;Object.keys(istanbulFootprints).forEach(function(moduleName){const m=istanbulFootprints[moduleName];context.configuration.appName=context.configuration.appName||"";let a=apps[context.configuration.appName];let isNewApp=false;if(!a){a={appName:context.configuration.appName,build:context.configuration.buildName,branch:context.configuration.branchName,footprints:[]};isNewApp=true}const footprints=a.footprints;let filename=m.path;filename=filename.replace(/\\/g,"/");Object.keys(m.f).forEach(function(funcId){const funcInfo=m.fnMap[funcId];if(!funcInfo||funcInfo.skip)return;if(m.f[funcId]>0){const mn=context.getMethodName(funcInfo.name,funcInfo.guessedName);let pos=context.formatLoc(funcInfo.loc.originalStart||funcInfo.loc.start);if(m.inputSourceMap&&context.window["sourceMap"]){const sourceMapConsumer=new context.window["sourceMap"].SourceMapConsumer(m.inputSourceMap);pos=context.formatLoc(sourceMapConsumer.originalPositionFor(funcInfo.loc.start))}filename=funcInfo.originalFilename||filename;filename=context.getRelativeModulePath(filename);const fqmn=[mn,filename,pos].join("@");const hash=funcInfo.hash&&funcInfo.hash.hash;const footprintsItem={name:fqmn,hits:m.f[funcId],hash:hash,branches:new Array};if(m.fnToBranch&&m.fnToBranch[funcId]&&m.fnToBranch[funcId].length){m.fnToBranch[funcId].forEach(function(branchArray,index){const fileBranch=branchArray[0];const branchIndex=branchArray[1];if(m.b[fileBranch.toString()][branchIndex]>0){footprintsItem.branches.push(index)}})}footprints.push(footprintsItem)}});if(footprints.length&&isNewApp){appsArray.push(a);apps[a.appName]=a}})}return appsArray}getMethodName(name,guessedName){let mn=name||guessedName||"(Anonymous)";if(mn.indexOf("(anonymous")>=0){mn="(Anonymous)"}return mn}formatLoc(loc){return[loc.line,loc.column].join(",")}getRelativeModulePath(path){const workspacepath=utils_1.Utils.adjustPathSlashes(this.configuration.workspacepath);path=utils_1.Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path}}exports.IstanbulToFootprintsConverter=IstanbulToFootprintsConverter})},{"./utils":223}],208:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/system-date","../configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=exports.LogLevels=void 0;const system_date_1=require("../../../common/system-date");const configuration_override_1=require("../configuration-override");var LogLevels;(function(LogLevels){LogLevels["TRACE"]="trace";LogLevels["DEBUG"]="debug";LogLevels["INFO"]="info";LogLevels["WARNING"]="warning";LogLevels["ERROR"]="error";LogLevels["CRITICAL"]="critical";LogLevels["FATAL"]="fatal"})(LogLevels=exports.LogLevels||(exports.LogLevels={}));class ConsoleLogger{constructor(level=LogLevels.INFO,selectedLogLevels=null){var _a,_b;this.level=level;this.selectedLogLevels=selectedLogLevels;this.logFn=()=>{};this.stringifyFn=o=>{return""};this.context={};(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.on(configuration_override_1.ConfigChangedEvents.LOG_LEVEL_CHANGED,this.initLogLevels.bind(this));if(!selectedLogLevels)this.initLogLevels(level);this.initStringifyFn();this.initLogFn()}withLogLevel(level){const c=new ConsoleLogger(this.level);c.context=this.context;return c}initLogFn(){if(console&&typeof console.log=="function"){this.logFn=o=>{const line=this.stringifyFn(o);console.log(line)}}else{}}initStringifyFn(){if(JSON&&typeof JSON.stringify=="function"){this.stringifyFn=JSON.stringify}else{this.stringifyFn=this.crudeStringifier}}crudeStringifier(o){const strParts=Array();for(const p in o){strParts.push(p+"="+o[p].toString())}return strParts.join(", ")}initLogLevels(level){const orderedLogLevels=[LogLevels.TRACE,LogLevels.DEBUG,LogLevels.INFO,LogLevels.WARNING,LogLevels.ERROR,LogLevels.CRITICAL,LogLevels.FATAL];const logLevel=level.toLowerCase();const minIdx=orderedLogLevels.indexOf(logLevel);if(minIdx===-1){this.handleLevelNotFound(level)}else{this.selectedLogLevels={};for(let i=0;i<orderedLogLevels.length;i++){this.selectedLogLevels[orderedLogLevels[i]]=i>=minIdx}}}handleLevelNotFound(logLevel){if(logLevel=="off"){this.selectedLogLevels={}}}internalLog(logLevel,logMsg,obj){if(!this.selectedLogLevels||!this.selectedLogLevels[logLevel])return;const logObject={level:logLevel.toUpperCase(),ts:(0,system_date_1.getSystemDate)().toISOString(),msg:logMsg?logMsg.toString():undefined};const ctx=this.context;for(const p in ctx){logObject[p]=ctx[p]}if(obj){if(obj instanceof Error){logObject.error=obj.toString()}else if(obj instanceof Object){for(const p in obj){logObject[p]=obj[p]}}else{logObject.data=obj}}this.logFn(logObject)}clone(){const c=new ConsoleLogger(this.level,this.selectedLogLevels);const _t=this.context;for(const p in _t){c.context[p]=_t[p]}return c}withClass(className){const c=this.clone();c.context.className=className;delete c.context.methodName;return c}withMethod(methodName){const c=this.clone();c.context.methodName=methodName;return c}withTx(tx){const c=this.clone();c.context.tx=tx;return c}withComponent(componentName,componentVersion){const c=this.clone();c.context.componentName=componentName;c.context.componentVersion=componentVersion;return c}withActivity(activityName){const c=this.clone();c.context.activityName=activityName;return c}withProperty(propName,propValue){const c=this.clone();c.context[propName]=propValue;return c}withProperties(objWithProperties,propNames){const c=this.clone();if(!propNames){propNames=Object.keys(objWithProperties)}propNames.forEach(function(pn){c.context[pn]=objWithProperties[pn]});return c}fatal(logMsg,obj){this.internalLog(LogLevels.FATAL,logMsg,obj)}critical(logMsg,obj){this.internalLog(LogLevels.CRITICAL,logMsg,obj)}error(logMsg,obj){this.internalLog(LogLevels.ERROR,logMsg,obj)}warn(logMsg,obj){this.internalLog(LogLevels.WARNING,logMsg,obj)}info(logMsg,obj){this.internalLog(LogLevels.INFO,logMsg,obj)}debug(logMsg,obj){this.internalLog(LogLevels.DEBUG,logMsg,obj)}trace(logMsg,obj){this.internalLog(LogLevels.TRACE,logMsg,obj)}}exports.ConsoleLogger=ConsoleLogger})},{"../../../common/system-date":275,"../configuration-override":188}],209:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./null-logger","./console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LogFactory=void 0;const null_logger_1=require("./null-logger");const console_logger_1=require("./console-logger");class LogFactory{static createLogger(className,logLevel){try{const logger=new console_logger_1.ConsoleLogger(logLevel);logger.withClass(className);return logger}catch(e){return null_logger_1.NullLogger.INSTANCE}}}exports.LogFactory=LogFactory})},{"./console-logger":208,"./null-logger":210}],210:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NullLogger=void 0;class NullLogger{fatal(logMsg,obj){}critical(logMsg,obj){}error(logMsg,obj){}warn(logMsg,obj){}info(logMsg,obj){}debug(logMsg,obj){}trace(logMsg,obj){}withClass(className){return NullLogger.INSTANCE}withMethod(methodName){return NullLogger.INSTANCE}withTx(tx){return NullLogger.INSTANCE}withComponent(componentName,componentVersion){return NullLogger.INSTANCE}withActivity(activityName){return NullLogger.INSTANCE}withProperty(propName,propValue){return NullLogger.INSTANCE}withProperties(objWithProperties,propNames){return NullLogger.INSTANCE}withLogLevel(level){return NullLogger.INSTANCE}}exports.NullLogger=NullLogger;NullLogger.INSTANCE=new NullLogger})},{}],211:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../entities/footprints-item-data","../delegate","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemsQueue=void 0;const footprints_item_data_1=require("../entities/footprints-item-data");const delegate_1=require("../delegate");const system_date_1=require("../../../common/system-date");class FootprintsItemsQueue{constructor(configuration){this.maxItemsInQueue=500;this.queueSize=0;this.queue=new Array;this.onQueueFull=new delegate_1.Delegate;this.isQueueFull=function(){return this.getCurrentQueueSize()>=this.maxItemsInQueue};if(!configuration)throw new Error("'configuration' cannot be null or undefined");this.enabled=configuration.enabled;this.maxItemsInQueue=configuration.maxItemsInQueue}setEnabled(isEnabled){isEnabled=!!isEnabled;if(isEnabled!==this.enabled){this.enabled=isEnabled}if(!isEnabled){this.queue=new Array}}getEnabled(){return this.enabled}enqueueItem(footprintsItem){if(!this.enabled){return}footprintsItem=footprintsItem||new footprints_item_data_1.FootprintsItemData;footprintsItem.localTime=(0,system_date_1.getSystemDateValueOf)();this.queue.push(footprintsItem);this.queueSize++;this.checkQueueSize()}checkQueueSize(){if(this.isQueueFull()){this.onQueueFull.fire()}}getCurrentQueueSize(){return this.queueSize}requeueItems(footprintsItems){if(!this.enabled){return}const context=this;footprintsItems.forEach(function(item){context.queue.push(item);context.queueSize+=1});this.checkQueueSize()}getQueueContentsAndEmptyQueue(){const returnedItems=this.queue;this.queue=new Array;this.queueSize=0;return returnedItems}}exports.FootprintsItemsQueue=FootprintsItemsQueue})},{"../../../common/system-date":275,"../delegate":190,"../entities/footprints-item-data":194}],212:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Queue=void 0;const validation_utils_1=require("../../../common/utils/validation-utils");class Queue{constructor(onQueueFull){this.queue=[];this._maxItemsInQueue=Queue.DEFAULT_MAX_ITEMS_IN_QUEUE;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(onQueueFull,"onQueueFull");this.onQueueFull=onQueueFull}requeue(items){if(!items||!items.length){return}this.queue=items.concat(this.queue)}enqueue(item){this.queue.push(item);if(this._maxItemsInQueue===this.queue.length){this.onQueueFull.fire()}}getQueueSize(){return this.queue.length}dequeue(size){if(!size){size=this.queue.length}if(this.queue.length===0){return[]}if(size>this.queue.length){size=this.queue.length}const dequeuedItems=this.queue.splice(0,size);return dequeuedItems}clear(){this.queue=[]}on(event,listener){this.onQueueFull.addListener(listener);return this}get maxItemsInQueue(){return this._maxItemsInQueue}set maxItemsInQueue(value){this._maxItemsInQueue=value}}exports.Queue=Queue;Queue.DEFAULT_MAX_ITEMS_IN_QUEUE=1e3})},{"../../../common/utils/validation-utils":280}],213:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./http-response"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;const http_response_1=require("./http-response");const REQUEST_DONE_STATE_CODE=4;class HttpClient{constructor(window,featureDetection,logger){this.window=window;this.featureDetection=featureDetection;this.logger=logger;if(window==null)throw new Error("'window' cannot be null or undefined");if(featureDetection==null)throw new Error("'featureDetection' cannot be null or undefined")}send(request,onSuccess,onError){if(!request.url)return;const url=request.url;const httpMethod=request.httpMethod;const httpRequest=new XMLHttpRequest;httpRequest.open(httpMethod,url,request.async);if(request.headers){for(let i=0;i<request.headers.length;i++){const header=request.headers[i];if(header&&header.name&&header.value){httpRequest.setRequestHeader(header.name,header.value)}}}httpRequest.onreadystatechange=function(){if(httpRequest.readyState===REQUEST_DONE_STATE_CODE){const httpResponse=new http_response_1.HttpResponse;httpResponse.statusCode=httpRequest.status;httpResponse.responseText=httpRequest.responseText;if(httpRequest.status===200){if(onSuccess){onSuccess(httpResponse)}}else{if(onError){onError(httpResponse)}}}};httpRequest.send(request.data)}}exports.HttpClient=HttpClient})},{"./http-response":215}],214:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpRequest=void 0;class HttpRequest{constructor(){this.async=true}}exports.HttpRequest=HttpRequest})},{}],215:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpResponse=void 0;class HttpResponse{}exports.HttpResponse=HttpResponse})},{}],216:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClientAdapter=void 0;const validation_utils_1=require("../../../../common/utils/validation-utils");class JsonClientAdapter{constructor(jsonClient,serverUrl,collectorUrl){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(jsonClient,"jsonClient");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(serverUrl,"serverUrl");this.jsonClient=jsonClient;this.serverUrl=serverUrl;this.collectorUrl=collectorUrl}delete(body,urlPath,callback){throw new Error("'delete' not implemented yet")}get(urlPath,callback,isNotFoundAcceptable=true,async=false){urlPath=`${this.getBaseUrl()}${urlPath}`;const onSuccess=response=>callback(null,response,response.statusCode);const onError=response=>{const error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.get(urlPath,onSuccess,onError,async)}put(requestData,urlPath,callback,async=true){throw new Error("'delete' not implemented yet")}post(requestData,urlPath,callback,async=true,contentType){urlPath=`${this.getBaseUrl()}${urlPath}`;const onSuccess=response=>callback(null,response,response.statusCode);const onError=response=>{const error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.post(urlPath,requestData,onSuccess,onError,async,contentType)}postMultipart(requestData,urlPath,callback){throw new Error("'postMultipart' not implemented yet")}updateMetadata(metadata){this.jsonClient.updateMetadata(metadata)}getBaseUrl(){if(this.collectorUrl){return this.collectorUrl}return this.serverUrl}}exports.JsonClientAdapter=JsonClientAdapter})},{"../../../../common/utils/validation-utils":280}],217:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../http/http-request","../../../../common/http/contracts","../../../../common/agent-events/agent-events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClient=void 0;const http_request_1=require("../http/http-request");const contracts_1=require("../../../../common/http/contracts");const agent_events_contracts_1=require("../../../../common/agent-events/agent-events-contracts");class JsonClient{constructor(httpClient,configuration,agentInstanceData){var _a;this.httpClient=httpClient;this.configuration=configuration;this.agentInstanceData=agentInstanceData;this.requestsInProgress=0;this.metadata={};this.requestsInProgress=0;this.updateMetadata({agentId:this.agentInstanceData.agentId,buildSessionId:(_a=this.configuration)===null||_a===void 0?void 0:_a.buildSessionId,agentType:agent_events_contracts_1.AgentTypes.BROWSER_AGENT,agentTechnology:agent_events_contracts_1.AgentTechnologies.BROWSER,labId:configuration.labId,appName:configuration.appName,branchName:configuration.branchName,buildName:configuration.buildName})}sendHttpRequest(request,onSuccess,onError,contentType){const context=this;try{this.requestsInProgress++;const httpRequest=new http_request_1.HttpRequest;httpRequest.headers=this.getHeaders(request.url,contentType,request.data);httpRequest.url=request.url;httpRequest.httpMethod=request.httpMethod;httpRequest.async=request.async;if(request.data!=null)httpRequest.data=JSON.stringify(request.data);this.httpClient.send(httpRequest,parseResponse,function(response){context.requestsInProgress--;if(onError!=null){onError(response)}})}catch(e){this.requestsInProgress--}function parseResponse(jsonResponse){try{let object;context.requestsInProgress--;if(jsonResponse&&jsonResponse.responseText&&jsonResponse.responseText!=""){object=JSON.parse(jsonResponse.responseText)}else{object=jsonResponse}if(onSuccess!=null){onSuccess(object)}}catch(e){if(onError!=null){jsonResponse.responseText="Failed parsing response. Response: '"+jsonResponse.responseText+"'";onError(jsonResponse)}}}}post(url,data,onSuccess,onError,async=true,contentType){this.send(url,data,onSuccess,onError,async,"POST",contentType)}get(url,onSuccess,onError,async=true,data){this.send(url,data,onSuccess,onError,async,"GET")}updateMetadata(metadata){this.metadata=Object.assign(Object.assign({},this.metadata),metadata)}send(url,data,onSuccess,onError,async=true,httpMethod,contentType){const request=new http_request_1.HttpRequest;request.url=url;request.data=data;request.httpMethod=httpMethod;request.async=async;this.sendHttpRequest(request,onSuccess,onError,contentType)}hasRequestsInProgress(){return this.requestsInProgress>0}createMetadataHeaders(messageType){return[{name:contracts_1.SealightsHeaderNames.LAB_ID,value:this.metadata.labId},{name:contracts_1.SealightsHeaderNames.BRANCH_NAME,value:this.metadata.branchName},{name:contracts_1.SealightsHeaderNames.BUILD_NAME,value:this.metadata.buildName},{name:contracts_1.SealightsHeaderNames.BSID,value:this.metadata.buildSessionId},{name:contracts_1.SealightsHeaderNames.EXECUTION_ID,value:this.metadata.executionId},{name:contracts_1.SealightsHeaderNames.AGENT_ID,value:this.metadata.agentId},{name:contracts_1.SealightsHeaderNames.APP_NAME,value:this.metadata.appName},{name:contracts_1.SealightsHeaderNames.MESSAGE_TYPE,value:messageType}]}getHeaders(url,contentType,requestData){var _a,_b,_c,_d;const headers=[{name:contracts_1.SealightsHeaderNames.CONTENT_TYPE,value:contentType||contracts_1.ContentType.JSON}];headers.push({name:contracts_1.SealightsHeaderNames.META_DATA,value:JSON.stringify(this.metadata)});const messageType=(_b=(_a=requestData===null||requestData===void 0?void 0:requestData.events)===null||_a===void 0?void 0:_a[0])===null||_b===void 0?void 0:_b.type;headers.push(...this.createMetadataHeaders(messageType));if((_c=this===null||this===void 0?void 0:this.configuration)===null||_c===void 0?void 0:_c.token){headers.push({name:contracts_1.SealightsHeaderNames.AUTHOTIZARTION,value:"Bearer "+((_d=this===null||this===void 0?void 0:this.configuration)===null||_d===void 0?void 0:_d.token)})}if(this.shouldAddCollectorRelatedHeaders(url)){headers.push({name:contracts_1.SealightsHeaderNames.MODE,value:contracts_1.SealightsHaderValues.LIGHT_AGENT_MODE})}return headers}shouldAddCollectorRelatedHeaders(url){const collectorUrl=this.configuration.collectorUrl;return collectorUrl&&url.indexOf(collectorUrl)==0}}exports.JsonClient=JsonClient})},{"../../../../common/agent-events/agent-events-contracts":227,"../../../../common/http/contracts":268,"../http/http-request":214}],218:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./json-client","../../logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopJsonClient=void 0;const json_client_1=require("./json-client");const log_factory_1=require("../../logger/log-factory");class NoopJsonClient extends json_client_1.JsonClient{constructor(){super(...arguments);this.logger=log_factory_1.LogFactory.createLogger("NoopJsonClient")}send(url,data,onSuccess,onError,async=true,httpMethod,contentType){this.logger.info(`noop json client not executing http request for url '${url}`);onSuccess({})}}exports.NoopJsonClient=NoopJsonClient})},{"../../logger/log-factory":209,"./json-client":217}],219:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LightBackendProxy=void 0;class LightBackendProxy{constructor(configuration,jsonClient,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.logger=logger}submitRequest(request,onSuccess,onError,async=true){const url=this.createServerUrl(this.configuration);this.jsonClient.post(url,request,onSuccess,onError,async)}hasRequestsInProgress(){return this.jsonClient.hasRequestsInProgress()}getRequestsInProgressCount(){return this.jsonClient.requestsInProgress}createServerUrl(configuration){if(configuration.token){const apiVersion=configuration.resolveWithoutHash?"/v5":"/v3";return configuration.server+apiVersion+"/agents/footprints/"}return configuration.server+"/v1/testfootprints/"}}exports.LightBackendProxy=LightBackendProxy})},{}],220:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/agent-events/cockpit-notifier","../../common/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlMappingLoader=void 0;const cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");const contracts_1=require("../../common/contracts");class SlMappingLoader{constructor(backendProxy,window,logger,configuration){this.backendProxy=backendProxy;this.window=window;this.logger=logger;this.configuration=configuration}loadSlMapping(buildSessionId){return __awaiter(this,void 0,void 0,function*(){this.window.slMappings=this.window.slMappings||{};if(!this.window.slMappings[buildSessionId]){try{if(this.configuration.footprintsMapping===contracts_1.FootprintsMapping.SERVER){this.loadEmptySlMapping(buildSessionId)}else{yield this.loadSlMappingFromBackend(buildSessionId)}}catch(err){const errMsg=`Error while trying to load slMapping from server '${err}'`;this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);this.window.slMappings[buildSessionId]={}}}})}loadSlMappingFromBackend(buildSessionId){return __awaiter(this,void 0,void 0,function*(){let flatted={};const slMappingArr=yield this.backendProxy.getSlMappingFromServer(buildSessionId);slMappingArr.forEach(mapping=>{flatted=Object.assign(Object.assign({},flatted),mapping)});this.window.slMappings[buildSessionId]=flatted})}loadEmptySlMapping(buildSessionId){this.window.slMappings[buildSessionId]={}}}exports.SlMappingLoader=SlMappingLoader})},{"../../common/agent-events/cockpit-notifier":234,"../../common/contracts":248}],221:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;const delegate_1=require("./delegate");const contracts_1=require("./contracts");class StateTracker{constructor(configuration,jsonClient,watchdog,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.watchdog=watchdog;this.logger=logger;this.colorChanged=new delegate_1.Delegate;this.setCurrentTestIdentifier(StateTracker.ANONYMOUS_FOOTPRINTS_COLOR);this.watchdog.addOnAlarmListener(()=>{this.checkForActiveExecution()});this.checkForActiveExecution(false);this.watchdog.start()}setCurrentTestIdentifier(newColorOnWindow){if(newColorOnWindow!=null){if(newColorOnWindow!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.stopWatchdog()}else{this.startWatchdog()}if(newColorOnWindow!=this.currentColorOnWindow){this.currentColorOnWindow=newColorOnWindow;this.colorChanged.fire()}}else if(this.currentColorOnWindow!=null&&newColorOnWindow==null){this.currentColorOnWindow=null;this.colorChanged.fire()}}getCurrentTestIdentifier(){return this.currentColorOnWindow}addOnColorChangedListener(listener){this.colorChanged.addListener(listener)}getCurrentColor(){return this.currentColorOnWindow}checkForActiveExecution(async=true){const url=this.configuration.server+`/v4/testExecution/${this.configuration.labId}`;this.logger.info(`[TO TST] - checkMappingStatus. Url '${url}'.`);const onSuccess=data=>{this.logger.info("[ACTIVE EXECUTION] Checking for active execution. No errors");if(data==null){this.logger.warn("[ACTIVE EXECUTION] Received empty response. not sending footprints.");this.hasActiveExecution=false;return}if(data.execution==null){this.logger.info("[ACTIVE EXECUTION] Couldn't find active execution. not sending footprints.");this.hasActiveExecution=false}else if(data.execution.status==contracts_1.ExecutionStatus.Ending){this.logger.info("[ACTIVE EXECUTION] Execution is pending delete. sending last footprints");this.hasActiveExecution=true}else if(data.execution.status==contracts_1.ExecutionStatus.InProgress){this.logger.info(`[ACTIVE EXECUTION] Active execution for labid '${this.configuration.labId}'`);this.hasActiveExecution=true}else{this.logger.warn(`[ACTIVE EXECUTION] Unexpected status. status: '${data.execution.status}'`);this.hasActiveExecution=false}};const onError=response=>{this.logger.error(`[ACTIVE EXECUTION] Error checking for active execution: '${response.responseText}'`);this.hasActiveExecution=false};this.jsonClient.get(url,onSuccess,onError,async)}shouldCollectFootprints(){if(this.getCurrentColor()==null){this.logger.info("Current test identifier is null, should not collect footprints");return false}if(this.getCurrentColor()!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.logger.info("Not in anonymous footprints, should collect footprints");return true}if(this.hasActiveExecution){this.logger.info("Has active execution, should collect footprints");return true}this.logger.info("No active execution, should not collect footprints");return false}setActiveExecution(value){this.hasActiveExecution=value}stopWatchdog(){if(this.watchdog.getStatus().running){this.watchdog.stop()}}startWatchdog(){if(!this.watchdog.getStatus().running){this.watchdog.start()}}}exports.StateTracker=StateTracker;StateTracker.ANONYMOUS_FOOTPRINTS_COLOR="00000000-0000-0000-0000-000000000000/__init"})},{"./contracts":189,"./delegate":190}],222:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestStateHelper=void 0;class TestStateHelper{constructor(){this.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId)return"";return executionId+"/"+testName};this.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";const executionId=testId.split("/")[0];let testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId)testName="";return{executionId:executionId,testName:testName}}}}exports.TestStateHelper=TestStateHelper})},{}],223:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Utils=void 0;const path=require("path");class Utils{static adjustPathSlashes(path){path=(path||"").replace(/\\/g,"/");return path}static getRelativeModulePath(path,workspacepath){workspacepath=Utils.adjustPathSlashes(workspacepath);path=Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path}static resolveOriginalFullFileName(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}const generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename}static parseBooleanValue(value){if(value&&typeof value=="boolean"){return value}if(value&&typeof value=="string"){return value.toLowerCase()=="true"}return false}}exports.Utils=Utils})},{path:161}],224:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=void 0;const delegate_1=require("./delegate");class Watchdog{constructor(timeout,timersWrapper,options,logger){this.timeout=timeout;this.timersWrapper=timersWrapper;this.options=options;this.logger=logger;this.handle=null;this.alarm=new delegate_1.Delegate;this.context=this;this.stopped=false;this.options=options||{}}abortTimer(){if(this.handle){this.timersWrapper.clearTimeout(this.handle);this.handle=null}}fireAlarm(){this.handle=null;try{this.alarm.fire()}catch(e){this.logger.error("Alarm caught an exception: ",e)}if(this.options.autoReset){this.context.reset()}}addOnAlarmListener(listener){this.alarm.addListener(listener)}reset(){this.abortTimer();if(!this.stopped){this.handle=this.timersWrapper.setTimeout(()=>{this.fireAlarm()},this.timeout)}}stop(){this.stopped=true;this.abortTimer()}start(){this.stopped=false;this.reset()}getStatus(){return{running:!this.stopped}}on(event,listener){this.addOnAlarmListener(listener)}startIfNotRunning(){if(this.stopped||!this.handle){this.start()}}setInterval(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.timeout=newInterval}}exports.Watchdog=Watchdog})},{"./delegate":190}],225:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WindowTimersWrapper=void 0;class WindowTimersWrapper{constructor(window){this.window=window;if(!this.window)throw new Error("'window' cannot be null or undefined")}clearInterval(handle){this.window.clearInterval(handle)}clearTimeout(handle){this.window.clearTimeout(handle)}setInterval(handler,timeout,...args){return this.window.setInterval(handler,timeout,args)}setTimeout(handler,timeout,...args){return this.window.setTimeout(handler,timeout,args)}}exports.WindowTimersWrapper=WindowTimersWrapper})},{}],226:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.COMMAND_ARGS=exports.COMMANDS=void 0;var COMMANDS;(function(COMMANDS){COMMANDS["CONFIG"]="config";COMMANDS["PR_CONFIG"]="prConfig";COMMANDS["BUILD"]="build";COMMANDS["SCAN"]="scan";COMMANDS["MOCHA"]="mocha";COMMANDS["JASMINE"]="jasmine";COMMANDS["MOCHA_PHANTOM_JS"]="mochaPhantomjs";COMMANDS["RUN"]="run";COMMANDS["START"]="start";COMMANDS["END"]="end";COMMANDS["UPLOAD_REPORTS"]="uploadReports";COMMANDS["EXTERNAL_REPORT"]="externalReport";COMMANDS["NYC_REPORT"]="nycReport";COMMANDS["INSTALL_BABEL"]="installBabel";COMMANDS["COMPONENT_UPDATE"]="componentUpdate";COMMANDS["COMPONENT_DELETE"]="componentDelete";COMMANDS["BUILD_END"]="buildend";COMMANDS["SCANNED"]="scanned";COMMANDS["DRY_RUN"]="dryRun"})(COMMANDS=exports.COMMANDS||(exports.COMMANDS={}));var COMMAND_ARGS;(function(COMMAND_ARGS){COMMAND_ARGS["USE_OTEL"]="useOtel";COMMAND_ARGS["ENABLE_OPEN_TELEMETRY"]="enableOpenTelemetry";COMMAND_ARGS["INSTRUMENT_FOR_BROWSERS"]="instrumentForBrowsers"})(COMMAND_ARGS=exports.COMMAND_ARGS||(exports.COMMAND_ARGS={}))})},{}],227:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentTechnologies=exports.AgentEventCode=exports.AgentTypes=void 0;var AgentTypes;(function(AgentTypes){AgentTypes["BUILD_SCANNER"]="BuildScanner";AgentTypes["TEST_LISTENER"]="TestListener";AgentTypes["BROWSER_AGENT"]="BrowserAgent";AgentTypes["SLNODEJS"]="slnodejs"})(AgentTypes=exports.AgentTypes||(exports.AgentTypes={}));var AgentEventCode;(function(AgentEventCode){AgentEventCode[AgentEventCode["GENERIC_AGENT_EVENT"]=1e3]="GENERIC_AGENT_EVENT";AgentEventCode[AgentEventCode["AGENT_STARTED"]=1001]="AGENT_STARTED";AgentEventCode[AgentEventCode["AGENT_SHUTDOWN"]=1002]="AGENT_SHUTDOWN";AgentEventCode[AgentEventCode["AGENT_PING"]=1003]="AGENT_PING";AgentEventCode[AgentEventCode["AGENT_CONFIG_CHANGED"]=1004]="AGENT_CONFIG_CHANGED";AgentEventCode[AgentEventCode["FIRST_COVERAGE_INSTRUMENTATION_PERFORMED"]=1005]="FIRST_COVERAGE_INSTRUMENTATION_PERFORMED";AgentEventCode[AgentEventCode["FIRST_TIME_HAS_EXECUTION"]=1006]="FIRST_TIME_HAS_EXECUTION";AgentEventCode[AgentEventCode["FIRST_TIME_NO_EXECUTION"]=1007]="FIRST_TIME_NO_EXECUTION";AgentEventCode[AgentEventCode["AGENT_MUTED"]=1008]="AGENT_MUTED";AgentEventCode[AgentEventCode["AGENT_UNMUTED"]=1009]="AGENT_UNMUTED";AgentEventCode[AgentEventCode["FIRST_TIME_COLLECTED_FP"]=1010]="FIRST_TIME_COLLECTED_FP";AgentEventCode[AgentEventCode["CONTEXT_PROPAGATION_TELEMETRY"]=1019]="CONTEXT_PROPAGATION_TELEMETRY";AgentEventCode[AgentEventCode["GENERIC_MESSAGE"]=2e3]="GENERIC_MESSAGE";AgentEventCode[AgentEventCode["GENERIC_MESSAGE_SUPERUSER"]=2999]="GENERIC_MESSAGE_SUPERUSER";AgentEventCode[AgentEventCode["WARN"]=3e3]="WARN";AgentEventCode[AgentEventCode["AGENT_DID_NOT_SHUTDOWN"]=3001]="AGENT_DID_NOT_SHUTDOWN";AgentEventCode[AgentEventCode["GENERIC_WARNING_SUPERUSER"]=3999]="GENERIC_WARNING_SUPERUSER";AgentEventCode[AgentEventCode["GIT_SUBMODULES_DETECTED"]=3501]="GIT_SUBMODULES_DETECTED";AgentEventCode[AgentEventCode["GENERIC_ERROR"]=4e3]="GENERIC_ERROR";AgentEventCode[AgentEventCode["DUPLICATE_MODULE"]=4001]="DUPLICATE_MODULE";AgentEventCode[AgentEventCode["DATA_PROCESSOR_NO_EXECUTIONS"]=4002]="DATA_PROCESSOR_NO_EXECUTIONS";AgentEventCode[AgentEventCode["DATA_PROCESSOR_INVALID_FORMAT"]=4003]="DATA_PROCESSOR_INVALID_FORMAT";AgentEventCode[AgentEventCode["DATA_PROCESSOR_EMPTY_DATA"]=4004]="DATA_PROCESSOR_EMPTY_DATA";AgentEventCode[AgentEventCode["BUILD_MAP_SUBMISSION_ERROR"]=4005]="BUILD_MAP_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_SUBMISSION_ERROR"]=4006]="FOOTPRINTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["TEST_EVENTS_SUBMISSION_ERROR"]=4007]="TEST_EVENTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR"]=4008]="EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["UNSUPPORTED_OS"]=4009]="UNSUPPORTED_OS";AgentEventCode[AgentEventCode["UNSUPPORTED_RUNTIME"]=4010]="UNSUPPORTED_RUNTIME";AgentEventCode[AgentEventCode["THIRD_PARTY_PACKAGE_DETECTED"]=4011]="THIRD_PARTY_PACKAGE_DETECTED";AgentEventCode[AgentEventCode["THIRD_PARTY_FILE_DETECTED"]=4012]="THIRD_PARTY_FILE_DETECTED";AgentEventCode[AgentEventCode["OTEL_ERROR"]=4013]="OTEL_ERROR";AgentEventCode[AgentEventCode["STATIC_INSTRUMENTATION_ERROR"]=4021]="STATIC_INSTRUMENTATION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_LOSS"]=4999]="FOOTPRINTS_LOSS";AgentEventCode[AgentEventCode["LEAST_VERBOSE_LOG"]=5001]="LEAST_VERBOSE_LOG";AgentEventCode[AgentEventCode["MOST_VERBOSE_LOG"]=5999]="MOST_VERBOSE_LOG"})(AgentEventCode=exports.AgentEventCode||(exports.AgentEventCode={}));var AgentTechnologies;(function(AgentTechnologies){AgentTechnologies["NODEJS"]="nodejs";AgentTechnologies["BROWSER"]="browser"})(AgentTechnologies=exports.AgentTechnologies||(exports.AgentTechnologies={}))})},{}],228:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-contracts","./agent-instance-info-builder","./machine-info-builder","./nodejs-env-info-builder","./agent-start-info-builder","./ci-info-builder","../utils/validation-utils","../watchdog","../system-date","./browser-info-builder","../utils/data-cleansing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsController=void 0;const agent_events_contracts_1=require("./agent-events-contracts");const agent_instance_info_builder_1=require("./agent-instance-info-builder");const machine_info_builder_1=require("./machine-info-builder");const nodejs_env_info_builder_1=require("./nodejs-env-info-builder");const agent_start_info_builder_1=require("./agent-start-info-builder");const ci_info_builder_1=require("./ci-info-builder");const validation_utils_1=require("../utils/validation-utils");const watchdog_1=require("../watchdog");const system_date_1=require("../system-date");const browser_info_builder_1=require("./browser-info-builder");const data_cleansing_utils_1=require("../utils/data-cleansing-utils");class AgentEventsController{constructor(agentConfig,agentInstanceData,logger,backendProxy,tool,tags,colorContextManager){this.colorContextManager=colorContextManager;this.active=false;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentConfig,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");this._agentConfig=agentConfig;this._logger=logger;this._agentInstanceData=agentInstanceData;this.shutDownRetries=0;this._backendProxy=backendProxy;this.addTags(tags);this.addTool(tool);this.initWatchdog();this.submittedEventsMap=new Map}submitAgentStartedEvent(packageJsonFile){return __awaiter(this,void 0,void 0,function*(){this.active=true;this.startRequestStatus=StartRequestStatus.PENDING;const event=this.buildAgentStartEvent(packageJsonFile||{});const result=yield this.submitAgentEventRequest(event);this.startRequestStatus=result?StartRequestStatus.SUCCEED:StartRequestStatus.FAILED;if(this.startRequestStatus!==StartRequestStatus.SUCCEED){this._logger.info("Agent start event failed to submit - ping events will not be sent")}else{this._pingWatchdog.start()}})}addColorToEvent(event){var _a;const colorName=(_a=this.colorContextManager)===null||_a===void 0?void 0:_a.getTestName();return Array.isArray(event)?event.forEach(eventObject=>eventObject.colorName=colorName):event.colorName=colorName}submitAgentEventRequest(event){return __awaiter(this,void 0,void 0,function*(){if(!this.active){this._logger.debug("Agent not active - not submitting event");return false}const request={agentId:this._agentInstanceData.agentId,events:Array.isArray(event)?event:[event],appName:this._agentConfig.appName.value,buildSessionId:this._agentConfig.buildSessionId.value};try{yield this._backendProxy.submitAgentEvent(request);this._logger.info(`Submitted '${request.events.length}' events successfully`);return true}catch(e){this._logger.warn(`Failed to submit '${request.events.length}' events. Error ${e}`);return false}})}buildAgentStartEvent(packageJsonFile){const agentInstanceInfoBuilder=new agent_instance_info_builder_1.AgentInstanceInfoBuilder(this);const machineInfoBuilder=new machine_info_builder_1.MachineInfoBuilder;const dependencies=Object.assign(Object.assign({},packageJsonFile.dependencies),packageJsonFile.devDependencies);const nodejsEnvInfoBuilder=this.agentInstanceData.technology===agent_events_contracts_1.AgentTechnologies.BROWSER?new browser_info_builder_1.BrowserInfoBuilder:new nodejs_env_info_builder_1.NodejsEnvInfoBuilder(this.agentInstanceData,dependencies);const ciInfoBuilder=new ci_info_builder_1.CiInfoBuilder;const agentStartInfoBuilder=new agent_start_info_builder_1.AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,nodejsEnvInfoBuilder,ciInfoBuilder,this._agentConfig);const agentStartInfo=agentStartInfoBuilder.build();return this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_STARTED,agentStartInfo)}buildAgentShutdownEvent(){return this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_SHUTDOWN)}submitAgentShutdownEvent(){return __awaiter(this,void 0,void 0,function*(){this.shutDownRetries++;if(this.startRequestStatus==StartRequestStatus.FAILED){this._logger.debug("Agent start not submitted - not sending shut down events");return}if(this.shutDownRetries>AgentEventsController.MAX_SHUTDOWN_RETRIES){this._logger.debug("Stop trying to send shutdown event after 60 seconds ");return}this._pingWatchdog.stop();const event=this.buildAgentShutdownEvent();if(this.startRequestStatus==StartRequestStatus.PENDING){setTimeout(()=>this.submitAgentShutdownEvent.call(this),1e3)}else{const result=yield this.submitAgentEventRequest(event);this.active=false;return result}})}submitPingEvent(){return this.submitEvent(agent_events_contracts_1.AgentEventCode.AGENT_PING,{agentInfo:{labId:this.agentConfig.labId.value}})}submitEvent(code,data){this.submittedEventsMap.set(code,true);this._logger.debug(`About to send event with code '${code}', current time: ${(0,system_date_1.getSystemDateValueOf)()}`);const event=this.buildEvent(code,data);this.submitAgentEventRequest(event).then(()=>this._logger.debug(`Event with code '${code}' submitted successfully`))}submitEventOnce(code){if(!this.submittedEventsMap.get(code)){this.submitEvent(code)}}submitGenericMessage(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.GENERIC_MESSAGE)}submitWarning(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.WARN)}submitError(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.GENERIC_ERROR)}submitErrorsBatch(messages){if(!messages||!messages.length){return}const events=messages.map(msg=>this.buildEvent(agent_events_contracts_1.AgentEventCode.GENERIC_ERROR,msg));this.submitAgentEventRequest(events).then(()=>this.logger.debug(`'${events.length}' events were submitted successfully`))}sendMessage(message,code){this.logger.debug(`About to send message '${message}' with code '${code}', current time: ${(0,system_date_1.getSystemDateValueOf)()}`);const messageEvent=this.buildEvent(code,message);this.submitAgentEventRequest(messageEvent).then(()=>this.logger.debug("Message submitted successfully"))}submitConfigChanged(){const messageEvent=this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_CONFIG_CHANGED,this._agentConfig.toJsonObject());this.submitAgentEventRequest(messageEvent).then(()=>this.logger.debug("Config changed event submitted successfully"))}get watchdog(){return this._pingWatchdog}get agentConfig(){return this._agentConfig}get logger(){return this._logger}get tools(){return this._tools}resolveTags(){return this._tags||[]}addTags(tags){if(!tags)return;this._tags=[...this._tags||[],...tags||[]]}addTool(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)}initWatchdog(){const watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};const timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))}getTimers(){if(this._agentInstanceData.technology===agent_events_contracts_1.AgentTechnologies.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}}buildEvent(type,data){var _a;const cleanData=this._agentConfig.removeSensitiveData.value?data_cleansing_utils_1.DataCleansingUtils.removeSensitiveData(data):data;return{type:type,utcTimestamp_ms:(0,system_date_1.getSystemDateValueOf)(),data:cleanData,colorName:(_a=this.colorContextManager)===null||_a===void 0?void 0:_a.getTestName()}}get agentInstanceData(){return this._agentInstanceData}}exports.AgentEventsController=AgentEventsController;AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../system-date":275,"../utils/data-cleansing-utils":276,"../utils/validation-utils":280,"../watchdog":281,"./agent-events-contracts":227,"./agent-instance-info-builder":230,"./agent-start-info-builder":231,"./browser-info-builder":232,"./ci-info-builder":233,"./machine-info-builder":236,"./nodejs-env-info-builder":238}],229:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date","./cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsGuard=void 0;const system_date_1=require("../system-date");const cockpit_notifier_1=require("./cockpit-notifier");class AgentEventsGuard{static notifyIfNeeded(eventCode,data){const currentTime=(0,system_date_1.getSystemDateValueOf)();const lastCallTime=AgentEventsGuard.EVENT_CODE_TO_LAST_CALL.get(eventCode);if(!lastCallTime||currentTime-lastCallTime>=AgentEventsGuard.DEFAULT_FIVE_MIN_BUFFER){cockpit_notifier_1.CockpitNotifier.sendEvent(eventCode,data);AgentEventsGuard.EVENT_CODE_TO_LAST_CALL.set(eventCode,currentTime)}}static init(){AgentEventsGuard.EVENT_CODE_TO_LAST_CALL=new Map}}exports.AgentEventsGuard=AgentEventsGuard;AgentEventsGuard.DEFAULT_FIVE_MIN_BUFFER=5*60*1e3;AgentEventsGuard.EVENT_CODE_TO_LAST_CALL=new Map})},{"../system-date":275,"./cockpit-notifier":234}],230:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./sensitive-data-filter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceInfoBuilder=void 0;const sensitive_data_filter_1=require("./sensitive-data-filter");const SEALIGHTS_ENV_VAR_PREFIX="SL_";const CI_ENV_VARS=new Set(["build_number","build_id","build_url","node_name","job_name","build_tag","jenkins_url","workspace","git_commit","git_url","git_branch","circle_branch","circle_build_num","circle_build_url","circle_job","circle_node_index","circle_node_total","circle_pr_number","circle_pr_reponame","circle_previous_build_num","circle_project_reponame","circle_pull_request","circle_repository_url","circle_sha1","circle_tag","circle_workflow_id","circle_workflow_job_id","circle_workflow_workspace_id","circle_working_directory","teamcity_version","teamcity_project_name","teamcity_buildconf_name","build_is_personal","ci_builds_dir","ci_commit_author","ci_commit_before_sha","ci_commit_branch","ci_commit_description","ci_commit_message","ci_commit_ref_name","ci_commit_ref_slug","ci_commit_sha","ci_commit_short_sha","ci_commit_tag","ci_commit_timestamp","ci_commit_title","ci_concurrent_id","ci_concurrent_project_id","ci_config_path","ci_default_branch","ci_dependency_proxy_server","ci_disposable_environment","ci_environment_name","ci_environment_slug","ci_environment_url","ci_environment_action","ci_environment_tier","ci_job_id","ci_job_image","ci_job_name","ci_job_stage","ci_job_url","ci_job_started_at","ci_kubernetes_active","ci_node_index","ci_node_total","ci_pipeline_url","ci_project_dir","ci_project_name","ci_project_namespace","ci_project_path_slug","ci_project_path","ci_project_repository_languages","ci_project_root_namespace","ci_project_title","ci_project_description","ci_project_url","ci_registry_image","ci_repository_url","ci_server_host","ci_server_name","ci_server_url","ci_server_version_major","ci_server_version_minor","ci_server_version_patch","ci_server_version","gitlab_ci","ci_merge_request_approved","ci_merge_request_assignees","ci_merge_request_id","ci_merge_request_iid","ci_merge_request_labels","ci_merge_request_milestone","ci_merge_request_project_id","ci_merge_request_project_path","ci_merge_request_project_url","ci_merge_request_ref_path","ci_merge_request_source_branch_name","ci_merge_request_source_branch_sha","ci_merge_request_source_project_id","ci_merge_request_source_project_path","ci_merge_request_source_project_url","ci_merge_request_target_branch_name","ci_merge_request_target_branch_sha","ci_merge_request_title","ci_merge_request_event_type","ci_merge_request_diff_id","ci_merge_request_diff_base_sha","ci_external_pull_request_iid","ci_external_pull_request_source_repository","ci_external_pull_request_target_repository","ci_external_pull_request_source_branch_name","ci_external_pull_request_source_branch_sha","ci_external_pull_request_target_branch_name","ci_external_pull_request_target_branch_sha","github_action","github_action_path","github_action_repository","github_base_ref","github_env","github_head_ref","github_job","github_path","github_ref","github_ref_name","github_ref_type","github_repository","github_repository_owner","github_sha","github_step_summary","github_workflow","github_workspace","runner_arch","runner_name","runner_os","runner_temp","runner_tool_cache"]);class AgentInstanceInfoBuilder{constructor(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.tags=agentEventsController.resolveTags();this.tools=agentEventsController.tools;this.logger=agentEventsController.logger;this.technology=agentEventsController.agentInstanceData.technology;this.info={agentId:agentEventsController.agentInstanceData.agentId,agentType:agentEventsController.agentInstanceData.agentType,agentVersion:agentEventsController.agentInstanceData.agentVersion,technology:agentEventsController.agentInstanceData.technology}}fillData(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()}build(){this.fillData();return this.info}fillFromAgentConfig(){this.info.buildSessionId=this.agentConfig.buildSessionId.value;this.info.labId=this.agentConfig.labId.value||this.agentConfig.buildSessionId.value;this.info.testStage=this.agentConfig.testStage.value;this.info.agentConfig=this.agentConfig.toJsonObject()}fillFromProcessObject(){this.info.processId=process.pid;this.info.processArch=process.arch;this.info.argv=process.argv;this.info.cwd=process.cwd();this.info.envVars=this.extractSealightsEnvVars()}extractSealightsEnvVars(){const slEnvVars={};Object.keys(process.env).forEach(key=>{if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0||key==="NODE_OPTIONS"||key==="PATH"||CI_ENV_VARS.has(key.toLowerCase())){slEnvVars[key]=(0,sensitive_data_filter_1.isSensitive)(key,process.env[key],this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars}}exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder;AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********"})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":239,_process:162}],231:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/data-cleansing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentStartInfoBuilder=void 0;const data_cleansing_utils_1=require("../utils/data-cleansing-utils");class AgentStartInfoBuilder{constructor(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder,agentConfig){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder;this.agentConfig=agentConfig;this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}fillData(){}build(){const response={agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()};if(this.agentConfig.removeSensitiveData.value)return data_cleansing_utils_1.DataCleansingUtils.removeSensitiveData(response);return response}}exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{"../utils/data-cleansing-utils":276}],232:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserInfoBuilder=void 0;const system_date_1=require("../system-date");class BrowserInfoBuilder{constructor(){this.info={}}fillData(){const currentDate=(0,system_date_1.getSystemDate)();this.info.userAgent=window.navigator.userAgent;this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.location=window.location.toString()}build(){this.fillData();return this.info}}exports.BrowserInfoBuilder=BrowserInfoBuilder})},{"../system-date":275}],233:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CiInfoBuilder=void 0;const JENKINS_JOB_NAME_ENV="JOB_NAME";const JENKINS_JOB_ID_ENV="BUILD_ID";const JENKINS_JOB_URL_ENV="BUILD_URL";class CiInfoBuilder{constructor(){this.info={}}fillData(){if(this.isJenkins()){this.info.jobId=process.env[JENKINS_JOB_ID_ENV];this.info.jobName=process.env[JENKINS_JOB_NAME_ENV];this.info.jobUrl=process.env[JENKINS_JOB_URL_ENV]}}isJenkins(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]}build(){this.fillData();return this.info}}exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:162}],234:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller","./dry-run-agent-events-controller","./no-op-agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;const agent_events_controller_1=require("./agent-events-controller");const dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");const no_op_agent_events_controller_1=require("./no-op-agent-events-controller");class CockpitNotifier{static notifyStart(agentConfig,agentInstanceData,logger,backendProxy,packageJsonFile,tool,tags,colorContextManager){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags,colorContextManager);yield CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)})}static notifyStartNoOp(agentConfig,agentInstanceData,logger,backendProxy,packageJsonFile,tool,tags){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.controller=new no_op_agent_events_controller_1.NoOpAgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags)})}static notifyShutdown(){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.verifyControllerInitialized();yield CockpitNotifier.controller.submitAgentShutdownEvent()})}static sendGenericMessage(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)}static sendWarning(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)}static sendError(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)}static sendErrorsBatch(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)}static sendEvent(code,data){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code,data)}static sendEventOnce(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)}static verifyControllerInitialized(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}}static reset(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false}static setDryRunMode(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)}}exports.CockpitNotifier=CockpitNotifier;CockpitNotifier.controllerNullLogged=false})},{"./agent-events-controller":228,"./dry-run-agent-events-controller":235,"./no-op-agent-events-controller":237}],235:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-contracts","./agent-events-controller","../config-process/config","../agent-instance-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DryRunAgentEventsController=void 0;const agent_events_contracts_1=require("./agent-events-contracts");const agent_events_controller_1=require("./agent-events-controller");const config_1=require("../config-process/config");const agent_instance_data_1=require("../agent-instance-data");class DryRunAgentEventsController extends agent_events_controller_1.AgentEventsController{constructor(logger,proxy){super(new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_contracts_1.AgentTypes.SLNODEJS,agent_events_contracts_1.AgentTechnologies.NODEJS),logger,proxy,null)}submitAgentStartedEvent(packageJsonFile){return Promise.resolve(undefined)}}exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":240,"../config-process/config":243,"./agent-events-contracts":227,"./agent-events-controller":228}],236:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","os","../system-date","../footprints-process-v6/buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;const os=require("os");const system_date_1=require("../system-date");const buffer_size_helper_1=require("../footprints-process-v6/buffer-size-helper");class MachineInfoBuilder{constructor(){this.info={}}fillData(){const currentDate=(0,system_date_1.getSystemDate)();this.info.machineName=os.hostname();const cpus=os.cpus();this.info.cpu=cpus.map(cpu=>`${cpu.model} (${cpu.speed} MHz`).join(", ");this.info.totalMemory=`${os.totalmem()/buffer_size_helper_1.BufferSizeHelper.BYTES_IN_GB} Gb`;this.info.arch=os.arch();this.info.os=os.platform();this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.runtime=process.version;this.info.ipAddress=this.extractIpAddresses()}build(){this.fillData();return this.info}extractIpAddresses(){let ipAddresses=[];const interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(key=>{const addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(addressObject=>addressObject.address))});return ipAddresses}}exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../footprints-process-v6/buffer-size-helper":257,"../system-date":275,_process:162,os:160}],237:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoOpAgentEventsController=void 0;const agent_events_controller_1=require("./agent-events-controller");class NoOpAgentEventsController extends agent_events_controller_1.AgentEventsController{submitAgentStartedEvent(packageJsonFile){return __awaiter(this,void 0,void 0,function*(){})}submitAgentEventRequest(event){return __awaiter(this,void 0,void 0,function*(){return true})}sendMessage(message,code){}submitAgentShutdownEvent(){return __awaiter(this,void 0,void 0,function*(){return null})}submitPingEvent(){}submitEvent(code,data){}submitEventOnce(code){}submitGenericMessage(message){}submitWarning(message){}submitError(message){}submitErrorsBatch(messages){}}exports.NoOpAgentEventsController=NoOpAgentEventsController})},{"./agent-events-controller":228}],238:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NodejsEnvInfoBuilder=void 0;class NodejsEnvInfoBuilder{constructor(agentInstanceData,dependencies){this.agentInstanceData=agentInstanceData;this.info={};this.dependencies=dependencies||{}}fillData(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node;this.info.execArgv=process.execArgv;this.info.allocatedMemoryInMB=this.agentInstanceData.AgentAllocatedMemoryInMb}build(){this.fillData();return this.info}}exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:162}],239:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSensitive=void 0;const secretKeysRegexes={"Slack Token":"(xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})","RSA private key":"-----BEGIN RSA PRIVATE KEY-----","SSH (DSA) private key":"-----BEGIN DSA PRIVATE KEY-----","SSH (EC) private key":"-----BEGIN EC PRIVATE KEY-----","PGP private key block":"-----BEGIN PGP PRIVATE KEY BLOCK-----","Amazon AWS Access Key ID":"AKIA[0-9A-Z]{16}","Amazon MWS Auth Token":"amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}","AWS API Key":"AKIA[0-9A-Z]{16}","Facebook Access Token":"EAACEdEose0cBA[0-9A-Za-z]+","Facebook OAuth":"[f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|\"][0-9a-f]{32}['|\"]",GitHub:"[g|G][i|I][t|T][h|H][u|U][b|B].*['|\"][0-9a-zA-Z]{35,40}['|\"]","Generic API Key":"[a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Generic Secret":"[s|S][e|E][c|C][r|R][e|E][t|T].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Google API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google Drive API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Drive OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google (GCP) Service-account":'"type": "service_account"',"Google Gmail API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Gmail OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google OAuth Access Token":"ya29\\.[0-9A-Za-z\\-_]+","Google YouTube API Key":"AIza[0-9A-Za-z\\-_]{35}","Google YouTube OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Heroku API Key":"[h|H][e|E][r|R][o|O][k|K][u|U].*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}","MailChimp API Key":"[0-9a-f]{32}-us[0-9]{1,2}","Mailgun API Key":"key-[0-9a-zA-Z]{32}","Password in URL":"[a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}[\"'\\s]","PayPal Braintree Access Token":"access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}","Picatic API Key":"sk_live_[0-9a-z]{32}","Slack Webhook":"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}","Stripe API Key":"sk_live_[0-9a-zA-Z]{24}","Stripe Restricted API Key":"rk_live_[0-9a-zA-Z]{24}","Square Access Token":"sq0atp-[0-9A-Za-z\\-_]{22}","Square OAuth Secret":"sq0csp-[0-9A-Za-z\\-_]{43}","Twilio API Key":"SK[0-9a-fA-F]{32}","Twitter Access Token":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40}","Twitter OAuth":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|\"][0-9a-zA-Z]{35,44}['|\"]"};function isSensitive(envVar,value,logger){for(const[key,regex]of Object.entries(secretKeysRegexes)){if(new RegExp(regex).test(value)){logger.debug(`Value for key ${envVar} filtered out since it suspected to contains data fpr ${key}`);return true}}return false}exports.isSensitive=isSensitive})},{}],240:[function(require,module,exports){(function(__dirname){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","uuid","./agent-events/agent-events-contracts","./utils/files-utils","fs","./agent-events/agent-instance-info-builder"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceData=void 0;const uuid=require("uuid");const agent_events_contracts_1=require("./agent-events/agent-events-contracts");const files_utils_1=require("./utils/files-utils");const fs_1=require("fs");const agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");class AgentInstanceData{constructor(agentType,technology,buildSessionId){this.agentType=agentType;this.technology=technology;this.buildSessionId=buildSessionId;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}resolveAgentVersion(){if(this.technology===agent_events_contracts_1.AgentTechnologies.BROWSER){return this.resolveAgentVersionForBrowserAgent()}const packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{const packageJson=(0,fs_1.readFileSync)(packageJsonFilePath).toString();const parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn(`Failed to resolve agent version, Error: '${e}`);return null}}return null}resolveAgentVersionForBrowserAgent(){const windowVar=typeof window!=="undefined"?window:null;return windowVar&&windowVar[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT]&&windowVar[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT].agentVersion||agent_instance_info_builder_1.AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION}set AgentAllocatedMemoryInMb(memory){this.agentAllocatedMemoryInMb=memory}get AgentAllocatedMemoryInMb(){return this.agentAllocatedMemoryInMb}}exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-contracts":227,"./agent-events/agent-instance-info-builder":230,"./utils/files-utils":278,fs:157,uuid:285}],241:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system","./config","../constants/sl-env-vars","fs","jwt-decode","../../cli-parse/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;const config_system_1=require("./config-system");const config_1=require("./config");const sl_env_vars_1=require("../constants/sl-env-vars");const fs=require("fs");const jwtDecode=require("jwt-decode");const contracts_1=require("../../cli-parse/contracts");class ConfigLoader{constructor(logger){this.logger=logger}loadAgentConfiguration(initialJsonConfig){const agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{const jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error(`Error parsing agent configuration ${e}`)}}agentCfg.loadConfiguration(new config_system_1.EnvVariableConfigurationProvider("SL_"));if(initialJsonConfig){agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(initialJsonConfig))}if(!agentCfg.token.hasValue&&agentCfg.tokenFile.hasValue){try{agentCfg.token.value=fs.readFileSync(agentCfg.tokenFile.value).toString()}catch(err){}}if(agentCfg.token.hasValue){this.loadConfigFromToken(agentCfg,agentCfg.token.value)}this.resolveUsingOtel(agentCfg,initialJsonConfig);this.printConfiguration(agentCfg);return agentCfg}printConfiguration(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())}resolveUsingOtel(agentCfg,initialJsonConfig){agentCfg.useOtel.value=sl_env_vars_1.SlEnvVars.shouldUseOtel()||(initialJsonConfig===null||initialJsonConfig===void 0?void 0:initialJsonConfig[contracts_1.COMMAND_ARGS.ENABLE_OPEN_TELEMETRY])}loadConfigFromToken(agentCfg,token){if(!token)return null;try{const tokenData=jwtDecode(token);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}let customerId=tokenData["subject"];const subjectParts=tokenData["subject"].split("@");if(subjectParts.length>=1){customerId=subjectParts[0]}if(!agentCfg.server.hasValue){agentCfg.server.value=tokenData["x-sl-server"]}agentCfg.customerId.value=customerId}catch(err){}}}exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"../../cli-parse/contracts":226,"../constants/sl-env-vars":247,"./config":243,"./config-system":242,_process:162,fs:157,"jwt-decode":284}],242:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseConfiguration=exports.BooleanConfigKey=exports.NumberConfigKey=exports.StringConfigKey=exports.AgentConfigKey=exports.JsonConfigFileConfigurationProvider=exports.ConfigProviderAggregator=exports.EnvVariableConfigurationProvider=exports.JsonObjectConfigurationProvider=void 0;const fs=require("fs");class JsonObjectConfigurationProvider{constructor(configObject){this.configObject=configObject;this.configObject=configObject||{}}getAllKeyValues(callback){return callback(null,this.configObject)}getName(){return"JSON Object"}}exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;class EnvVariableConfigurationProvider{constructor(prefix){this.prefix=prefix}getAllKeyValues(callback){if(this.prefix){const ret={};ret["httpMaxAttempts"]=process.env["SL_HttpMaxAttempts"];ret["httpAttemptInterval"]=process.env["SL_HttpAttemptInterval"];for(const key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substring(this.prefix.length)]=process.env[key]}}return callback(null,ret)}else{return callback(null,process.env)}}getName(){return"Environment Variables"}}exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;class ConfigProviderAggregator{constructor(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}getAllKeyValues(callback){const flattenedConfiguration={};const remainingProviders=[].concat(this.providers);const attemptNext=()=>{if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}const nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues((err,keysAndValues)=>{if(err)return attemptNext();Object.keys(keysAndValues).forEach(k=>{if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()}getName(){return"Aggregated config from multiple providers: "+this.providers.map(t=>t.getName())}}exports.ConfigProviderAggregator=ConfigProviderAggregator;class JsonConfigFileConfigurationProvider{constructor(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}getAllKeyValues(callback){try{const cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}}getName(){return"Config filename: "+this.filename}}exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;class AgentConfigKey{}exports.AgentConfigKey=AgentConfigKey;class StringConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){this.value=s;this.hasValue=true}}exports.StringConfigKey=StringConfigKey;class NumberConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){const parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true}}exports.NumberConfigKey=NumberConfigKey;class BooleanConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){if(s==null)s="";if(typeof s==="boolean")s=String(s);s=s.toLowerCase();switch(s){case"true":this.value=true;this.hasValue=true;return;case"false":this.value=false;this.hasValue=true;return;case"undefined":this.value=false;this.hasValue=false;return;default:throw new Error("Invalid boolean value: "+s)}}}exports.BooleanConfigKey=BooleanConfigKey;class BaseConfiguration{loadConfigurationFromMultipleProviders(configProviders,callback){const provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)}loadConfiguration(configProvider,callback,dbg){try{configProvider.getAllKeyValues((err,keysAndValues)=>{if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};const knownKeys=Object.keys(this);let hadError=false;let keyWithError="";knownKeys.forEach(keyName=>{if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}const cfgKey=this[keyName];if(!cfgKey.isConfigKey)return;const rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){const msg="Required configuration is missing: "+keyName+", provider:"+configProvider.getName();hadError=true;if(callback){callback(new Error(msg))}}if(rawValue==undefined)return;try{cfgKey.loadFromRawData(rawValue)}catch(e){const msg="Invalid configuration for key="+keyName+", value="+rawValue+ +", provider="+configProvider.getName()+": "+e.toString();console.log("[Sealights Test Listener] - "+msg);hadError=true;keyWithError=keyName;if(callback){callback(new Error(msg))}}});if(!hadError){if(callback){callback(null)}return}})}catch(e){if(callback){callback(e)}return}}toJsonObject(){const ret={};const knownKeys=Object.keys(this);knownKeys.forEach(keyName=>{const cfgKey=this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret}getLowerCaseToKeyMap(){const lowerCaseMap={};Object.keys(this).forEach(key=>{lowerCaseMap[key.toLowerCase()]=key});return lowerCaseMap}}exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:162,fs:157}],243:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentConfigWithRuntimeArgs=exports.AgentConfig=void 0;const config_system_1=require("./config-system");class AgentConfig extends config_system_1.BaseConfiguration{constructor(){super(...arguments);this.token=new config_system_1.StringConfigKey(false);this.buildSessionId=new config_system_1.StringConfigKey(false);this.tokenFile=new config_system_1.StringConfigKey(false);this.server=new config_system_1.StringConfigKey(false);this.proxy=new config_system_1.StringConfigKey(false);this.interval=new config_system_1.NumberConfigKey(false,1e4);this.testStatusCheckInterval=new config_system_1.NumberConfigKey(false,3e4);this.enabled=new config_system_1.BooleanConfigKey(false,true);this.useOtel=new config_system_1.BooleanConfigKey(false,false);this.sendFootprints=new config_system_1.BooleanConfigKey(false,true);this.sendEvents=new config_system_1.BooleanConfigKey(false,true);this.sendLogs=new config_system_1.BooleanConfigKey(false,false);this.customerId=new config_system_1.StringConfigKey(false);this.appName=new config_system_1.StringConfigKey(false);this.branch=new config_system_1.StringConfigKey(false);this.build=new config_system_1.StringConfigKey(false);this.environmentName=new config_system_1.StringConfigKey(false);this.useBranchCoverage=new config_system_1.BooleanConfigKey(false,false);this.labId=new config_system_1.StringConfigKey(false);this.testGroupId=new config_system_1.StringConfigKey(false);this.testStage=new config_system_1.StringConfigKey(false);this.httpServerColoring=new config_system_1.BooleanConfigKey(false,false);this.httpClientColoring=new config_system_1.BooleanConfigKey(false,false);this.useInitialColor=new config_system_1.BooleanConfigKey(false,true);this.gzip=new config_system_1.BooleanConfigKey(false,true);this.useIstanbul=new config_system_1.BooleanConfigKey(false,false);this.enableChildProcessPatcher=new config_system_1.BooleanConfigKey(false,false);this.loggers=new config_system_1.StringConfigKey(false,"");this.httpListeningPort=new config_system_1.NumberConfigKey(false,0);this.useFootprintsV3=new config_system_1.BooleanConfigKey(false,true);this.extendedFootprints=new config_system_1.BooleanConfigKey(false,false);this.projectRoot=new config_system_1.StringConfigKey(false);this.enforceFullRun=new config_system_1.BooleanConfigKey(false,false);this.footprintsEnableV6=new config_system_1.BooleanConfigKey(false,true);this.footprintsBufferThresholdMb=new config_system_1.NumberConfigKey(false,10);this.executionQueryIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.footprintsQueueSize=new config_system_1.NumberConfigKey(false,2);this.footprintsSendIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.footprintsCollectIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.shouldCheckForActiveExecutionOnStartUp=new config_system_1.BooleanConfigKey(false,true);this.useTsNode=new config_system_1.BooleanConfigKey(false,false);this.testRecommendationSleepSeconds=new config_system_1.NumberConfigKey(false,1);this.removeSensitiveData=new config_system_1.BooleanConfigKey(false,false);this.httpTimeout=new config_system_1.NumberConfigKey(false,60*1e3*2);this.httpMaxAttempts=new config_system_1.NumberConfigKey(false,6);this.httpAttemptInterval=new config_system_1.NumberConfigKey(false,5*1e3);this.collectorUrl=new config_system_1.StringConfigKey(false)}}exports.AgentConfig=AgentConfig;class AgentConfigWithRuntimeArgs extends AgentConfig{constructor(){super(...arguments);this.cfg=new config_system_1.StringConfigKey(false)}}exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":242}],244:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./config-system","object-assign","jwt-decode"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigProcess=void 0;const events=require("events");const config_system_1=require("./config-system");const assign=require("object-assign");const jwtDecode=require("jwt-decode");class ConfigProcess extends events.EventEmitter{constructor(cfg,watchdog,backendProxy,logger){super();this.cfg=cfg;this.watchdog=watchdog;this.backendProxy=backendProxy;this.logger=logger;this.isRunning=false;if(!cfg)throw new Error("cfg is required");this.initialCfg=assign({},cfg.toJsonObject());if(!watchdog)throw new Error("watchdog is required");if(!backendProxy)throw new Error("backendProxy is required");if(!logger){throw new Error("logger is required")}watchdog.on("alarm",()=>{watchdog.stop();this.reloadConfigFromServer()});this.initCfg()}reloadConfigFromServer(callback){this.backendProxy.getRemoteConfig({appName:this.cfg.appName.value,branch:this.cfg.branch.value,build:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value},(err,updatedCfg)=>{if(!err&&updatedCfg){this.mergeConfigFromServerAndFireEvent(updatedCfg)}this.watchdog.start();if(callback){callback(err)}})}mergeConfigFromServerAndFireEvent(updatedCfgObject){let configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(const key in updatedCfgObject){if(this.cfg[key]&&this.cfg[key].isConfigKey&&this.cfg[key].value!=updatedCfgObject[key]){configChanged=true;break}}if(configChanged){this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(updatedCfgObject));this.emit("configuration_changed",this.cfg)}}getConfiguration(){return this.cfg}initCfg(){if(this.cfg.token.hasValue){try{const tokenData=jwtDecode(this.cfg.token.value);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!this.cfg.server.hasValue)this.cfg.server.value=tokenData["x-sl-server"];if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}let customerId=tokenData["subject"];const subjectParts=tokenData["subject"].split("@");customerId=subjectParts[0];this.cfg.customerId.value=this.cfg.customerId.value||customerId}catch(err){this.cfg.enabled.value=false;this.logger.error(`Error loading configuration. Agent will be disabled. ${err}`)}}}start(callback){if(this.isRunning)return;if(!this.cfg.enabled.value)return;if(!this.cfg.server.value||!this.cfg.token.hasValue)return;this.reloadConfigFromServer(callback);this.isRunning=true}stop(callback){this.watchdog.stop();this.isRunning=false;return callback()}}exports.ConfigProcess=ConfigProcess})},{"./config-system":242,events:158,"jwt-decode":284,"object-assign":159}],245:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./index"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopConfigProcess=void 0;const index_1=require("./index");class NoopConfigProcess extends index_1.ConfigProcess{start(callback){return callback===null||callback===void 0?void 0:callback(null)}stop(callback){return callback()}reloadConfigFromServer(callback){return callback===null||callback===void 0?void 0:callback(null)}}exports.NoopConfigProcess=NoopConfigProcess})},{"./index":244}],246:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:true});exports.Constants=void 0;class Constants{}exports.Constants=Constants;Constants.TRUE="true";Constants.FALSE="false";Constants.BUILD_SESSION_ID="buildSessionId";Constants.REQUEST="request";Constants.FOOTPRINTS_PACKET="footprintsPacket";Constants.TEST_STAGE="testStage";Constants.EXECUTION_BSID="executionBsid";Constants.CALLBACK="callback";Constants.PULL_REQUEST_PARAMS="pullRequestParams";Constants.SL_WINDOW_OBJECT="window.$Sealights";Constants.SKIP_BROWSER_AGENT=`${Constants.SL_WINDOW_OBJECT}.skipSlAgent`;Constants.Messages=(_a=class{},_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a)})},{}],247:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../footprints-process-v6/buffer-size-helper","../utils/env-var-parsing"],factory)}})(function(require,exports){"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;const buffer_size_helper_1=require("../footprints-process-v6/buffer-size-helper");const env_var_parsing_1=require("../utils/env-var-parsing");class SlEnvVars{static inProductionListenerMode(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]}static getProductionListenerModes(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")}static getFileStorage(){return process.env[SlEnvVars.FILE_STORAGE]}static getBasePath(){return process.env[SlEnvVars.BASE_PATH]}static isUseNewUniqueId(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)}static isUseIstanbul(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_ISTANBUL)}static enableFootprintsV6(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)}static getFootprintsCollectIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)}static getFootprintsSendMaxIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)}static getFootprintsQueueSize(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)}static getExecutionQueryIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)}static getFootprintsBufferThresholdMb(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)}static blockBrowserHttpTraffic(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)}static getDisableHookDependencyGuard(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)}static shouldUseOtel(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_OTEL_AGENT)}static useSlMapping(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_SL_MAPPING)}static turnOtelOn(){process.env[SlEnvVars.USE_OTEL_AGENT]="true"}static turnOtelOff(){process.env[SlEnvVars.USE_OTEL_AGENT]="false"}static useSpawnWrap(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.SL_USE_SPAWN_WRAP)}}exports.SlEnvVars=SlEnvVars;SlEnvVars.PRODUCTION_LISTENER="SL_production";SlEnvVars.FILE_STORAGE="SL_fileStorage";SlEnvVars.NEW_UNIQUE_ID="SL_newUniqueId";SlEnvVars.BASE_PATH="SL_basePath";SlEnvVars.USE_ISTANBUL="SL_useIstanbul";SlEnvVars.ENABLE_FOOTPRINTS_V6="SL_footprintsEnableV6";SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS="SL_footprintsCollectIntervalSecs";SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS="SL_footprintsSendIntervalSecs";SlEnvVars.FOOTPRINTS_QUEUE_SIZE="SL_footprintsQueueSize";SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC="SL_executionQueryIntervalSecs";SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB="SL_footprintsBufferThresholdMb";SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC="SL_blockBrowserHttpTraffic";SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD="SL_disableHookDependencyGuard";SlEnvVars.USE_OTEL_AGENT="SL_useOtelAgent";SlEnvVars.USE_SL_MAPPING="SL_useSlMapping";SlEnvVars.SL_USE_SPAWN_WRAP="SL_useSpawnWrap";SlEnvVars.CIA=(_a=class{static getFileExtensions(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]}static getSendCommitTitles(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.SEND_COMMIT_TITLES,true)}static getSourceRoot(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]}static getSlMappingPath(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]}static getSlMappingUrl(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]}static reduceInstrumentedFileSize(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)}static omitInstrumentedFunctionMap(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.OMIT_INSTRUMENTED_FUNCTION_MAP)}static minifyInstrumentedOutput(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)}static inProcessInstrumentation(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)}static useExperimentalSizeReduction(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.USE_EXPERIMENTAL_SIZE_REDUCTION)}static getMaxBuffer(){const bufferInBytes=env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*buffer_size_helper_1.BufferSizeHelper.BYTES_IN_MB}return bufferInBytes}},_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SL_SOURCE_ROOT="SL_sourceRoot",_a.SL_MAPPING_PATH="SL_mappingPath",_a.SL_MAPPING_URL="SL_mappingUrl",_a.REDUCE_INSTRUMENTED_FILE_SIZE="SL_reduceInstrumentedFileSize",_a.OMIT_INSTRUMENTED_FUNCTION_MAP="SL_omitInstrumentedFunctionMap",_a.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.USE_EXPERIMENTAL_SIZE_REDUCTION="SL_experimentalSizeReduction",_a.SEND_COMMIT_TITLES="SL_sendCommitTitles",_a.MAX_BUFFER="SL_maxBuffer",_a)})}).call(this)}).call(this,require("_process"))},{"../footprints-process-v6/buffer-size-helper":257,"../utils/env-var-parsing":277,_process:162}],248:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsMapping=void 0;var FootprintsMapping;(function(FootprintsMapping){FootprintsMapping["SERVER"]="server";FootprintsMapping["AGENT"]="agent"})(FootprintsMapping=exports.FootprintsMapping||(exports.FootprintsMapping={}))})},{}],249:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ElementType=void 0;var ElementType;(function(ElementType){ElementType["METHOD"]="method";ElementType["BRANCH"]="branch"})(ElementType=exports.ElementType||(exports.ElementType={}))})},{}],250:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FileElement=void 0;const validation_utils_1=require("../utils/validation-utils");class FileElement{constructor(type,startPosition,endPosition,uniqueIdKey,filename){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(type,"type");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(startPosition,"startPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(endPosition,"endPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(uniqueIdKey,"uniqueIdKey");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(filename,"filename");this._type=type;this._startPosition=startPosition;this._endPosition=endPosition;this._uniqueIdKey=uniqueIdKey;this._filename=filename}get type(){return this._type}set type(value){this._type=value}get startPosition(){return this._startPosition}set startPosition(value){this._startPosition=value}get endPosition(){return this._endPosition}set endPosition(value){this._endPosition=value}get uniqueIdKey(){return this._uniqueIdKey}set uniqueIdKey(value){this._uniqueIdKey=value}get uniqueIdKey_decl(){return this._uniqueIdKey_decl}set uniqueIdKey_decl(value){this._uniqueIdKey_decl=value}get filename(){return this._filename}set filename(value){this._filename=value}get uniqueId(){return this._uniqueId}set uniqueId(value){this._uniqueId=value}get parentPosition(){return this._parentPosition}set parentPosition(value){this._parentPosition=value}get index(){return this._index}set index(value){this._index=value}isStartsAfter(fileElement){if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())>parseInt(fileElement.startPosition.column.toString())){return true}return false}isStartsBefore(fileElement){if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())<parseInt(fileElement.startPosition.column.toString())){return true}return false}isEndsAfter(fileElement){if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())>parseInt(fileElement.endPosition.column.toString())){return true}return false}isEndsBefore(fileElement){if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())<parseInt(fileElement.endPosition.column.toString())){return true}return false}}exports.FileElement=FileElement})},{"../utils/validation-utils":280}],251:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulUniqueIdConverter=void 0;const contracts_1=require("./contracts");const unique_id_converter_1=require("./unique-id-converter");class IstanbulUniqueIdConverter extends unique_id_converter_1.UniqueIdConverter{constructor(filename,logger){super(filename,logger)}createElementsArray(file){file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};const methodsArr=Object.keys(file.fnMap).map(key=>this.formatMethod(file.fnMap[key]));const branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)}createElementPosition(position){return position}createBranchElements(branchesMap){const branchesMapArr=Object.keys(branchesMap).map(key=>branchesMap[key]);let branchesArr=[];for(const branch of branchesMapArr){branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr}extractBranchParts(branch){const formattedBranches=[];const locations=branch.locations;for(let i=0;i<locations.length;i++){const element={};element.position=locations[i].start;element.endPosition=locations[i].end;element.uniqueId=this.filename+"|"+this.formatLoc(element.position)+"|"+i;formattedBranches.push(element)}return formattedBranches}formatMethod(method){const element={};element.position=method.loc.start;element.endPosition=method.loc.end;element.uniqueId=this.filename+"@"+this.formatLoc(method.loc.start);if(method.decl&&method.decl.start){element.uniqueId_decl=this.filename+"@"+this.formatLoc(method.decl.start);if(method.decl.start.line<method.loc.start.line){element.position=method.decl.start}}return element}formatLoc(loc){return loc.line+","+loc.column}}exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":249,"./unique-id-converter":254}],252:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","../system-date","../utils/files-utils","./istanbul-unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveNewId=void 0;const path_1=require("path");const system_date_1=require("../system-date");const files_utils_1=require("../utils/files-utils");const istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=(0,path_1.normalize)(moduleName);const moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug(`building uniqueids map for ${moduleData.path}`);const before=(0,system_date_1.getSystemDateValueOf)();logger.debug(`file ${moduleData.path} not contains uniqueIdMaps, trying to reload`);createSLMapping(moduleData.path,relativePath,coverageObject,logger);const after=(0,system_date_1.getSystemDateValueOf)();logger.debug("*******************************create unique id map ******************************************");logger.debug(after-before);logger.debug("*******************************create unique id map ******************************************")}const newUniqueId=moduleData.uniqueIdsMap[uniqueIdKey];if(!newUniqueId){logger.error(`could not generate new uniqueId for '${uniqueIdKey}'`)}return newUniqueId}exports.resolveNewId=resolveNewId;function resolveModule(coverageObject,moduleName,logger){const withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);const moduleData=coverageObject[moduleName]||coverageObject[withLeftSlashes];if(!moduleData){logger.warn(`Coverage object not contains data for ${moduleName} or ${withLeftSlashes}`)}return moduleData}function createSLMapping(fullPath,relativePath,coverageObject,logger){const module=coverageObject[fullPath];const converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":275,"../utils/files-utils":278,"./istanbul-unique-id-converter":251,path:161}],253:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../utils/files-utils","../source-maps-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OriginalModuleLoader=void 0;const validation_utils_1=require("../utils/validation-utils");const files_utils_1=require("../utils/files-utils");const source_maps_utils_1=require("../source-maps-utils");const BRANCHES_MAP_KEY="branchMap";const METHODS_MAP_KEY="fnMap";class OriginalModuleLoader{constructor(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}load(){const modules=Object.keys(this.coverageObject);modules.map(moduleName=>this.tryLoadOriginalModule(moduleName))}tryLoadOriginalModule(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)}readOriginalModule(moduleName){const sourceMapsReader=this.getSourceMapForFile(moduleName);const module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(key=>this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName));Object.keys(module.fnMap).map(key=>this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName))}resolveAndAddMethod(method,sourceMapsReader,moduleName){const originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;const originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}}resolveAndAddBranch(branch,sourceMapsReader,moduleName){const originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;const originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){const originalLocations=branch.locations.map(locationElement=>this.createElementSourceData(locationElement,sourceMapsReader,moduleName));originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}}loadOriginalDataForElement(sourceMapsReader,element,moduleName,originalElement){const sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);const sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;const originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};const sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);const sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName}addElementToModule(moduleName,element,mapObjectKey){const module=this.getOrCreateIstanbulModule(moduleName);const key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}}createElementSourceData(locationElement,sourceMapsReader,moduleName){const sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);const sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}const sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement}getOrCreateIstanbulModule(moduleName){let module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module}getSourceMapForFile(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}const sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap}readSourceMapData(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{const originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){let originalFilename=originalPosition.source;if(originalFilename.indexOf("webpack:///webpack/")===-1&&originalFilename.indexOf("webpack:///external")===-1){if(originalFilename.indexOf("webpack:///")===0){originalFilename=originalFilename.substring(11)}originalFilename=files_utils_1.FilesUtils.resolveOriginalFullFileName(fullPath,originalFilename);const originalPositionObj={line:originalPosition.line,column:originalPosition.column};const result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null}createElementKey(element){return element.loc.start.line+":"+element.loc.start.column}createEmptyBranchObject(){return{loc:{},locations:[],type:"",line:null}}createEmptyMethodObject(){return{loc:{},name:"",line:null}}createIstanbulModule(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,uniqueIdsMap:null}}get fileToSourceMapConsumer(){return this._fileToSourceMapConsumer}set fileToSourceMapConsumer(value){this._fileToSourceMapConsumer=value}}exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":272,"../utils/files-utils":278,"../utils/validation-utils":280}],254:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./file-element"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.UniqueIdConverter=void 0;const contracts_1=require("./contracts");const file_element_1=require("./file-element");const METHOD_DELIMITER="@";const BRANCH_DELIMITER="|";const NULL_PARAM_MESSAGE="cannot be null or undefined";class UniqueIdConverter{constructor(filename,logger){if(!filename){throw new Error("'filename' "+NULL_PARAM_MESSAGE)}if(!logger){throw new Error("'logger' "+NULL_PARAM_MESSAGE)}this._filename=filename;this.logger=logger;this._uniqueIdsMap={};this._methodsArray=[];this._branchesArray=[]}sortElements(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)}createElementsArray(file){file.methods=file.methods||[];file.branches=file.branches||[];this.fillFileElementsArray(file.methods,this._methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(file.branches,this._branchesArray,contracts_1.ElementType.BRANCH)}createFileElement(element,filename,type){const startPosition=this.createElementPosition(element.position);const endPosition=this.createElementPosition(element.endPosition);const fileElement=new file_element_1.FileElement(type,startPosition,endPosition,element.uniqueId,filename);if(element.uniqueId_decl){fileElement.uniqueIdKey_decl=element.uniqueId_decl}if(element.parentPosition){const index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}return fileElement}process(){this.removeDuplicateElements(this._methodsArray);this.removeDuplicateElements(this._branchesArray);this.sortElements();this.logger.debug(`sorted ${this._branchesArray.length} branches`);this.logger.debug(`sorted ${this._methodsArray.length} methods`);this.fillUniqueIdsMap()}setAndInitFile(file){this.createElementsArray(file)}createElementPosition(position){let line;let column;if(Array.isArray(position)&&position.length===2){line=parseInt(position[0]);column=parseInt(position[1])}else{throw new Error("element has no correct startPosition array, cannot resolve startPosition")}return{column:column,line:line}}fillFileElementsArray(elements,array,type){for(const element of elements){array.push(this.createFileElement(element,this._filename,type))}}fillUniqueIdsMap(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)}createNewUniqueIds(array,delimiter){const aggregatedByLine=this.aggregateElementsByLine(array);const lines=Object.keys(aggregatedByLine);for(const line of lines){const indexesArray=aggregatedByLine[line];for(let i=0;i<indexesArray.length;i++){const currentIndex=indexesArray[i];const currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug(`[UniqueIdConverter] uniqueId ${currentElement.uniqueIdKey} converted to
4
+ branch: ${configuration.branchName}. Error ${e}`)}}start(){if(this.instances.length==0){return}this.instances.forEach(instance=>instance.start());this.running=true}stop(){return __awaiter(this,void 0,void 0,function*(){yield Promise.all(this.instances.map(instance=>instance.stop()));this.running=false})}isRunning(){return this.running}setCurrentTestIdentifier(identifier){this.instances.forEach(instance=>instance.setCurrentTestIdentifier(identifier))}sendAllFootprints(){return __awaiter(this,void 0,void 0,function*(){context_message_manager_1.ContextMessageManager.getInstance().sendAllEvents();yield Promise.all(this.instances.map(instance=>instance.submitFootprintsSync()))})}}exports.BrowserAgent=BrowserAgent})},{"./agent-factory":176,"./events-bridge/context-message-manager":196,"./logger/log-factory":209}],180:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/events-process"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserEventsProcess=void 0;const events_process_1=require("../../common/events-process");class BrowserEventsProcess extends events_process_1.EventsProcess{stop(){return __awaiter(this,void 0,void 0,function*(){this.isRunning=false;this.sendToServerWatchdog.stop();if(this.configuration.enabled.value===false||this.configuration.sendEvents.value===false){return}const callback=err=>{if(err){this.logger.error(`Failed to submit final events, Error : '${err}'`)}};while(this.eventsQueue.getQueueSize()>0){const items=this.eventsQueue.dequeue(events_process_1.EventsProcess.ITEMS_TO_DEQUE);const packet=this.createEventsPacket(items);this.backendProxy.submitEvents(packet,callback,false)}})}}exports.BrowserEventsProcess=BrowserEventsProcess})},{"../../common/events-process":255}],181:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/footprints-buffer","../../common/contracts","./events-bridge/context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserFootprintsBuffer=void 0;const footprints_buffer_1=require("../../common/footprints-process-v6/footprints-buffer");const contracts_1=require("../../common/contracts");const context_message_manager_1=require("./events-bridge/context-message-manager");class BrowserFootprintsBuffer extends footprints_buffer_1.FootprintsBuffer{constructor(agentInstanceData,agentConfig,footprintsMapping){super(agentInstanceData,agentConfig);this.contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();this.meta.footprintsMapping=footprintsMapping===contracts_1.FootprintsMapping.SERVER?footprintsMapping:contracts_1.FootprintsMapping.AGENT}createPacket(){var _a;const packet=super.createPacket();(_a=packet===null||packet===void 0?void 0:packet.executions)===null||_a===void 0?void 0:_a.forEach(execution=>{var _a;(_a=execution===null||execution===void 0?void 0:execution.hits)===null||_a===void 0?void 0:_a.forEach(hit=>{if(hit.testName){this.contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED,1)}else{this.contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON,1)}})});return packet}}exports.BrowserFootprintsBuffer=BrowserFootprintsBuffer})},{"../../common/contracts":248,"../../common/footprints-process-v6/footprints-buffer":260,"./events-bridge/context-message-manager":196}],182:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/hits-collector"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsCollector=void 0;const hits_collector_1=require("../../common/footprints-process-v6/hits-collector");class BrowserHitsCollector extends hits_collector_1.HitsCollector{constructor(buildSessionId,logger,globalCoverageObject){super(logger,globalCoverageObject);this.buildSessionId=buildSessionId}getGlobalCoverageObject(){if(!this.globalCoverageObject){const coverageObject="$SealightsCoverage";const coverageObjectForBSID=`${coverageObject}_${this.buildSessionId}`;this.globalCoverageObject=window[coverageObjectForBSID]||window[coverageObject]}return this.globalCoverageObject}}exports.BrowserHitsCollector=BrowserHitsCollector})},{"../../common/footprints-process-v6/hits-collector":261}],183:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/footprints-process-v6/base-browser-hits-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserHitsConverter=void 0;const base_browser_hits_converter_1=require("../../common/footprints-process-v6/base-browser-hits-converter");class BrowserHitsConverter extends base_browser_hits_converter_1.BaseBrowserHitsConverter{constructor(relativePathResolver,window,buildSessionId,logger){super(relativePathResolver,buildSessionId,logger);this.window=window}getSlMapping(){return this.window.slMappings[this.buildSessionId]||{}}}exports.BrowserHitsConverter=BrowserHitsConverter})},{"../../common/footprints-process-v6/base-browser-hits-converter":256}],184:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CodeCoverageManager=void 0;class CodeCoverageManager{constructor(convertor,configuration){this.convertor=convertor;this.configuration=configuration;this.aggregatedCoverage={};this.isDestroyed=false}findCoverageContainer(){const coverageObject="$SealightsCoverage";const coverageObjectForBSID=`${coverageObject}_${this.configuration.buildSessionId}`;return window[coverageObjectForBSID]||window[coverageObject]}getFootprints(testInfo){const counters=this.getCounters(true);return this.convertor.convert(counters,testInfo.testName,testInfo.executionId)}_clearCounters(istanbulCoverageObject){if(!istanbulCoverageObject)return;if(this.isDestroyed)return;const context=this;this.forEachProp(istanbulCoverageObject,function(moduleName,m){context.aggregatedCoverage[moduleName]=context.aggregatedCoverage[moduleName]||{s:{},b:{},f:{}};const am=context.aggregatedCoverage[moduleName];context.forEachProp(m.s,function(sid,s){am.s[sid]=(am.s[sid]||0)+m.s[sid];m.s[sid]=0});context.forEachProp(m.b,function(bid,b){am.b[bid]=am.b[bid]||Array.apply(null,Array(m.b[bid].length)).map(Number.prototype.valueOf,0);for(let idx=0;idx<am.b[bid].length;idx++){am.b[bid][idx]+=m.b[bid][idx];m.b[bid][idx]=0}});context.forEachProp(m.f,function(fid,f){am.f[fid]=(am.f[fid]||0)+m.f[fid];m.f[fid]=0})})}cloneCodeMetrics(o){const cloned={};for(const i in o){cloned[i]=this.cloneModule(o[i])}return cloned}cloneModule(m){const cm={b:{},f:{},s:{}};for(const i in m.s){cm.s[i]=m.s[i]}for(const i in m.f){cm.f[i]=m.f[i]}for(const i in m.b){cm.b[i]=m.b[i].slice()}cm.metadata=m.metadata;cm.path=m.path;cm.fnMap=m.fnMap;cm.fnToBranch=m.fnToBranch;cm.branchMap=m.branchMap;cm.inputSourceMap=m.inputSourceMap;return cm}forEachProp(obj,func){Object.keys(obj).forEach(function(k){func(k,obj[k])})}clearCounters(){if(this.isDestroyed)return;const ct=this.findCoverageContainer();if(ct){this._clearCounters(ct)}}getCounters(clearAfterwards){if(this.isDestroyed)return{};const ct=this.findCoverageContainer();if(ct){const ret=this.cloneCodeMetrics(ct);if(clearAfterwards)this._clearCounters(ct);return ret}}}exports.CodeCoverageManager=CodeCoverageManager})},{}],185:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ColorContextManager=void 0;class ColorContextManager{constructor(){this.windowObj=window;this.testName=null;this.executionId=null}setTestName(testName){this.testName=testName}setExecutionId(executionId){if(!(executionId===null||executionId===void 0?void 0:executionId.length)){return this.executionId=null}const isValid=executionId.indexOf("/")===-1;if(!isValid){throw new Error(`Invalid executionId received: ${executionId}. executionId cannot contain backslash('/') character.`)}this.executionId=executionId}setCurrentTestIdentifier(testName,executionId){var _a;this.setExecutionId(executionId);this.setTestName(testName);(_a=this.windowObj.$SealightsAgent)===null||_a===void 0?void 0:_a.setCurrentTestIdentifier(this.getCurrentTestIdentifier())}getCurrentTestIdentifier(){var _a,_b;if(!((_a=this.testName)===null||_a===void 0?void 0:_a.length)||!((_b=this.executionId)===null||_b===void 0?void 0:_b.length))return null;return`${this.executionId}/${this.testName}`}getTestName(){return this.testName}getExecutionId(){return this.executionId}}exports.ColorContextManager=ColorContextManager})},{}],186:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SL_AGENT_TYPE=exports.SL_AGENT_VERSION=void 0;exports.SL_AGENT_VERSION="6.1.627";exports.SL_AGENT_TYPE="browser"})},{}],187:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/configuration-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationManager=void 0;const configuration_data_1=require("./entities/configuration-data");class ConfigurationManager{constructor(logger,basicConfiguration,window){this.logger=logger;this.basicConfiguration=basicConfiguration;this.window=window;if(logger==null)throw new Error("'logger' cannot be null or undefined");if(basicConfiguration==null)throw new Error("'basicConfiguration' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined")}getConfiguration(){if(this.currentConfiguration)return this.currentConfiguration;const configurationData=this.getDefaults();this.overrideConfiguration(configurationData);configurationData.labId=this.resolveLabId();this.currentConfiguration=configurationData;this.printConfiguration(configurationData);this.validateConfiguration(configurationData);return configurationData}getDefaults(){const config=new configuration_data_1.ConfigurationData;config.appName=this.basicConfiguration.appName;config.branchName=this.basicConfiguration.branchName;config.buildName=this.basicConfiguration.buildName;config.buildSessionId=this.basicConfiguration.buildSessionId;config.customerId=this.basicConfiguration.customerId;config.token=this.basicConfiguration.token;config.server=this.basicConfiguration.server;config.interval=this.basicConfiguration.interval||10;config.maxItemsInQueue=this.basicConfiguration.maxItemsInQueue||500;config.workspacepath=this.basicConfiguration.workspacepath;return config}resolveLabId(){let labId=this.readLabIdFromWindow();if(labId){this.logger.info("Using labId from the 'window' object. LabId:"+labId);return labId}labId=this.basicConfiguration.labId;if(labId){this.logger.info("Using labId from basic configuration. LabId:"+labId);return labId}labId=this.readLabIdFromSessionStorage();if(labId){this.logger.info("Using labId from session storage. LabId:"+labId);return labId}labId=this.basicConfiguration.buildSessionId;if(labId){this.logger.info("Using buildSessionId as labId. LabId:"+labId);return labId}labId=this.basicConfiguration.appName;if(labId){this.logger.info("Using appName as labId. LabId:"+labId);return labId}return"DefaultLabId"}overrideConfiguration(configurationData){for(const p in this.basicConfiguration){configurationData[p]=this.basicConfiguration[p]}this.logger.info("[TO CS] - TODO: Send request to server to get the configuration.")}printConfiguration(configurationData){this.logger.info("***********************************************************");this.logger.info("Current configuration:");this.logger.info("------------------------------------------------");for(const prop in configurationData){this.logger.info(prop+": '"+configurationData[prop])+"'"}this.logger.info("***********************************************************")}validateConfiguration(configurationData){const fieldsWithError=[];if(!configurationData.customerId||configurationData.customerId=="")fieldsWithError.push("customerId");if(!configurationData.server||configurationData.server=="")fieldsWithError.push("server");if(!configurationData.appName||configurationData.appName=="")fieldsWithError.push("appName");if(!configurationData.branchName||configurationData.branchName=="")fieldsWithError.push("branchName");if(!configurationData.buildName||configurationData.buildName=="")fieldsWithError.push("buildName");if(!configurationData.token||configurationData.token=="")fieldsWithError.push("token");if(fieldsWithError.length>0){this.logger.warn("------------------------------------------------");this.logger.warn("Detected an invalid configuration:");fieldsWithError.forEach(field=>{this.logger.warn("'"+field+"' is required but it had a 'null' or empty value.")});this.logger.warn("Please fix the configuration prior to using SeaLights.");this.logger.warn("------------------------------------------------")}this._isValidConfiguration=fieldsWithError.length==0}isValidConfiguration(){return this._isValidConfiguration}readLabIdFromSessionStorage(){let labId=null;if(this.window.sessionStorage&&typeof this.window.sessionStorage==="function"){labId=this.window.sessionStorage.getItem(ConfigurationManager.LAB_ID_KEY)}return labId}readLabIdFromWindow(){return this.window[ConfigurationManager.LAB_ID_KEY]}}exports.ConfigurationManager=ConfigurationManager;ConfigurationManager.LAB_ID_KEY="__sl.labId__"})},{"./entities/configuration-data":192}],188:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./logger/console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationOverride=exports.ConfigChangedEvents=void 0;const EventEmitter=require("events");const console_logger_1=require("./logger/console-logger");var ConfigChangedEvents;(function(ConfigChangedEvents){ConfigChangedEvents["LOG_LEVEL_CHANGED"]="logLevelChanged"})(ConfigChangedEvents=exports.ConfigChangedEvents||(exports.ConfigChangedEvents={}));class ConfigurationOverride extends EventEmitter{constructor(initialConfig){super();this._logLevel=console_logger_1.LogLevels.INFO;this.setMaxListeners(500);this.loadInitialConfig(initialConfig)}get logLevel(){return this._logLevel}set logLevel(value){this._logLevel=value;this.emit(ConfigChangedEvents.LOG_LEVEL_CHANGED,value)}loadInitialConfig(initialConfig={}){for(const prop in initialConfig){const descriptor=Object.getOwnPropertyDescriptor(this.constructor.prototype,prop);if(descriptor&&typeof descriptor.set==="function"){this[prop]=initialConfig[prop]}}}static create(configuration){if(configuration instanceof ConfigurationOverride){return configuration}return new ConfigurationOverride(configuration)}}exports.ConfigurationOverride=ConfigurationOverride})},{"./logger/console-logger":208,events:158}],189:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ExecutionStatus=void 0;var ExecutionStatus;(function(ExecutionStatus){ExecutionStatus["InProgress"]="created";ExecutionStatus["Ending"]="pendingDelete"})(ExecutionStatus=exports.ExecutionStatus||(exports.ExecutionStatus={}))})},{}],190:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Delegate=void 0;class Delegate{constructor(){this.functions=new Array}addListener(func){if(!func)return;if(this.functions)this.functions.push(func)}fire(){if(!this.functions)return;for(let i=0;i<this.functions.length;i++){this.functions[i]()}}}exports.Delegate=Delegate})},{}],191:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicConfigurationData=void 0;class BasicConfigurationData{}exports.BasicConfigurationData=BasicConfigurationData})},{}],192:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./basic-configuation-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationData=void 0;const basic_configuation_data_1=require("./basic-configuation-data");class ConfigurationData extends basic_configuation_data_1.BasicConfigurationData{constructor(){super(...arguments);this.registerShutdownHook=true;this.enabled=true}}exports.ConfigurationData=ConfigurationData})},{"./basic-configuation-data":191}],193:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvironmentData=void 0;const config_1=require("../config");class EnvironmentData{static create(configuration){const data=new EnvironmentData;data.agentType=config_1.SL_AGENT_TYPE;data.agentVersion=config_1.SL_AGENT_VERSION;data.agentId=EnvironmentData.constantAgentId;data.labId=configuration.labId||"";data.meta={navigator:window.navigator,userAgent:window.navigator&&window.navigator.userAgent,location:window.location};return data}}exports.EnvironmentData=EnvironmentData})},{"../config":186}],194:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemData=void 0;class FootprintsItemData{}exports.FootprintsItemData=FootprintsItemData})},{}],195:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.relativePathRegex=exports.EVENTS=exports.EVENT_TYPES=exports.SL_CONTEXT_DIAGNOSIS=exports.SL_SESSION_CONTEXT=exports.CONTEXT=exports.SL_EVENTS_BRIDGE=exports.SL_EXECUTION_ID=exports.SL_TEST_NAME=exports.SL_SESSION_ID=exports.SL_CONTEXT_KEY=exports.SL_BAGGAGE_HEADER=void 0;exports.SL_BAGGAGE_HEADER="baggage";exports.SL_CONTEXT_KEY="sl-context";exports.SL_SESSION_ID="x-sl-test-session-id";exports.SL_TEST_NAME="x-sl-test-name";exports.SL_EXECUTION_ID="x-sl-execution-id";exports.SL_EVENTS_BRIDGE="sl-events-bridge";exports.CONTEXT="context";exports.SL_SESSION_CONTEXT="sl-session-ctx";exports.SL_CONTEXT_DIAGNOSIS="sl-ctx-test";exports.EVENT_TYPES={SET:"set",ACK:"ack",DELETE:"delete",READY:"ready",REQUEST:"request",RESPONSE:"response"};exports.EVENTS={SET_BAGGAGE:`${exports.EVENT_TYPES.SET}:${exports.SL_BAGGAGE_HEADER}`,SET_CONTEXT:`${exports.EVENT_TYPES.SET}:${exports.CONTEXT}`,ACK_BAGGAGE:`${exports.EVENT_TYPES.ACK}:${exports.SL_BAGGAGE_HEADER}`,ACK_CONTEXT:`${exports.EVENT_TYPES.ACK}:${exports.CONTEXT}`,DELETE_BAGGAGE:`${exports.EVENT_TYPES.DELETE}:${exports.SL_BAGGAGE_HEADER}`,DELETE_CONTEXT:`${exports.EVENT_TYPES.DELETE}:${exports.CONTEXT}`,READY_EVENTS_BRIDGE:`${exports.EVENT_TYPES.READY}:${exports.SL_EVENTS_BRIDGE}`,REQUEST_AGENT_CONTEXT:`${exports.EVENT_TYPES.REQUEST}:${exports.SL_CONTEXT_KEY}`,RESPONSE_AGENT_CONTEXT:`${exports.EVENT_TYPES.RESPONSE}:${exports.SL_CONTEXT_KEY}`};exports.relativePathRegex=new RegExp("^(?!www\\.|(?:http|ftp)s?://|[A-Za-z]:\\\\|//).*")})},{}],196:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/agent-events/cockpit-notifier","../../../common/agent-events/agent-events-contracts","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ContextMessageManager=exports.CONTEXT_EVENTS_KEYS=void 0;const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const agent_events_contracts_1=require("../../../common/agent-events/agent-events-contracts");const system_date_1=require("../../../common/system-date");var CONTEXT_EVENTS_KEYS;(function(CONTEXT_EVENTS_KEYS){CONTEXT_EVENTS_KEYS["SET_EVENTS_RECEIVED"]="setEventsReceived";CONTEXT_EVENTS_KEYS["DELETE_EVENTS_RECEIVED"]="deleteEventsReceived";CONTEXT_EVENTS_KEYS["EVENTS_WITH_PERSIST"]="eventsWithPersist";CONTEXT_EVENTS_KEYS["WITH_BAGGAGE"]="withBaggage";CONTEXT_EVENTS_KEYS["WITHOUT_BAGGAGE"]="withoutBaggage";CONTEXT_EVENTS_KEYS["FOOTPRINTS_LAST_SUBMISSION_COLORED"]="footprintsLastSubmissionColored";CONTEXT_EVENTS_KEYS["FOOTPRINTS_LAST_SUBMISSION_ANON"]="footprintsLastSubmissionAnon";CONTEXT_EVENTS_KEYS["FOOTPRINTS_COLORED"]="footprintsColored";CONTEXT_EVENTS_KEYS["FOOTPRINTS_ANON"]="footprintsAnon"})(CONTEXT_EVENTS_KEYS=exports.CONTEXT_EVENTS_KEYS||(exports.CONTEXT_EVENTS_KEYS={}));class ContextMessageManager{constructor(sendCockpitEvents){this.sendCockpitEvents=sendCockpitEvents;this.sources=[];this.contextDataTracking={[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED]:0,[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED]:0,[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]:0,[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE]:0,[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]:0,[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]:0}}static getInstance(sendCockpitEvents=true){return this._instance||(this._instance=new this(sendCockpitEvents))}startContextManager(){if(this.sendCockpitEvents){setInterval(()=>{this.sendAllEvents()},ContextMessageManager.DEFAULT_SEND_INTERVAL)}}incrementContextEventValue(eventKey,incrementBy){if(incrementBy<=0){return}this.contextDataTracking[eventKey]+=incrementBy;switch(eventKey){case CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED:{this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]=(0,system_date_1.getSystemDateValueOf)();break}case CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON:{this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]=(0,system_date_1.getSystemDateValueOf)();break}case CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:case CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE:{this.sources=this.sources.map(source=>{var _a;source.firstSpanDate=(_a=source.firstSpanDate)!==null&&_a!==void 0?_a:(0,system_date_1.getSystemDateValueOf)();source.lastSpanDate=(0,system_date_1.getSystemDateValueOf)();source.count++;return source});break}}}sendAllEvents(){cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_contracts_1.AgentEventCode.CONTEXT_PROPAGATION_TELEMETRY,{contextPropagation:this.getState()})}addSource(source){const sourceIndex=this.sources.findIndex(existingSource=>{return existingSource.agentId&&existingSource.agentId===source.agentId||existingSource.buildSessionId&&existingSource.buildSessionId===source.buildSessionId||existingSource.appName&&existingSource.appName===source.appName});if(sourceIndex>-1){return}this.sources.push(Object.assign(Object.assign({},source),{count:0,firstSpanDate:undefined,lastSpanDate:undefined}))}getState(){return{internalEvents:{[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED],[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED],[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]:this.contextDataTracking[CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST]},spans:{opened:{withBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE],withoutBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]},closed:{withBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITH_BAGGAGE],withoutBaggage:this.contextDataTracking[CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE]}},footprintsRequests:{colored:{count:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_COLORED],lastSubmission:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_COLORED]},anon:{count:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_ANON],lastSubmission:this.contextDataTracking[CONTEXT_EVENTS_KEYS.FOOTPRINTS_LAST_SUBMISSION_ANON]}},sources:this.sources}}getSources(){return this.sources}}exports.ContextMessageManager=ContextMessageManager;ContextMessageManager.DEFAULT_SEND_INTERVAL=60*1e3})},{"../../../common/agent-events/agent-events-contracts":227,"../../../common/agent-events/cockpit-notifier":234,"../../../common/system-date":275}],197:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deleteCookie=exports.setCookie=exports.getCookie=void 0;function getCookie(cookieName){const name=cookieName.trim()+"=";const decodedCookie=decodeURIComponent(document.cookie);const cookieArray=decodedCookie.split(";");for(let i=0;i<cookieArray.length;i++){const cookie=cookieArray[i].trim();if(cookie.indexOf(name)===0){const cookieValue=cookie.substring(name.length,cookie.length);return(cookieValue===null||cookieValue===void 0?void 0:cookieValue.length)?cookieValue:null}}return null}exports.getCookie=getCookie;function setCookie(cookieKey,cookieValue){document.cookie=cookieKey+"="+encodeURIComponent(cookieValue)}exports.setCookie=setCookie;function deleteCookie(cookieKey){const expiration="expires=Thu, 01 Jan 1970 00:00:00 UTC";document.cookie=cookieKey+"=;"+expiration}exports.deleteCookie=deleteCookie})},{}],198:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./const","@opentelemetry/api","../../../common/agent-events/cockpit-notifier","./context-message-manager","./utils","./cookie-utils","../agent-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deleteBaggageHandler=exports.deleteContextHandler=exports.setContextHandler=exports.setBaggageHandler=exports.checkExistingCookies=exports.checkExistingContext=exports.registerEvents=void 0;const SlConst=require("./const");const api=require("@opentelemetry/api");const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const context_message_manager_1=require("./context-message-manager");const utils_1=require("./utils");const cookie_utils_1=require("./cookie-utils");const agent_factory_1=require("../agent-factory");let SlContext;const registerEvents=(logger,withOpenTelemetry,sendCockpitEvents=false)=>{try{const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance(sendCockpitEvents);contextMessageManager.startContextManager();const colorContextManager=agent_factory_1.AgentFactory.getColorContextManager();window.$Sealights.eventsBridge={loaded:false,otel:false};if(withOpenTelemetry){SlContext=api.ROOT_CONTEXT.setValue(api.createContextKey(SlConst.SL_CONTEXT_KEY),true);window.$Sealights.eventsBridge.getBaggage=()=>SlContext.getValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));window.$Sealights.eventsBridge.getContext=()=>SlContext.getValue(api.createContextKey(SlConst.CONTEXT));window.$Sealights.eventsBridge.otel=true}addEventListener(SlConst.EVENTS.SET_BAGGAGE,({detail})=>{const incrementSetEvents=(detail===null||detail===void 0?void 0:detail.incrementSetEvents)!==false;setBaggageHandler(detail,contextMessageManager,colorContextManager,withOpenTelemetry,logger,incrementSetEvents)});addEventListener(SlConst.EVENTS.SET_CONTEXT,({detail})=>setContextHandler(detail,contextMessageManager,withOpenTelemetry,logger));addEventListener(SlConst.EVENTS.REQUEST_AGENT_CONTEXT,()=>{dispatchEvent(new CustomEvent(SlConst.EVENTS.RESPONSE_AGENT_CONTEXT,{detail:{components:window.$Sealights.components||{}}}))});addEventListener(SlConst.EVENTS.DELETE_BAGGAGE,()=>deleteBaggageHandler(contextMessageManager,colorContextManager));addEventListener(SlConst.EVENTS.DELETE_CONTEXT,()=>deleteContextHandler(contextMessageManager,colorContextManager));window.$Sealights.eventsBridge.loaded=true;logger.info(`Events Bridge integration loaded. All events registered successfully. OpenTelemetry status: ${withOpenTelemetry}`);const sessionContext=checkExistingContext(logger);if(!sessionContext){checkExistingCookies(logger)}}catch(error){logger.error(`An error occurred while registering OpenTelemetry integration events.`,error);window.$Sealights.eventsBridge.error=error;cockpit_notifier_1.CockpitNotifier.sendError(JSON.stringify(error,Object.getOwnPropertyNames(error)))}};exports.registerEvents=registerEvents;function checkExistingContext(logger){const existingContext=sessionStorage.getItem(SlConst.SL_SESSION_CONTEXT);if(!(existingContext===null||existingContext===void 0?void 0:existingContext.length)){return false}const parsedContext=JSON.parse(existingContext);logger.info(`Found existing context in session storage. Dispatching event with data: ${existingContext}`);const storedContextEvent=new CustomEvent(SlConst.EVENTS.SET_CONTEXT,{detail:parsedContext});dispatchEvent(storedContextEvent);return true}exports.checkExistingContext=checkExistingContext;function checkExistingCookies(logger){const testNameCookieValue=(0,cookie_utils_1.getCookie)(SlConst.SL_TEST_NAME);const executionIdCookieValue=(0,cookie_utils_1.getCookie)(SlConst.SL_EXECUTION_ID);if(!(testNameCookieValue===null||testNameCookieValue===void 0?void 0:testNameCookieValue.length)||!(executionIdCookieValue===null||executionIdCookieValue===void 0?void 0:executionIdCookieValue.length)){return false}logger.info(`Found existing test name and executionId cookies. Dispatching event with data: ${testNameCookieValue}/${executionIdCookieValue}`);dispatchEvent(new CustomEvent(SlConst.EVENTS.SET_BAGGAGE,{detail:{[SlConst.SL_SESSION_ID]:executionIdCookieValue,[SlConst.SL_TEST_NAME]:testNameCookieValue}}));return true}exports.checkExistingCookies=checkExistingCookies;function setBaggageHandler(detail,contextMessageManager,colorContextManager,withOpenTelemetry,logger,incrementSetEvents=true){if(incrementSetEvents){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED,1)}logger.info(`setBaggage: Received event "detail": ${JSON.stringify(detail,null,4)}`);if(!detail){logger.warn(`Received setBaggage event with no detail, not changing baggage.`);return}const executionId=detail[SlConst.SL_SESSION_ID];const testName=detail[SlConst.SL_TEST_NAME];if(!(executionId===null||executionId===void 0?void 0:executionId.length)||!(testName===null||testName===void 0?void 0:testName.length)){logger.warn(`Received setBaggage event with with missing testName/executionId: testName=${testName} executionId=${executionId}`);return}if((0,utils_1.checkIsDiagnosisBaggage)(detail)){return(0,utils_1.sendAckEvent)(detail)}if(withOpenTelemetry){SlContext=SlContext.setValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER),{[SlConst.SL_SESSION_ID]:executionId,[SlConst.SL_TEST_NAME]:encodeURIComponent(testName)})}colorContextManager.setCurrentTestIdentifier(testName,executionId);(0,cookie_utils_1.setCookie)(SlConst.SL_EXECUTION_ID,executionId);(0,cookie_utils_1.setCookie)(SlConst.SL_TEST_NAME,testName);(0,utils_1.sendAckEvent)(detail)}exports.setBaggageHandler=setBaggageHandler;function setContextHandler(detail,contextMessageManager,withOpenTelemetry,logger){var _a;logger.info(`setContext: Received event "detail": ${JSON.stringify(detail,null,4)}`);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.SET_EVENTS_RECEIVED,1);if(!detail){logger.info(`Received setContext event with no detail, not changing context.`);return}if((0,utils_1.checkIsDiagnosisBaggage)(detail[SlConst.SL_BAGGAGE_HEADER])){return(0,utils_1.sendAckEvent)(detail)}detail.persist=detail.persist!==false;if(detail.persist){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.EVENTS_WITH_PERSIST,1);sessionStorage.setItem(SlConst.SL_SESSION_CONTEXT,JSON.stringify(detail))}dispatchEvent(new CustomEvent(SlConst.EVENTS.SET_BAGGAGE,{detail:Object.assign(Object.assign({},(_a=detail[SlConst.SL_BAGGAGE_HEADER])!==null&&_a!==void 0?_a:{}),{incrementSetEvents:false})}));delete detail[SlConst.SL_BAGGAGE_HEADER];if(withOpenTelemetry){SlContext=SlContext.setValue(api.createContextKey(SlConst.CONTEXT),detail)}(0,utils_1.sendAckEvent)(detail)}exports.setContextHandler=setContextHandler;function deleteContextHandler(contextMessageManager,colorContextManager){SlContext=SlContext.deleteValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));SlContext=SlContext.deleteValue(api.createContextKey(SlConst.CONTEXT));colorContextManager.setCurrentTestIdentifier(null,null);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED,1);(0,cookie_utils_1.deleteCookie)(SlConst.SL_TEST_NAME);(0,cookie_utils_1.deleteCookie)(SlConst.SL_EXECUTION_ID)}exports.deleteContextHandler=deleteContextHandler;function deleteBaggageHandler(contextMessageManager,colorContextManager){SlContext=SlContext.deleteValue(api.createContextKey(SlConst.SL_BAGGAGE_HEADER));colorContextManager.setCurrentTestIdentifier(null,null);contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.DELETE_EVENTS_RECEIVED,1);(0,cookie_utils_1.deleteCookie)(SlConst.SL_TEST_NAME);(0,cookie_utils_1.deleteCookie)(SlConst.SL_EXECUTION_ID)}exports.deleteBaggageHandler=deleteBaggageHandler})},{"../../../common/agent-events/cockpit-notifier":234,"../agent-factory":176,"./const":195,"./context-message-manager":196,"./cookie-utils":197,"./utils":203,"@opentelemetry/api":18}],199:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation-fetch","../utils","../context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CustomFetchInstrumentation=exports.handleAddHeaders=void 0;const instrumentation_fetch_1=require("@opentelemetry/instrumentation-fetch");const utils_1=require("../utils");const context_message_manager_1=require("../context-message-manager");const setPropagationHeaders=(options,contextPropagationHeaders)=>{for(const[key,value]of Object.entries(contextPropagationHeaders)){if(value){options.headers.set(key,typeof value==="string"?value:String(value))}}};function handleAddHeaders(options,spanUrl,allowCORS,logger){const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();const allowHeadersPropagation=(0,utils_1.shouldAddHeaders)(window.location.origin,spanUrl,allowCORS);if(!allowHeadersPropagation){if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}const originLog={current:window.location.origin,target:spanUrl};logger.warn(`Not adding header in CustomFetchInstrumentation because of origin difference: ${JSON.stringify(originLog,null,4)}`);return}const contextPropagationHeaders=Object.assign(Object.assign({},(0,utils_1.constructBaggageHeader)()),(0,utils_1.constructContextHeaders)());if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(Object.keys(contextPropagationHeaders).length?context_message_manager_1.CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}if(options instanceof Request&&contextPropagationHeaders){setPropagationHeaders(options,contextPropagationHeaders)}else if(options.headers instanceof Headers&&contextPropagationHeaders){setPropagationHeaders(options,contextPropagationHeaders)}else if(typeof options.headers==="object"&&options.headers!==null){for(const[key,value]of Object.entries(contextPropagationHeaders)){options.headers[key]=value}}else{options.headers=Object.assign({},contextPropagationHeaders,options.headers||{})}}exports.handleAddHeaders=handleAddHeaders;class CustomFetchInstrumentation extends instrumentation_fetch_1.FetchInstrumentation{constructor(config){super(config);this["_addHeaders"]=(options,spanUrl)=>{handleAddHeaders(options,spanUrl,config.allowCORS,config.logger)}}}exports.CustomFetchInstrumentation=CustomFetchInstrumentation})},{"../context-message-manager":196,"../utils":203,"@opentelemetry/instrumentation-fetch":89}],200:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation-xml-http-request","../utils","../context-message-manager"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CustomXMLHttpRequestInstrumentation=exports.handleAddHeaders=void 0;const instrumentation_xml_http_request_1=require("@opentelemetry/instrumentation-xml-http-request");const utils_1=require("../utils");const context_message_manager_1=require("../context-message-manager");function handleAddHeaders(xhr,spanUrl,allowCORS,logger){const contextMessageManager=context_message_manager_1.ContextMessageManager.getInstance();const allowHeadersPropagation=(0,utils_1.shouldAddHeaders)(window.location.origin,spanUrl,allowCORS);if(!allowHeadersPropagation){if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}const originLog={current:window.location.origin,target:spanUrl};logger.warn(`Not adding header in CustomXMLHttpRequestInstrumentation because of origin difference: ${JSON.stringify(originLog,null,4)}`);return}const headers=Object.assign(Object.assign({},(0,utils_1.constructBaggageHeader)()),(0,utils_1.constructContextHeaders)());if(!(0,utils_1.isSealightsAPI)(spanUrl)){contextMessageManager.incrementContextEventValue(Object.keys(headers).length?context_message_manager_1.CONTEXT_EVENTS_KEYS.WITH_BAGGAGE:context_message_manager_1.CONTEXT_EVENTS_KEYS.WITHOUT_BAGGAGE,1)}Object.keys(headers).forEach(headerKey=>{xhr.setRequestHeader(headerKey,headers[headerKey])})}exports.handleAddHeaders=handleAddHeaders;class CustomXMLHttpRequestInstrumentation extends instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation{constructor(config){super(config);this["_addHeaders"]=(xhr,spanUrl)=>{handleAddHeaders(xhr,spanUrl,config.allowCORS,config.logger)}}}exports.CustomXMLHttpRequestInstrumentation=CustomXMLHttpRequestInstrumentation})},{"../context-message-manager":196,"../utils":203,"@opentelemetry/instrumentation-xml-http-request":93}],201:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./otel","./events","./const"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.registerEventsBridge=void 0;const otel_1=require("./otel");const events_1=require("./events");const const_1=require("./const");const registerEventsBridge=(logger,enableOpenTelemetry,sendCockpitEvents=true,allowCORS)=>{var _a,_b,_c,_d;const eventsBridgeRegistered=(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)===null||_b===void 0?void 0:_b.loaded;const otelRegistered=(_d=(_c=window.$Sealights)===null||_c===void 0?void 0:_c.eventsBridge)===null||_d===void 0?void 0:_d.otel;if(!eventsBridgeRegistered){(0,events_1.registerEvents)(logger,enableOpenTelemetry,sendCockpitEvents)}if(enableOpenTelemetry&&!otelRegistered){(0,otel_1.registerOpenTelemetry)(logger,allowCORS)}const event=new Event(const_1.EVENTS.READY_EVENTS_BRIDGE);window.dispatchEvent(event)};exports.registerEventsBridge=registerEventsBridge})},{"./const":195,"./events":198,"./otel":202}],202:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","@opentelemetry/instrumentation","./implementations/CustomFetchInstrumentation","./implementations/CustomXMLHttpRequestInstrumentation","../../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.registerOpenTelemetry=void 0;const instrumentation_1=require("@opentelemetry/instrumentation");const CustomFetchInstrumentation_1=require("./implementations/CustomFetchInstrumentation");const CustomXMLHttpRequestInstrumentation_1=require("./implementations/CustomXMLHttpRequestInstrumentation");const cockpit_notifier_1=require("../../../common/agent-events/cockpit-notifier");const registerOpenTelemetry=(logger,allowCORS)=>{try{(0,instrumentation_1.registerInstrumentations)({instrumentations:[new CustomFetchInstrumentation_1.CustomFetchInstrumentation({allowCORS:allowCORS,logger:logger}),new CustomXMLHttpRequestInstrumentation_1.CustomXMLHttpRequestInstrumentation({allowCORS:allowCORS,logger:logger})]})}catch(error){logger.error(`An error occurred while registering OpenTelemetry Fetch/XMLHttp instrumentation.`,error);window.$Sealights.eventsBridge.error=error;cockpit_notifier_1.CockpitNotifier.sendError(JSON.stringify(error,Object.getOwnPropertyNames(error)))}};exports.registerOpenTelemetry=registerOpenTelemetry})},{"../../../common/agent-events/cockpit-notifier":234,"./implementations/CustomFetchInstrumentation":199,"./implementations/CustomXMLHttpRequestInstrumentation":200,"@opentelemetry/instrumentation":98}],203:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./const","./const"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSealightsAPI=exports.shouldAddHeaders=exports.sendAckEvent=exports.checkIsDiagnosisBaggage=exports.constructContextHeaders=exports.constructBaggageHeader=exports.mapHeaderValuesToString=void 0;const const_1=require("./const");const SlConst=require("./const");const mapHeaderValuesToString=headerValues=>{return Object.keys(headerValues!==null&&headerValues!==void 0?headerValues:{}).map(key=>{return`${key}=${headerValues[key]}`}).join()};exports.mapHeaderValuesToString=mapHeaderValuesToString;const constructBaggageHeader=()=>{var _a,_b;const{getBaggage}=((_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)||{};const baggage=(_b=getBaggage===null||getBaggage===void 0?void 0:getBaggage())!==null&&_b!==void 0?_b:{};if(!Object.keys(baggage).length){return{}}return{baggage:(0,exports.mapHeaderValuesToString)(baggage)}};exports.constructBaggageHeader=constructBaggageHeader;const constructContextHeaders=()=>{var _a,_b;const{getContext}=((_a=window.$Sealights)===null||_a===void 0?void 0:_a.eventsBridge)||{};const contextHeaders=(_b=getContext===null||getContext===void 0?void 0:getContext())!==null&&_b!==void 0?_b:{};if(!Object.keys(contextHeaders).length){return{}}const headers={};Object.entries(contextHeaders).forEach(entry=>{const[key,value]=entry;if(typeof value==="string"){headers[key]=value}else{headers[key]=(0,exports.mapHeaderValuesToString)(value)}});return headers};exports.constructContextHeaders=constructContextHeaders;const checkIsDiagnosisBaggage=baggage=>{const testName=baggage===null||baggage===void 0?void 0:baggage[const_1.SL_TEST_NAME];return testName===null||testName===void 0?void 0:testName.includes(const_1.SL_CONTEXT_DIAGNOSIS)};exports.checkIsDiagnosisBaggage=checkIsDiagnosisBaggage;const sendAckEvent=detail=>{dispatchEvent(new CustomEvent(SlConst.EVENTS.ACK_CONTEXT,{detail:detail}))};exports.sendAckEvent=sendAckEvent;const shouldAddHeaders=(origin,spanUrl,allowCORS)=>{if((allowCORS===null||allowCORS===void 0?void 0:allowCORS.trim())==="*")return true;const isRelativeUrl=const_1.relativePathRegex.test(spanUrl);if(isRelativeUrl){spanUrl=`${origin}${spanUrl.startsWith("/")?"":"/"}${spanUrl}`}const allowCORSArray=!(allowCORS===null||allowCORS===void 0?void 0:allowCORS.length)?[origin]:allowCORS===null||allowCORS===void 0?void 0:allowCORS.split(",");return allowCORSArray.some(propagationOrigin=>spanUrl===null||spanUrl===void 0?void 0:spanUrl.startsWith(propagationOrigin.trim()))};exports.shouldAddHeaders=shouldAddHeaders;const isSealightsAPI=spanUrl=>{try{const url=new URL(spanUrl);return url.origin.includes("sealights")}catch(error){return false}};exports.isSealightsAPI=isSealightsAPI})},{"./const":195}],204:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FeatureDetection=void 0;class FeatureDetection{constructor(window){this.window=window;if(!window)throw new Error("'window' cannot be null or undefined")}hasBeaconAPI(){const result=window.navigator&&this.isFunction(window.navigator["sendBeacon"]);return result}hasConsoleLogAPI(){const result=window.console&&this.isFunction(window.console.log);return result}hasJsonAPI(){const result=JSON&&this.isFunction(JSON.stringify)&&this.isFunction(JSON.parse);return result}isFunction(o){return o&&typeof o==="function"}}exports.FeatureDetection=FeatureDetection})},{}],205:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./entities/footprints-item-data","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsQueueSender=void 0;const footprints_item_data_1=require("./entities/footprints-item-data");const system_date_1=require("../../common/system-date");class FootprintsQueueSender{constructor(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsQueue,window,logger,slMappingLoader){this.watchdog=watchdog;this.lightBackendProxy=lightBackendProxy;this.codeCoverageManager=codeCoverageManager;this.stateTracker=stateTracker;this.testStateHelper=testStateHelper;this.environmentData=environmentData;this.configuration=configuration;this.footprintsQueue=footprintsQueue;this.window=window;this.logger=logger;this.slMappingLoader=slMappingLoader;this.isStarted=false;if(watchdog==null)throw new Error("'watchdog' cannot be null or undefined");if(lightBackendProxy==null)throw new Error("'lightBackendProxy' cannot be null or undefined");if(codeCoverageManager==null)throw new Error("'codeCoverageManager' cannot be null or undefined");if(stateTracker==null)throw new Error("'stateTracker' cannot be null or undefined");if(testStateHelper==null)throw new Error("'testStateHelper' cannot be null or undefined");if(environmentData==null)throw new Error("'environmentData' cannot be null or undefined");if(configuration==null)throw new Error("'configuration' cannot be null or undefined");if(footprintsQueue==null)throw new Error("'footprintsQueue' cannot be null or undefined");if(window==null)throw new Error("'window' cannot be null or undefined");if(logger==null)throw new Error("'logger' cannot be null or undefined");this.context=this;this.watchdog.addOnAlarmListener(()=>{this.context.onTimerTick()})}onTimerTick(){if(!this.stateTracker.shouldCollectFootprints()){return}const footprints=this.getCurrentFootprints();this.send(footprints)}start(){if(this.isStarted)return;this.watchdog.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId);this.isStarted=true}stop(){if(!this.isStarted)return;this.watchdog.stop();this.isStarted=false}send(footprintsData,async=true,shouldRequeue=true){if(!footprintsData){this.logger.info("No need to send footprints as the 'footprintsData' is null or undefined.");return}const request=this.createRequest(footprintsData);if(request==null){this.logger.info("No need to send footprints as the request is empty.");return}const context=this;const onSuccess=function(){context.logger.info("Sent footprints successfully")};const onError=function(response){context.logger.error("Failed while trying to send footprints. response.responseText: '"+response.responseText+"'. response.statusCode:"+response.statusCode);if(shouldRequeue){context.logger.info("Requeuing footprints again");context.footprintsQueue.requeueItems(footprintsData)}};this.lightBackendProxy.submitRequest(request,onSuccess,onError,async)}sendAllSync(){if(!this.stateTracker.shouldCollectFootprints()){return}this.logger.info("Sending all remaining footprints synchronously.");this.delayIfHasRequestsInProgress();const async=false;const footprints=this.getCurrentFootprints();this.send(footprints,async)}sendAll(){const footprints=this.getCurrentFootprints();this.send(footprints)}delayIfHasRequestsInProgress(){let counter=this.configuration.delayShutdownInSeconds||30;while(this.lightBackendProxy.hasRequestsInProgress()&&counter-- >0){this.logger.info("Has other requests in progress. Sleeping.. # of requests: "+this.lightBackendProxy.getRequestsInProgressCount()+". Remaining retries: "+counter);this.sleep(1e3)}}pushCurrentFootprints(){if(!this.stateTracker.shouldCollectFootprints()){return}const testId=this.stateTracker.getCurrentTestIdentifier();const testInfo=this.testStateHelper.splitTestIdToExecutionAndTestName(testId);const footprints=this.codeCoverageManager.getFootprints(testInfo);if(this.configuration.resolveWithoutHash){this.enqueueV5Footprints(footprints)}else{this.enqueueV2Footprints(footprints,testInfo)}}enqueueV2Footprints(appsAndFootprintsArray,testInfo){if(appsAndFootprintsArray&&appsAndFootprintsArray.length){const queueItem=new footprints_item_data_1.FootprintsItemData;queueItem.testName=testInfo.testName;queueItem.executionId=testInfo.executionId;queueItem.apps=appsAndFootprintsArray;this.footprintsQueue.enqueueItem(queueItem)}}enqueueV5Footprints(footprintsRequest){if(!footprintsRequest)return;if(!footprintsRequest.apps||footprintsRequest.apps.length==0)return;if(!footprintsRequest.tests||footprintsRequest.tests.length==0)return;this.footprintsQueue.enqueueItem(footprintsRequest)}getCurrentFootprints(){this.pushCurrentFootprints();return this.footprintsQueue.getQueueContentsAndEmptyQueue()}createRequest(data){if(this.configuration.resolveWithoutHash){return this.createV5FootprintsRequest(data)}return this.createV2FootprintsRequest(data)}createV5FootprintsRequest(footprintsData){const originalRequest=footprintsData[0];if(!originalRequest){return null}if(!this.hasApps(originalRequest)||!this.hasTests(originalRequest)){return null}const request={};request.customerId=this.configuration.customerId;request.environment=this.environmentData;request.configurationData=this.configuration;request.apps=originalRequest.apps;request.tests=originalRequest.tests;request.meta=originalRequest.meta;return request}createV2FootprintsRequest(appsAndFootprintsArray){if(!appsAndFootprintsArray||!appsAndFootprintsArray.length){return null}const request={};request.customerId=this.configuration.customerId;request.items=appsAndFootprintsArray;request.environment=this.environmentData;request.configurationData=this.configuration;return request}sleep(millis){const start=(0,system_date_1.getSystemDateValueOf)();let end=null;do{end=(0,system_date_1.getSystemDateValueOf)()}while(end-start<millis)}hasApps(request){return request.apps&&request.apps.length>0}hasTests(request){return request.tests&&request.tests.length>0}}exports.FootprintsQueueSender=FootprintsQueueSender})},{"../../common/system-date":275,"./entities/footprints-item-data":194}],206:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./logger/log-factory","../../common/footprints-process-v6/location-formatter","../../common/footprints-process/collection-interval","../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConvertorV3=void 0;const log_factory_1=require("./logger/log-factory");const location_formatter_1=require("../../common/footprints-process-v6/location-formatter");const collection_interval_1=require("../../common/footprints-process/collection-interval");const system_date_1=require("../../common/system-date");class IstanbulToFootprintsConvertorV3{constructor(window,cfg){this.window=window;this.cfg=cfg;this.totalTests=0;if(!window)throw new Error("window is required");if(!cfg)throw new Error("cfg is required");this.collectionInterval=new collection_interval_1.CollectionInterval(this.cfg.interval*1e3);this.logger=log_factory_1.LogFactory.createLogger("IstanbulToFootprintsConvertor")}resetState(){this.totalTests=0;this.eidToHitsIndex={};this.uniqueIdToElement={};this.testNameToTestData={};this.fileNameToAppFile={};this.collectionInterval.next()}convert(istanbulFootprints,testName,executionId,mockTime){this.resetState();const result=this.createFootprintsFile();const app=result.apps[0];const localTime=mockTime?mockTime:(0,system_date_1.getSystemDateValueOf)();const test=this.getOrCreateTestData(testName,executionId,localTime,result);for(const moduleName in istanbulFootprints){const istanbulModule=istanbulFootprints[moduleName];if(!istanbulModule){continue}const scopeData={test:test,app:app,modulePath:istanbulModule.path.replace(/\\/g,"/"),istanbulModule:istanbulModule};if(istanbulModule.f){this.addMethodsWithHits(scopeData)}if(istanbulModule.b){this.addBranchesWithHits(scopeData)}}result.apps=this.filterAppsWithoutHits(result.apps);return result}filterAppsWithoutHits(apps){if(!apps)return apps;return apps.filter(app=>this.filterFilesWithoutHits(app))}filterFilesWithoutHits(app){let hasFiles=false;if(!app||!app.files){return hasFiles}app.files=app.files.filter(file=>this.filterElementsWithoutHits(file));hasFiles=app.files.length>0;return hasFiles}filterElementsWithoutHits(file){const hasMethodHits=this.filterElementWithoutHits(file,"methods");const hasBranchHits=this.filterElementWithoutHits(file,"branches");const hasLineHits=this.filterElementWithoutHits(file,"lines");const hasHits=hasMethodHits||hasBranchHits||hasLineHits;return hasHits}filterElementWithoutHits(file,coverageType){const fileObject=file;let arrayOfCodeElements=fileObject[coverageType]||[];arrayOfCodeElements=arrayOfCodeElements.filter(ce=>this.hasHit(ce));fileObject[coverageType]=arrayOfCodeElements;const hasHits=arrayOfCodeElements.length>0;return hasHits}hasHit(element){const hasHitInAnyTest=element.hits.some(hitToTest=>hitToTest[1]>0);return hasHitInAnyTest}addMethodsWithHits(scopeData){const istanbulModule=scopeData.istanbulModule;for(const methodId in istanbulModule.f){const hits=istanbulModule.f[methodId];if(hits>0){const methodData=istanbulModule.fnMap[methodId];this.addOrUpdateMethodElement(scopeData,methodData,hits)}}}addBranchesWithHits(scopeData){const istanbulModule=scopeData.istanbulModule;for(const branchId in istanbulModule.b){const probesArray=istanbulModule.b[branchId];for(let idx=0;idx<probesArray.length;idx++){const hits=probesArray[idx];if(hits>0){const branchData=istanbulModule.branchMap[branchId];this.addOrUpdateBranchElement(scopeData,branchData,idx,hits)}}}}addOrUpdateMethodElement(scopeData,methodData,hits){const loc=methodData.loc||methodData.lc;const decl=methodData.decl||methodData.d;this.addOrUpdateElement(scopeData,loc,hits,this.getOrCreateMethodElement,false);if(decl){this.addOrUpdateElement(scopeData,decl,hits,this.getOrCreateMethodElement,false)}}addOrUpdateBranchElement(scopeData,branchData,probeIndex,hits){const locations=branchData.locations||branchData.lcs;const probePositionData=locations[probeIndex];this.addOrUpdateElement(scopeData,probePositionData,hits,this.getOrCreateBranchElement,true,probeIndex)}addOrUpdateElement(scopeData,startPositionData,hits,getOrCreateElement,isBranch,probIndex){const file=this.getOrCreateFootprintsAppFile(scopeData.modulePath,scopeData.app);const startPosition=startPositionData.start||startPositionData.st;const uniqueId=this.createUniqueId(startPosition,scopeData.modulePath,isBranch,probIndex);if(!uniqueId){return}const element=getOrCreateElement.call(this,uniqueId,file);this.addOrUpdateElementHits(scopeData.test,uniqueId,element,hits)}createUniqueId(startPosition,fullFilePath,isBranch,probIndex){const delimiter=isBranch?"|":"@";let uniqueId=fullFilePath+delimiter+this.formatLoc(startPosition);if(probIndex!=null){uniqueId+="|"+probIndex}const mapping=this.window.slMappings[this.cfg.buildSessionId];if(mapping){uniqueId=mapping[uniqueId]||uniqueId}return uniqueId}addOrUpdateElementHits(testData,elementUniqueId,element,hits){const HITS_INDEX=1;const eid=elementUniqueId+"|"+testData.index;const index=this.eidToHitsIndex[eid];if(index!=null){const testIndexAndHits=element.hits[index];let elementHits=testIndexAndHits[HITS_INDEX];elementHits=elementHits+hits;testIndexAndHits[HITS_INDEX]=elementHits}else{const testIndexAndHits=new Array;testIndexAndHits.push(testData.index);testIndexAndHits.push(hits);const length=element.hits.push(testIndexAndHits);this.eidToHitsIndex[eid]=length-1}}getOrCreateTestData(testName,executionId,localTime,result){if(!this.testNameToTestData[testName]){const test={executionId:executionId,localTime:localTime,testName:testName,collectionInterval:this.collectionInterval.toJson()};result.tests.push(test);this.testNameToTestData[testName]={index:this.totalTests++,test:test}}return this.testNameToTestData[testName]}getOrCreateMethodElement(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){const x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;file.methods.push(x)}return this.uniqueIdToElement[uniqueId]}getOrCreateBranchElement(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){const x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;if(file.branches)file.branches.push(x)}return this.uniqueIdToElement[uniqueId]}getOrCreateFootprintsAppFile(fileName,app){if(this.fileNameToAppFile[fileName]){return this.fileNameToAppFile[fileName]}const file={methods:new Array,branches:new Array,lines:new Array,path:fileName};app.files.push(file);this.fileNameToAppFile[fileName]=file;return file}createFootprintsFile(){const result={configurationData:{},customerId:this.cfg.customerId,environment:{},tests:[],apps:[],meta:{}};this.fileNameToAppFile={};this.testNameToTestData={};const app={appName:this.cfg.appName,branchName:this.cfg.branchName,buildName:this.cfg.buildName,moduleName:"",buildSessionId:this.cfg.buildSessionId,files:new Array};result.apps.push(app);return result}formatLoc(loc){return(0,location_formatter_1.formatLocation)(loc,this.logger)}}exports.IstanbulToFootprintsConvertorV3=IstanbulToFootprintsConvertorV3})},{"../../common/footprints-process-v6/location-formatter":264,"../../common/footprints-process/collection-interval":266,"../../common/system-date":275,"./logger/log-factory":209}],207:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConverter=void 0;const utils_1=require("./utils");class IstanbulToFootprintsConverter{constructor(window,configuration){this.window=window;this.configuration=configuration;if(configuration==null)throw new Error("'configuration' cannot be null or undefined")}convert(istanbulFootprints){const apps={};const appsArray=new Array;if(istanbulFootprints){const context=this;Object.keys(istanbulFootprints).forEach(function(moduleName){const m=istanbulFootprints[moduleName];context.configuration.appName=context.configuration.appName||"";let a=apps[context.configuration.appName];let isNewApp=false;if(!a){a={appName:context.configuration.appName,build:context.configuration.buildName,branch:context.configuration.branchName,footprints:[]};isNewApp=true}const footprints=a.footprints;let filename=m.path;filename=filename.replace(/\\/g,"/");Object.keys(m.f).forEach(function(funcId){const funcInfo=m.fnMap[funcId];if(!funcInfo||funcInfo.skip)return;if(m.f[funcId]>0){const mn=context.getMethodName(funcInfo.name,funcInfo.guessedName);let pos=context.formatLoc(funcInfo.loc.originalStart||funcInfo.loc.start);if(m.inputSourceMap&&context.window["sourceMap"]){const sourceMapConsumer=new context.window["sourceMap"].SourceMapConsumer(m.inputSourceMap);pos=context.formatLoc(sourceMapConsumer.originalPositionFor(funcInfo.loc.start))}filename=funcInfo.originalFilename||filename;filename=context.getRelativeModulePath(filename);const fqmn=[mn,filename,pos].join("@");const hash=funcInfo.hash&&funcInfo.hash.hash;const footprintsItem={name:fqmn,hits:m.f[funcId],hash:hash,branches:new Array};if(m.fnToBranch&&m.fnToBranch[funcId]&&m.fnToBranch[funcId].length){m.fnToBranch[funcId].forEach(function(branchArray,index){const fileBranch=branchArray[0];const branchIndex=branchArray[1];if(m.b[fileBranch.toString()][branchIndex]>0){footprintsItem.branches.push(index)}})}footprints.push(footprintsItem)}});if(footprints.length&&isNewApp){appsArray.push(a);apps[a.appName]=a}})}return appsArray}getMethodName(name,guessedName){let mn=name||guessedName||"(Anonymous)";if(mn.indexOf("(anonymous")>=0){mn="(Anonymous)"}return mn}formatLoc(loc){return[loc.line,loc.column].join(",")}getRelativeModulePath(path){const workspacepath=utils_1.Utils.adjustPathSlashes(this.configuration.workspacepath);path=utils_1.Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path}}exports.IstanbulToFootprintsConverter=IstanbulToFootprintsConverter})},{"./utils":223}],208:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/system-date","../configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=exports.LogLevels=void 0;const system_date_1=require("../../../common/system-date");const configuration_override_1=require("../configuration-override");var LogLevels;(function(LogLevels){LogLevels["TRACE"]="trace";LogLevels["DEBUG"]="debug";LogLevels["INFO"]="info";LogLevels["WARNING"]="warning";LogLevels["ERROR"]="error";LogLevels["CRITICAL"]="critical";LogLevels["FATAL"]="fatal"})(LogLevels=exports.LogLevels||(exports.LogLevels={}));class ConsoleLogger{constructor(level=LogLevels.INFO,selectedLogLevels=null){var _a,_b;this.level=level;this.selectedLogLevels=selectedLogLevels;this.logFn=()=>{};this.stringifyFn=o=>{return""};this.context={};(_b=(_a=window.$Sealights)===null||_a===void 0?void 0:_a.configuration)===null||_b===void 0?void 0:_b.on(configuration_override_1.ConfigChangedEvents.LOG_LEVEL_CHANGED,this.initLogLevels.bind(this));if(!selectedLogLevels)this.initLogLevels(level);this.initStringifyFn();this.initLogFn()}withLogLevel(level){const c=new ConsoleLogger(this.level);c.context=this.context;return c}initLogFn(){if(console&&typeof console.log=="function"){this.logFn=o=>{const line=this.stringifyFn(o);console.log(line)}}else{}}initStringifyFn(){if(JSON&&typeof JSON.stringify=="function"){this.stringifyFn=JSON.stringify}else{this.stringifyFn=this.crudeStringifier}}crudeStringifier(o){const strParts=Array();for(const p in o){strParts.push(p+"="+o[p].toString())}return strParts.join(", ")}initLogLevels(level){const orderedLogLevels=[LogLevels.TRACE,LogLevels.DEBUG,LogLevels.INFO,LogLevels.WARNING,LogLevels.ERROR,LogLevels.CRITICAL,LogLevels.FATAL];const logLevel=level.toLowerCase();const minIdx=orderedLogLevels.indexOf(logLevel);if(minIdx===-1){this.handleLevelNotFound(level)}else{this.selectedLogLevels={};for(let i=0;i<orderedLogLevels.length;i++){this.selectedLogLevels[orderedLogLevels[i]]=i>=minIdx}}}handleLevelNotFound(logLevel){if(logLevel=="off"){this.selectedLogLevels={}}}internalLog(logLevel,logMsg,obj){if(!this.selectedLogLevels||!this.selectedLogLevels[logLevel])return;const logObject={level:logLevel.toUpperCase(),ts:(0,system_date_1.getSystemDate)().toISOString(),msg:logMsg?logMsg.toString():undefined};const ctx=this.context;for(const p in ctx){logObject[p]=ctx[p]}if(obj){if(obj instanceof Error){logObject.error=obj.toString()}else if(obj instanceof Object){for(const p in obj){logObject[p]=obj[p]}}else{logObject.data=obj}}this.logFn(logObject)}clone(){const c=new ConsoleLogger(this.level,this.selectedLogLevels);const _t=this.context;for(const p in _t){c.context[p]=_t[p]}return c}withClass(className){const c=this.clone();c.context.className=className;delete c.context.methodName;return c}withMethod(methodName){const c=this.clone();c.context.methodName=methodName;return c}withTx(tx){const c=this.clone();c.context.tx=tx;return c}withComponent(componentName,componentVersion){const c=this.clone();c.context.componentName=componentName;c.context.componentVersion=componentVersion;return c}withActivity(activityName){const c=this.clone();c.context.activityName=activityName;return c}withProperty(propName,propValue){const c=this.clone();c.context[propName]=propValue;return c}withProperties(objWithProperties,propNames){const c=this.clone();if(!propNames){propNames=Object.keys(objWithProperties)}propNames.forEach(function(pn){c.context[pn]=objWithProperties[pn]});return c}fatal(logMsg,obj){this.internalLog(LogLevels.FATAL,logMsg,obj)}critical(logMsg,obj){this.internalLog(LogLevels.CRITICAL,logMsg,obj)}error(logMsg,obj){this.internalLog(LogLevels.ERROR,logMsg,obj)}warn(logMsg,obj){this.internalLog(LogLevels.WARNING,logMsg,obj)}info(logMsg,obj){this.internalLog(LogLevels.INFO,logMsg,obj)}debug(logMsg,obj){this.internalLog(LogLevels.DEBUG,logMsg,obj)}trace(logMsg,obj){this.internalLog(LogLevels.TRACE,logMsg,obj)}}exports.ConsoleLogger=ConsoleLogger})},{"../../../common/system-date":275,"../configuration-override":188}],209:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./null-logger","./console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LogFactory=void 0;const null_logger_1=require("./null-logger");const console_logger_1=require("./console-logger");class LogFactory{static createLogger(className,logLevel){try{const logger=new console_logger_1.ConsoleLogger(logLevel);logger.withClass(className);return logger}catch(e){return null_logger_1.NullLogger.INSTANCE}}}exports.LogFactory=LogFactory})},{"./console-logger":208,"./null-logger":210}],210:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NullLogger=void 0;class NullLogger{fatal(logMsg,obj){}critical(logMsg,obj){}error(logMsg,obj){}warn(logMsg,obj){}info(logMsg,obj){}debug(logMsg,obj){}trace(logMsg,obj){}withClass(className){return NullLogger.INSTANCE}withMethod(methodName){return NullLogger.INSTANCE}withTx(tx){return NullLogger.INSTANCE}withComponent(componentName,componentVersion){return NullLogger.INSTANCE}withActivity(activityName){return NullLogger.INSTANCE}withProperty(propName,propValue){return NullLogger.INSTANCE}withProperties(objWithProperties,propNames){return NullLogger.INSTANCE}withLogLevel(level){return NullLogger.INSTANCE}}exports.NullLogger=NullLogger;NullLogger.INSTANCE=new NullLogger})},{}],211:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../entities/footprints-item-data","../delegate","../../../common/system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsItemsQueue=void 0;const footprints_item_data_1=require("../entities/footprints-item-data");const delegate_1=require("../delegate");const system_date_1=require("../../../common/system-date");class FootprintsItemsQueue{constructor(configuration){this.maxItemsInQueue=500;this.queueSize=0;this.queue=new Array;this.onQueueFull=new delegate_1.Delegate;this.isQueueFull=function(){return this.getCurrentQueueSize()>=this.maxItemsInQueue};if(!configuration)throw new Error("'configuration' cannot be null or undefined");this.enabled=configuration.enabled;this.maxItemsInQueue=configuration.maxItemsInQueue}setEnabled(isEnabled){isEnabled=!!isEnabled;if(isEnabled!==this.enabled){this.enabled=isEnabled}if(!isEnabled){this.queue=new Array}}getEnabled(){return this.enabled}enqueueItem(footprintsItem){if(!this.enabled){return}footprintsItem=footprintsItem||new footprints_item_data_1.FootprintsItemData;footprintsItem.localTime=(0,system_date_1.getSystemDateValueOf)();this.queue.push(footprintsItem);this.queueSize++;this.checkQueueSize()}checkQueueSize(){if(this.isQueueFull()){this.onQueueFull.fire()}}getCurrentQueueSize(){return this.queueSize}requeueItems(footprintsItems){if(!this.enabled){return}const context=this;footprintsItems.forEach(function(item){context.queue.push(item);context.queueSize+=1});this.checkQueueSize()}getQueueContentsAndEmptyQueue(){const returnedItems=this.queue;this.queue=new Array;this.queueSize=0;return returnedItems}}exports.FootprintsItemsQueue=FootprintsItemsQueue})},{"../../../common/system-date":275,"../delegate":190,"../entities/footprints-item-data":194}],212:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Queue=void 0;const validation_utils_1=require("../../../common/utils/validation-utils");class Queue{constructor(onQueueFull){this.queue=[];this._maxItemsInQueue=Queue.DEFAULT_MAX_ITEMS_IN_QUEUE;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(onQueueFull,"onQueueFull");this.onQueueFull=onQueueFull}requeue(items){if(!items||!items.length){return}this.queue=items.concat(this.queue)}enqueue(item){this.queue.push(item);if(this._maxItemsInQueue===this.queue.length){this.onQueueFull.fire()}}getQueueSize(){return this.queue.length}dequeue(size){if(!size){size=this.queue.length}if(this.queue.length===0){return[]}if(size>this.queue.length){size=this.queue.length}const dequeuedItems=this.queue.splice(0,size);return dequeuedItems}clear(){this.queue=[]}on(event,listener){this.onQueueFull.addListener(listener);return this}get maxItemsInQueue(){return this._maxItemsInQueue}set maxItemsInQueue(value){this._maxItemsInQueue=value}}exports.Queue=Queue;Queue.DEFAULT_MAX_ITEMS_IN_QUEUE=1e3})},{"../../../common/utils/validation-utils":280}],213:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./http-response"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;const http_response_1=require("./http-response");const REQUEST_DONE_STATE_CODE=4;class HttpClient{constructor(window,featureDetection,logger){this.window=window;this.featureDetection=featureDetection;this.logger=logger;if(window==null)throw new Error("'window' cannot be null or undefined");if(featureDetection==null)throw new Error("'featureDetection' cannot be null or undefined")}send(request,onSuccess,onError){if(!request.url)return;const url=request.url;const httpMethod=request.httpMethod;const httpRequest=new XMLHttpRequest;httpRequest.open(httpMethod,url,request.async);if(request.headers){for(let i=0;i<request.headers.length;i++){const header=request.headers[i];if(header&&header.name&&header.value){httpRequest.setRequestHeader(header.name,header.value)}}}httpRequest.onreadystatechange=function(){if(httpRequest.readyState===REQUEST_DONE_STATE_CODE){const httpResponse=new http_response_1.HttpResponse;httpResponse.statusCode=httpRequest.status;httpResponse.responseText=httpRequest.responseText;if(httpRequest.status===200){if(onSuccess){onSuccess(httpResponse)}}else{if(onError){onError(httpResponse)}}}};httpRequest.send(request.data)}}exports.HttpClient=HttpClient})},{"./http-response":215}],214:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpRequest=void 0;class HttpRequest{constructor(){this.async=true}}exports.HttpRequest=HttpRequest})},{}],215:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpResponse=void 0;class HttpResponse{}exports.HttpResponse=HttpResponse})},{}],216:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClientAdapter=void 0;const validation_utils_1=require("../../../../common/utils/validation-utils");class JsonClientAdapter{constructor(jsonClient,serverUrl,collectorUrl){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(jsonClient,"jsonClient");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(serverUrl,"serverUrl");this.jsonClient=jsonClient;this.serverUrl=serverUrl;this.collectorUrl=collectorUrl}delete(body,urlPath,callback){throw new Error("'delete' not implemented yet")}get(urlPath,callback,isNotFoundAcceptable=true,async=false){urlPath=`${this.getBaseUrl()}${urlPath}`;const onSuccess=response=>callback(null,response,response.statusCode);const onError=response=>{const error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.get(urlPath,onSuccess,onError,async)}put(requestData,urlPath,callback,async=true){throw new Error("'delete' not implemented yet")}post(requestData,urlPath,callback,async=true,contentType){urlPath=`${this.getBaseUrl()}${urlPath}`;const onSuccess=response=>callback(null,response,response.statusCode);const onError=response=>{const error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.post(urlPath,requestData,onSuccess,onError,async,contentType)}postMultipart(requestData,urlPath,callback){throw new Error("'postMultipart' not implemented yet")}updateMetadata(metadata){this.jsonClient.updateMetadata(metadata)}getBaseUrl(){if(this.collectorUrl){return this.collectorUrl}return this.serverUrl}}exports.JsonClientAdapter=JsonClientAdapter})},{"../../../../common/utils/validation-utils":280}],217:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../http/http-request","../../../../common/http/contracts","../../../../common/agent-events/agent-events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClient=void 0;const http_request_1=require("../http/http-request");const contracts_1=require("../../../../common/http/contracts");const agent_events_contracts_1=require("../../../../common/agent-events/agent-events-contracts");class JsonClient{constructor(httpClient,configuration,agentInstanceData){var _a;this.httpClient=httpClient;this.configuration=configuration;this.agentInstanceData=agentInstanceData;this.requestsInProgress=0;this.metadata={};this.requestsInProgress=0;this.updateMetadata({agentId:this.agentInstanceData.agentId,buildSessionId:(_a=this.configuration)===null||_a===void 0?void 0:_a.buildSessionId,agentType:agent_events_contracts_1.AgentTypes.BROWSER_AGENT,agentTechnology:agent_events_contracts_1.AgentTechnologies.BROWSER,labId:configuration.labId,appName:configuration.appName,branchName:configuration.branchName,buildName:configuration.buildName})}sendHttpRequest(request,onSuccess,onError,contentType){const context=this;try{this.requestsInProgress++;const httpRequest=new http_request_1.HttpRequest;httpRequest.headers=this.getHeaders(request.url,contentType,request.data);httpRequest.url=request.url;httpRequest.httpMethod=request.httpMethod;httpRequest.async=request.async;if(request.data!=null)httpRequest.data=JSON.stringify(request.data);this.httpClient.send(httpRequest,parseResponse,function(response){context.requestsInProgress--;if(onError!=null){onError(response)}})}catch(e){this.requestsInProgress--}function parseResponse(jsonResponse){try{let object;context.requestsInProgress--;if(jsonResponse&&jsonResponse.responseText&&jsonResponse.responseText!=""){object=JSON.parse(jsonResponse.responseText)}else{object=jsonResponse}if(onSuccess!=null){onSuccess(object)}}catch(e){if(onError!=null){jsonResponse.responseText="Failed parsing response. Response: '"+jsonResponse.responseText+"'";onError(jsonResponse)}}}}post(url,data,onSuccess,onError,async=true,contentType){this.send(url,data,onSuccess,onError,async,"POST",contentType)}get(url,onSuccess,onError,async=true,data){this.send(url,data,onSuccess,onError,async,"GET")}updateMetadata(metadata){this.metadata=Object.assign(Object.assign({},this.metadata),metadata)}send(url,data,onSuccess,onError,async=true,httpMethod,contentType){const request=new http_request_1.HttpRequest;request.url=url;request.data=data;request.httpMethod=httpMethod;request.async=async;this.sendHttpRequest(request,onSuccess,onError,contentType)}hasRequestsInProgress(){return this.requestsInProgress>0}createMetadataHeaders(messageType){return[{name:contracts_1.SealightsHeaderNames.LAB_ID,value:this.metadata.labId},{name:contracts_1.SealightsHeaderNames.BRANCH_NAME,value:this.metadata.branchName},{name:contracts_1.SealightsHeaderNames.BUILD_NAME,value:this.metadata.buildName},{name:contracts_1.SealightsHeaderNames.BSID,value:this.metadata.buildSessionId},{name:contracts_1.SealightsHeaderNames.EXECUTION_ID,value:this.metadata.executionId},{name:contracts_1.SealightsHeaderNames.AGENT_ID,value:this.metadata.agentId},{name:contracts_1.SealightsHeaderNames.APP_NAME,value:this.metadata.appName},{name:contracts_1.SealightsHeaderNames.MESSAGE_TYPE,value:messageType}]}getHeaders(url,contentType,requestData){var _a,_b,_c,_d;const headers=[{name:contracts_1.SealightsHeaderNames.CONTENT_TYPE,value:contentType||contracts_1.ContentType.JSON}];headers.push({name:contracts_1.SealightsHeaderNames.META_DATA,value:JSON.stringify(this.metadata)});const messageType=(_b=(_a=requestData===null||requestData===void 0?void 0:requestData.events)===null||_a===void 0?void 0:_a[0])===null||_b===void 0?void 0:_b.type;headers.push(...this.createMetadataHeaders(messageType));if((_c=this===null||this===void 0?void 0:this.configuration)===null||_c===void 0?void 0:_c.token){headers.push({name:contracts_1.SealightsHeaderNames.AUTHOTIZARTION,value:"Bearer "+((_d=this===null||this===void 0?void 0:this.configuration)===null||_d===void 0?void 0:_d.token)})}if(this.shouldAddCollectorRelatedHeaders(url)){headers.push({name:contracts_1.SealightsHeaderNames.MODE,value:contracts_1.SealightsHaderValues.LIGHT_AGENT_MODE})}return headers}shouldAddCollectorRelatedHeaders(url){const collectorUrl=this.configuration.collectorUrl;return collectorUrl&&url.indexOf(collectorUrl)==0}}exports.JsonClient=JsonClient})},{"../../../../common/agent-events/agent-events-contracts":227,"../../../../common/http/contracts":268,"../http/http-request":214}],218:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./json-client","../../logger/log-factory"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopJsonClient=void 0;const json_client_1=require("./json-client");const log_factory_1=require("../../logger/log-factory");class NoopJsonClient extends json_client_1.JsonClient{constructor(){super(...arguments);this.logger=log_factory_1.LogFactory.createLogger("NoopJsonClient")}send(url,data,onSuccess,onError,async=true,httpMethod,contentType){this.logger.info(`noop json client not executing http request for url '${url}`);onSuccess({})}}exports.NoopJsonClient=NoopJsonClient})},{"../../logger/log-factory":209,"./json-client":217}],219:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LightBackendProxy=void 0;class LightBackendProxy{constructor(configuration,jsonClient,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.logger=logger}submitRequest(request,onSuccess,onError,async=true){const url=this.createServerUrl(this.configuration);this.jsonClient.post(url,request,onSuccess,onError,async)}hasRequestsInProgress(){return this.jsonClient.hasRequestsInProgress()}getRequestsInProgressCount(){return this.jsonClient.requestsInProgress}createServerUrl(configuration){if(configuration.token){const apiVersion=configuration.resolveWithoutHash?"/v5":"/v3";return configuration.server+apiVersion+"/agents/footprints/"}return configuration.server+"/v1/testfootprints/"}}exports.LightBackendProxy=LightBackendProxy})},{}],220:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../../common/agent-events/cockpit-notifier","../../common/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlMappingLoader=void 0;const cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");const contracts_1=require("../../common/contracts");class SlMappingLoader{constructor(backendProxy,window,logger,configuration){this.backendProxy=backendProxy;this.window=window;this.logger=logger;this.configuration=configuration}loadSlMapping(buildSessionId){return __awaiter(this,void 0,void 0,function*(){this.window.slMappings=this.window.slMappings||{};if(!this.window.slMappings[buildSessionId]){try{if(this.configuration.footprintsMapping===contracts_1.FootprintsMapping.SERVER){this.loadEmptySlMapping(buildSessionId)}else{yield this.loadSlMappingFromBackend(buildSessionId)}}catch(err){const errMsg=`Error while trying to load slMapping from server '${err}'`;this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);this.window.slMappings[buildSessionId]={}}}})}loadSlMappingFromBackend(buildSessionId){return __awaiter(this,void 0,void 0,function*(){let flatted={};const slMappingArr=yield this.backendProxy.getSlMappingFromServer(buildSessionId);slMappingArr.forEach(mapping=>{flatted=Object.assign(Object.assign({},flatted),mapping)});this.window.slMappings[buildSessionId]=flatted})}loadEmptySlMapping(buildSessionId){this.window.slMappings[buildSessionId]={}}}exports.SlMappingLoader=SlMappingLoader})},{"../../common/agent-events/cockpit-notifier":234,"../../common/contracts":248}],221:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;const delegate_1=require("./delegate");const contracts_1=require("./contracts");class StateTracker{constructor(configuration,jsonClient,watchdog,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.watchdog=watchdog;this.logger=logger;this.colorChanged=new delegate_1.Delegate;this.setCurrentTestIdentifier(StateTracker.ANONYMOUS_FOOTPRINTS_COLOR);this.watchdog.addOnAlarmListener(()=>{this.checkForActiveExecution()});this.checkForActiveExecution(false);this.watchdog.start()}setCurrentTestIdentifier(newColorOnWindow){if(newColorOnWindow!=null){if(newColorOnWindow!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.stopWatchdog()}else{this.startWatchdog()}if(newColorOnWindow!=this.currentColorOnWindow){this.currentColorOnWindow=newColorOnWindow;this.colorChanged.fire()}}else if(this.currentColorOnWindow!=null&&newColorOnWindow==null){this.currentColorOnWindow=null;this.colorChanged.fire()}}getCurrentTestIdentifier(){return this.currentColorOnWindow}addOnColorChangedListener(listener){this.colorChanged.addListener(listener)}getCurrentColor(){return this.currentColorOnWindow}checkForActiveExecution(async=true){const url=this.configuration.server+`/v4/testExecution/${this.configuration.labId}`;this.logger.info(`[TO TST] - checkMappingStatus. Url '${url}'.`);const onSuccess=data=>{this.logger.info("[ACTIVE EXECUTION] Checking for active execution. No errors");if(data==null){this.logger.warn("[ACTIVE EXECUTION] Received empty response. not sending footprints.");this.hasActiveExecution=false;return}if(data.execution==null){this.logger.info("[ACTIVE EXECUTION] Couldn't find active execution. not sending footprints.");this.hasActiveExecution=false}else if(data.execution.status==contracts_1.ExecutionStatus.Ending){this.logger.info("[ACTIVE EXECUTION] Execution is pending delete. sending last footprints");this.hasActiveExecution=true}else if(data.execution.status==contracts_1.ExecutionStatus.InProgress){this.logger.info(`[ACTIVE EXECUTION] Active execution for labid '${this.configuration.labId}'`);this.hasActiveExecution=true}else{this.logger.warn(`[ACTIVE EXECUTION] Unexpected status. status: '${data.execution.status}'`);this.hasActiveExecution=false}};const onError=response=>{this.logger.error(`[ACTIVE EXECUTION] Error checking for active execution: '${response.responseText}'`);this.hasActiveExecution=false};this.jsonClient.get(url,onSuccess,onError,async)}shouldCollectFootprints(){if(this.getCurrentColor()==null){this.logger.info("Current test identifier is null, should not collect footprints");return false}if(this.getCurrentColor()!=StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.logger.info("Not in anonymous footprints, should collect footprints");return true}if(this.hasActiveExecution){this.logger.info("Has active execution, should collect footprints");return true}this.logger.info("No active execution, should not collect footprints");return false}setActiveExecution(value){this.hasActiveExecution=value}stopWatchdog(){if(this.watchdog.getStatus().running){this.watchdog.stop()}}startWatchdog(){if(!this.watchdog.getStatus().running){this.watchdog.start()}}}exports.StateTracker=StateTracker;StateTracker.ANONYMOUS_FOOTPRINTS_COLOR="00000000-0000-0000-0000-000000000000/__init"})},{"./contracts":189,"./delegate":190}],222:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TestStateHelper=void 0;class TestStateHelper{constructor(){this.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId)return"";return executionId+"/"+testName};this.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";const executionId=testId.split("/")[0];let testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId)testName="";return{executionId:executionId,testName:testName}}}}exports.TestStateHelper=TestStateHelper})},{}],223:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Utils=void 0;const path=require("path");class Utils{static adjustPathSlashes(path){path=(path||"").replace(/\\/g,"/");return path}static getRelativeModulePath(path,workspacepath){workspacepath=Utils.adjustPathSlashes(workspacepath);path=Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path}static resolveOriginalFullFileName(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}const generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename}static parseBooleanValue(value){if(value&&typeof value=="boolean"){return value}if(value&&typeof value=="string"){return value.toLowerCase()=="true"}return false}}exports.Utils=Utils})},{path:161}],224:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./delegate"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=void 0;const delegate_1=require("./delegate");class Watchdog{constructor(timeout,timersWrapper,options,logger){this.timeout=timeout;this.timersWrapper=timersWrapper;this.options=options;this.logger=logger;this.handle=null;this.alarm=new delegate_1.Delegate;this.context=this;this.stopped=false;this.options=options||{}}abortTimer(){if(this.handle){this.timersWrapper.clearTimeout(this.handle);this.handle=null}}fireAlarm(){this.handle=null;try{this.alarm.fire()}catch(e){this.logger.error("Alarm caught an exception: ",e)}if(this.options.autoReset){this.context.reset()}}addOnAlarmListener(listener){this.alarm.addListener(listener)}reset(){this.abortTimer();if(!this.stopped){this.handle=this.timersWrapper.setTimeout(()=>{this.fireAlarm()},this.timeout)}}stop(){this.stopped=true;this.abortTimer()}start(){this.stopped=false;this.reset()}getStatus(){return{running:!this.stopped}}on(event,listener){this.addOnAlarmListener(listener)}startIfNotRunning(){if(this.stopped||!this.handle){this.start()}}setInterval(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.timeout=newInterval}}exports.Watchdog=Watchdog})},{"./delegate":190}],225:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.WindowTimersWrapper=void 0;class WindowTimersWrapper{constructor(window){this.window=window;if(!this.window)throw new Error("'window' cannot be null or undefined")}clearInterval(handle){this.window.clearInterval(handle)}clearTimeout(handle){this.window.clearTimeout(handle)}setInterval(handler,timeout,...args){return this.window.setInterval(handler,timeout,args)}setTimeout(handler,timeout,...args){return this.window.setTimeout(handler,timeout,args)}}exports.WindowTimersWrapper=WindowTimersWrapper})},{}],226:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.COMMAND_ARGS=exports.COMMANDS=void 0;var COMMANDS;(function(COMMANDS){COMMANDS["CONFIG"]="config";COMMANDS["PR_CONFIG"]="prConfig";COMMANDS["BUILD"]="build";COMMANDS["SCAN"]="scan";COMMANDS["MOCHA"]="mocha";COMMANDS["JASMINE"]="jasmine";COMMANDS["MOCHA_PHANTOM_JS"]="mochaPhantomjs";COMMANDS["RUN"]="run";COMMANDS["START"]="start";COMMANDS["END"]="end";COMMANDS["UPLOAD_REPORTS"]="uploadReports";COMMANDS["EXTERNAL_REPORT"]="externalReport";COMMANDS["NYC_REPORT"]="nycReport";COMMANDS["INSTALL_BABEL"]="installBabel";COMMANDS["COMPONENT_UPDATE"]="componentUpdate";COMMANDS["COMPONENT_DELETE"]="componentDelete";COMMANDS["BUILD_END"]="buildend";COMMANDS["SCANNED"]="scanned";COMMANDS["DRY_RUN"]="dryRun"})(COMMANDS=exports.COMMANDS||(exports.COMMANDS={}));var COMMAND_ARGS;(function(COMMAND_ARGS){COMMAND_ARGS["USE_OTEL"]="useOtel";COMMAND_ARGS["ENABLE_OPEN_TELEMETRY"]="enableOpenTelemetry";COMMAND_ARGS["INSTRUMENT_FOR_BROWSERS"]="instrumentForBrowsers"})(COMMAND_ARGS=exports.COMMAND_ARGS||(exports.COMMAND_ARGS={}))})},{}],227:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentTechnologies=exports.AgentEventCode=exports.AgentTypes=void 0;var AgentTypes;(function(AgentTypes){AgentTypes["BUILD_SCANNER"]="BuildScanner";AgentTypes["TEST_LISTENER"]="TestListener";AgentTypes["BROWSER_AGENT"]="BrowserAgent";AgentTypes["SLNODEJS"]="slnodejs"})(AgentTypes=exports.AgentTypes||(exports.AgentTypes={}));var AgentEventCode;(function(AgentEventCode){AgentEventCode[AgentEventCode["GENERIC_AGENT_EVENT"]=1e3]="GENERIC_AGENT_EVENT";AgentEventCode[AgentEventCode["AGENT_STARTED"]=1001]="AGENT_STARTED";AgentEventCode[AgentEventCode["AGENT_SHUTDOWN"]=1002]="AGENT_SHUTDOWN";AgentEventCode[AgentEventCode["AGENT_PING"]=1003]="AGENT_PING";AgentEventCode[AgentEventCode["AGENT_CONFIG_CHANGED"]=1004]="AGENT_CONFIG_CHANGED";AgentEventCode[AgentEventCode["FIRST_COVERAGE_INSTRUMENTATION_PERFORMED"]=1005]="FIRST_COVERAGE_INSTRUMENTATION_PERFORMED";AgentEventCode[AgentEventCode["FIRST_TIME_HAS_EXECUTION"]=1006]="FIRST_TIME_HAS_EXECUTION";AgentEventCode[AgentEventCode["FIRST_TIME_NO_EXECUTION"]=1007]="FIRST_TIME_NO_EXECUTION";AgentEventCode[AgentEventCode["AGENT_MUTED"]=1008]="AGENT_MUTED";AgentEventCode[AgentEventCode["AGENT_UNMUTED"]=1009]="AGENT_UNMUTED";AgentEventCode[AgentEventCode["FIRST_TIME_COLLECTED_FP"]=1010]="FIRST_TIME_COLLECTED_FP";AgentEventCode[AgentEventCode["CONTEXT_PROPAGATION_TELEMETRY"]=1019]="CONTEXT_PROPAGATION_TELEMETRY";AgentEventCode[AgentEventCode["GENERIC_MESSAGE"]=2e3]="GENERIC_MESSAGE";AgentEventCode[AgentEventCode["GENERIC_MESSAGE_SUPERUSER"]=2999]="GENERIC_MESSAGE_SUPERUSER";AgentEventCode[AgentEventCode["WARN"]=3e3]="WARN";AgentEventCode[AgentEventCode["AGENT_DID_NOT_SHUTDOWN"]=3001]="AGENT_DID_NOT_SHUTDOWN";AgentEventCode[AgentEventCode["GENERIC_WARNING_SUPERUSER"]=3999]="GENERIC_WARNING_SUPERUSER";AgentEventCode[AgentEventCode["GIT_SUBMODULES_DETECTED"]=3501]="GIT_SUBMODULES_DETECTED";AgentEventCode[AgentEventCode["GENERIC_ERROR"]=4e3]="GENERIC_ERROR";AgentEventCode[AgentEventCode["DUPLICATE_MODULE"]=4001]="DUPLICATE_MODULE";AgentEventCode[AgentEventCode["DATA_PROCESSOR_NO_EXECUTIONS"]=4002]="DATA_PROCESSOR_NO_EXECUTIONS";AgentEventCode[AgentEventCode["DATA_PROCESSOR_INVALID_FORMAT"]=4003]="DATA_PROCESSOR_INVALID_FORMAT";AgentEventCode[AgentEventCode["DATA_PROCESSOR_EMPTY_DATA"]=4004]="DATA_PROCESSOR_EMPTY_DATA";AgentEventCode[AgentEventCode["BUILD_MAP_SUBMISSION_ERROR"]=4005]="BUILD_MAP_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_SUBMISSION_ERROR"]=4006]="FOOTPRINTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["TEST_EVENTS_SUBMISSION_ERROR"]=4007]="TEST_EVENTS_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR"]=4008]="EXTERNAL_DATA_PROCESSOR_SUBMISSION_ERROR";AgentEventCode[AgentEventCode["UNSUPPORTED_OS"]=4009]="UNSUPPORTED_OS";AgentEventCode[AgentEventCode["UNSUPPORTED_RUNTIME"]=4010]="UNSUPPORTED_RUNTIME";AgentEventCode[AgentEventCode["THIRD_PARTY_PACKAGE_DETECTED"]=4011]="THIRD_PARTY_PACKAGE_DETECTED";AgentEventCode[AgentEventCode["THIRD_PARTY_FILE_DETECTED"]=4012]="THIRD_PARTY_FILE_DETECTED";AgentEventCode[AgentEventCode["OTEL_ERROR"]=4013]="OTEL_ERROR";AgentEventCode[AgentEventCode["STATIC_INSTRUMENTATION_ERROR"]=4021]="STATIC_INSTRUMENTATION_ERROR";AgentEventCode[AgentEventCode["FOOTPRINTS_LOSS"]=4999]="FOOTPRINTS_LOSS";AgentEventCode[AgentEventCode["LEAST_VERBOSE_LOG"]=5001]="LEAST_VERBOSE_LOG";AgentEventCode[AgentEventCode["MOST_VERBOSE_LOG"]=5999]="MOST_VERBOSE_LOG"})(AgentEventCode=exports.AgentEventCode||(exports.AgentEventCode={}));var AgentTechnologies;(function(AgentTechnologies){AgentTechnologies["NODEJS"]="nodejs";AgentTechnologies["BROWSER"]="browser"})(AgentTechnologies=exports.AgentTechnologies||(exports.AgentTechnologies={}))})},{}],228:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-contracts","./agent-instance-info-builder","./machine-info-builder","./nodejs-env-info-builder","./agent-start-info-builder","./ci-info-builder","../utils/validation-utils","../watchdog","../system-date","./browser-info-builder","../utils/data-cleansing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsController=void 0;const agent_events_contracts_1=require("./agent-events-contracts");const agent_instance_info_builder_1=require("./agent-instance-info-builder");const machine_info_builder_1=require("./machine-info-builder");const nodejs_env_info_builder_1=require("./nodejs-env-info-builder");const agent_start_info_builder_1=require("./agent-start-info-builder");const ci_info_builder_1=require("./ci-info-builder");const validation_utils_1=require("../utils/validation-utils");const watchdog_1=require("../watchdog");const system_date_1=require("../system-date");const browser_info_builder_1=require("./browser-info-builder");const data_cleansing_utils_1=require("../utils/data-cleansing-utils");class AgentEventsController{constructor(agentConfig,agentInstanceData,logger,backendProxy,tool,tags,colorContextManager){this.colorContextManager=colorContextManager;this.active=false;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentConfig,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");this._agentConfig=agentConfig;this._logger=logger;this._agentInstanceData=agentInstanceData;this.shutDownRetries=0;this._backendProxy=backendProxy;this.addTags(tags);this.addTool(tool);this.initWatchdog();this.submittedEventsMap=new Map}submitAgentStartedEvent(packageJsonFile){return __awaiter(this,void 0,void 0,function*(){this.active=true;this.startRequestStatus=StartRequestStatus.PENDING;const event=this.buildAgentStartEvent(packageJsonFile||{});const result=yield this.submitAgentEventRequest(event);this.startRequestStatus=result?StartRequestStatus.SUCCEED:StartRequestStatus.FAILED;if(this.startRequestStatus!==StartRequestStatus.SUCCEED){this._logger.info("Agent start event failed to submit - ping events will not be sent")}else{this._pingWatchdog.start()}})}addColorToEvent(event){var _a;const colorName=(_a=this.colorContextManager)===null||_a===void 0?void 0:_a.getTestName();return Array.isArray(event)?event.forEach(eventObject=>eventObject.colorName=colorName):event.colorName=colorName}submitAgentEventRequest(event){return __awaiter(this,void 0,void 0,function*(){if(!this.active){this._logger.debug("Agent not active - not submitting event");return false}const request={agentId:this._agentInstanceData.agentId,events:Array.isArray(event)?event:[event],appName:this._agentConfig.appName.value,buildSessionId:this._agentConfig.buildSessionId.value};try{yield this._backendProxy.submitAgentEvent(request);this._logger.info(`Submitted '${request.events.length}' events successfully`);return true}catch(e){this._logger.warn(`Failed to submit '${request.events.length}' events. Error ${e}`);return false}})}buildAgentStartEvent(packageJsonFile){const agentInstanceInfoBuilder=new agent_instance_info_builder_1.AgentInstanceInfoBuilder(this);const machineInfoBuilder=new machine_info_builder_1.MachineInfoBuilder;const dependencies=Object.assign(Object.assign({},packageJsonFile.dependencies),packageJsonFile.devDependencies);const nodejsEnvInfoBuilder=this.agentInstanceData.technology===agent_events_contracts_1.AgentTechnologies.BROWSER?new browser_info_builder_1.BrowserInfoBuilder:new nodejs_env_info_builder_1.NodejsEnvInfoBuilder(this.agentInstanceData,dependencies);const ciInfoBuilder=new ci_info_builder_1.CiInfoBuilder;const agentStartInfoBuilder=new agent_start_info_builder_1.AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,nodejsEnvInfoBuilder,ciInfoBuilder,this._agentConfig);const agentStartInfo=agentStartInfoBuilder.build();return this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_STARTED,agentStartInfo)}buildAgentShutdownEvent(){return this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_SHUTDOWN)}submitAgentShutdownEvent(){return __awaiter(this,void 0,void 0,function*(){this.shutDownRetries++;if(this.startRequestStatus==StartRequestStatus.FAILED){this._logger.debug("Agent start not submitted - not sending shut down events");return}if(this.shutDownRetries>AgentEventsController.MAX_SHUTDOWN_RETRIES){this._logger.debug("Stop trying to send shutdown event after 60 seconds ");return}this._pingWatchdog.stop();const event=this.buildAgentShutdownEvent();if(this.startRequestStatus==StartRequestStatus.PENDING){setTimeout(()=>this.submitAgentShutdownEvent.call(this),1e3)}else{const result=yield this.submitAgentEventRequest(event);this.active=false;return result}})}submitPingEvent(){return this.submitEvent(agent_events_contracts_1.AgentEventCode.AGENT_PING,{agentInfo:{labId:this.agentConfig.labId.value}})}submitEvent(code,data){this.submittedEventsMap.set(code,true);this._logger.debug(`About to send event with code '${code}', current time: ${(0,system_date_1.getSystemDateValueOf)()}`);const event=this.buildEvent(code,data);this.submitAgentEventRequest(event).then(()=>this._logger.debug(`Event with code '${code}' submitted successfully`))}submitEventOnce(code){if(!this.submittedEventsMap.get(code)){this.submitEvent(code)}}submitGenericMessage(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.GENERIC_MESSAGE)}submitWarning(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.WARN)}submitError(message){this.sendMessage(message,agent_events_contracts_1.AgentEventCode.GENERIC_ERROR)}submitErrorsBatch(messages){if(!messages||!messages.length){return}const events=messages.map(msg=>this.buildEvent(agent_events_contracts_1.AgentEventCode.GENERIC_ERROR,msg));this.submitAgentEventRequest(events).then(()=>this.logger.debug(`'${events.length}' events were submitted successfully`))}sendMessage(message,code){this.logger.debug(`About to send message '${message}' with code '${code}', current time: ${(0,system_date_1.getSystemDateValueOf)()}`);const messageEvent=this.buildEvent(code,message);this.submitAgentEventRequest(messageEvent).then(()=>this.logger.debug("Message submitted successfully"))}submitConfigChanged(){const messageEvent=this.buildEvent(agent_events_contracts_1.AgentEventCode.AGENT_CONFIG_CHANGED,this._agentConfig.toJsonObject());this.submitAgentEventRequest(messageEvent).then(()=>this.logger.debug("Config changed event submitted successfully"))}get watchdog(){return this._pingWatchdog}get agentConfig(){return this._agentConfig}get logger(){return this._logger}get tools(){return this._tools}resolveTags(){return this._tags||[]}addTags(tags){if(!tags)return;this._tags=[...this._tags||[],...tags||[]]}addTool(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)}initWatchdog(){const watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};const timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))}getTimers(){if(this._agentInstanceData.technology===agent_events_contracts_1.AgentTechnologies.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}}buildEvent(type,data){var _a;const cleanData=this._agentConfig.removeSensitiveData.value?data_cleansing_utils_1.DataCleansingUtils.removeSensitiveData(data):data;return{type:type,utcTimestamp_ms:(0,system_date_1.getSystemDateValueOf)(),data:cleanData,colorName:(_a=this.colorContextManager)===null||_a===void 0?void 0:_a.getTestName()}}get agentInstanceData(){return this._agentInstanceData}}exports.AgentEventsController=AgentEventsController;AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../system-date":275,"../utils/data-cleansing-utils":276,"../utils/validation-utils":280,"../watchdog":281,"./agent-events-contracts":227,"./agent-instance-info-builder":230,"./agent-start-info-builder":231,"./browser-info-builder":232,"./ci-info-builder":233,"./machine-info-builder":236,"./nodejs-env-info-builder":238}],229:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date","./cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsGuard=void 0;const system_date_1=require("../system-date");const cockpit_notifier_1=require("./cockpit-notifier");class AgentEventsGuard{static notifyIfNeeded(eventCode,data){const currentTime=(0,system_date_1.getSystemDateValueOf)();const lastCallTime=AgentEventsGuard.EVENT_CODE_TO_LAST_CALL.get(eventCode);if(!lastCallTime||currentTime-lastCallTime>=AgentEventsGuard.DEFAULT_FIVE_MIN_BUFFER){cockpit_notifier_1.CockpitNotifier.sendEvent(eventCode,data);AgentEventsGuard.EVENT_CODE_TO_LAST_CALL.set(eventCode,currentTime)}}static init(){AgentEventsGuard.EVENT_CODE_TO_LAST_CALL=new Map}}exports.AgentEventsGuard=AgentEventsGuard;AgentEventsGuard.DEFAULT_FIVE_MIN_BUFFER=5*60*1e3;AgentEventsGuard.EVENT_CODE_TO_LAST_CALL=new Map})},{"../system-date":275,"./cockpit-notifier":234}],230:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./sensitive-data-filter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceInfoBuilder=void 0;const sensitive_data_filter_1=require("./sensitive-data-filter");const SEALIGHTS_ENV_VAR_PREFIX="SL_";const CI_ENV_VARS=new Set(["build_number","build_id","build_url","node_name","job_name","build_tag","jenkins_url","workspace","git_commit","git_url","git_branch","circle_branch","circle_build_num","circle_build_url","circle_job","circle_node_index","circle_node_total","circle_pr_number","circle_pr_reponame","circle_previous_build_num","circle_project_reponame","circle_pull_request","circle_repository_url","circle_sha1","circle_tag","circle_workflow_id","circle_workflow_job_id","circle_workflow_workspace_id","circle_working_directory","teamcity_version","teamcity_project_name","teamcity_buildconf_name","build_is_personal","ci_builds_dir","ci_commit_author","ci_commit_before_sha","ci_commit_branch","ci_commit_description","ci_commit_message","ci_commit_ref_name","ci_commit_ref_slug","ci_commit_sha","ci_commit_short_sha","ci_commit_tag","ci_commit_timestamp","ci_commit_title","ci_concurrent_id","ci_concurrent_project_id","ci_config_path","ci_default_branch","ci_dependency_proxy_server","ci_disposable_environment","ci_environment_name","ci_environment_slug","ci_environment_url","ci_environment_action","ci_environment_tier","ci_job_id","ci_job_image","ci_job_name","ci_job_stage","ci_job_url","ci_job_started_at","ci_kubernetes_active","ci_node_index","ci_node_total","ci_pipeline_url","ci_project_dir","ci_project_name","ci_project_namespace","ci_project_path_slug","ci_project_path","ci_project_repository_languages","ci_project_root_namespace","ci_project_title","ci_project_description","ci_project_url","ci_registry_image","ci_repository_url","ci_server_host","ci_server_name","ci_server_url","ci_server_version_major","ci_server_version_minor","ci_server_version_patch","ci_server_version","gitlab_ci","ci_merge_request_approved","ci_merge_request_assignees","ci_merge_request_id","ci_merge_request_iid","ci_merge_request_labels","ci_merge_request_milestone","ci_merge_request_project_id","ci_merge_request_project_path","ci_merge_request_project_url","ci_merge_request_ref_path","ci_merge_request_source_branch_name","ci_merge_request_source_branch_sha","ci_merge_request_source_project_id","ci_merge_request_source_project_path","ci_merge_request_source_project_url","ci_merge_request_target_branch_name","ci_merge_request_target_branch_sha","ci_merge_request_title","ci_merge_request_event_type","ci_merge_request_diff_id","ci_merge_request_diff_base_sha","ci_external_pull_request_iid","ci_external_pull_request_source_repository","ci_external_pull_request_target_repository","ci_external_pull_request_source_branch_name","ci_external_pull_request_source_branch_sha","ci_external_pull_request_target_branch_name","ci_external_pull_request_target_branch_sha","github_action","github_action_path","github_action_repository","github_base_ref","github_env","github_head_ref","github_job","github_path","github_ref","github_ref_name","github_ref_type","github_repository","github_repository_owner","github_sha","github_step_summary","github_workflow","github_workspace","runner_arch","runner_name","runner_os","runner_temp","runner_tool_cache"]);class AgentInstanceInfoBuilder{constructor(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.tags=agentEventsController.resolveTags();this.tools=agentEventsController.tools;this.logger=agentEventsController.logger;this.technology=agentEventsController.agentInstanceData.technology;this.info={agentId:agentEventsController.agentInstanceData.agentId,agentType:agentEventsController.agentInstanceData.agentType,agentVersion:agentEventsController.agentInstanceData.agentVersion,technology:agentEventsController.agentInstanceData.technology}}fillData(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()}build(){this.fillData();return this.info}fillFromAgentConfig(){this.info.buildSessionId=this.agentConfig.buildSessionId.value;this.info.labId=this.agentConfig.labId.value||this.agentConfig.buildSessionId.value;this.info.testStage=this.agentConfig.testStage.value;this.info.agentConfig=this.agentConfig.toJsonObject()}fillFromProcessObject(){this.info.processId=process.pid;this.info.processArch=process.arch;this.info.argv=process.argv;this.info.cwd=process.cwd();this.info.envVars=this.extractSealightsEnvVars()}extractSealightsEnvVars(){const slEnvVars={};Object.keys(process.env).forEach(key=>{if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0||key==="NODE_OPTIONS"||key==="PATH"||CI_ENV_VARS.has(key.toLowerCase())){slEnvVars[key]=(0,sensitive_data_filter_1.isSensitive)(key,process.env[key],this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars}}exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder;AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********"})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":239,_process:162}],231:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/data-cleansing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentStartInfoBuilder=void 0;const data_cleansing_utils_1=require("../utils/data-cleansing-utils");class AgentStartInfoBuilder{constructor(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder,agentConfig){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder;this.agentConfig=agentConfig;this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}fillData(){}build(){const response={agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()};if(this.agentConfig.removeSensitiveData.value)return data_cleansing_utils_1.DataCleansingUtils.removeSensitiveData(response);return response}}exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{"../utils/data-cleansing-utils":276}],232:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BrowserInfoBuilder=void 0;const system_date_1=require("../system-date");class BrowserInfoBuilder{constructor(){this.info={}}fillData(){const currentDate=(0,system_date_1.getSystemDate)();this.info.userAgent=window.navigator.userAgent;this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.location=window.location.toString()}build(){this.fillData();return this.info}}exports.BrowserInfoBuilder=BrowserInfoBuilder})},{"../system-date":275}],233:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CiInfoBuilder=void 0;const JENKINS_JOB_NAME_ENV="JOB_NAME";const JENKINS_JOB_ID_ENV="BUILD_ID";const JENKINS_JOB_URL_ENV="BUILD_URL";class CiInfoBuilder{constructor(){this.info={}}fillData(){if(this.isJenkins()){this.info.jobId=process.env[JENKINS_JOB_ID_ENV];this.info.jobName=process.env[JENKINS_JOB_NAME_ENV];this.info.jobUrl=process.env[JENKINS_JOB_URL_ENV]}}isJenkins(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]}build(){this.fillData();return this.info}}exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:162}],234:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller","./dry-run-agent-events-controller","./no-op-agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;const agent_events_controller_1=require("./agent-events-controller");const dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");const no_op_agent_events_controller_1=require("./no-op-agent-events-controller");class CockpitNotifier{static notifyStart(agentConfig,agentInstanceData,logger,backendProxy,packageJsonFile,tool,tags,colorContextManager){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags,colorContextManager);yield CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)})}static notifyStartNoOp(agentConfig,agentInstanceData,logger,backendProxy,packageJsonFile,tool,tags){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.controller=new no_op_agent_events_controller_1.NoOpAgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags)})}static notifyShutdown(){return __awaiter(this,void 0,void 0,function*(){CockpitNotifier.verifyControllerInitialized();yield CockpitNotifier.controller.submitAgentShutdownEvent()})}static sendGenericMessage(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)}static sendWarning(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)}static sendError(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)}static sendErrorsBatch(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)}static sendEvent(code,data){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code,data)}static sendEventOnce(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)}static verifyControllerInitialized(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}}static reset(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false}static setDryRunMode(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)}}exports.CockpitNotifier=CockpitNotifier;CockpitNotifier.controllerNullLogged=false})},{"./agent-events-controller":228,"./dry-run-agent-events-controller":235,"./no-op-agent-events-controller":237}],235:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-contracts","./agent-events-controller","../config-process/config","../agent-instance-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DryRunAgentEventsController=void 0;const agent_events_contracts_1=require("./agent-events-contracts");const agent_events_controller_1=require("./agent-events-controller");const config_1=require("../config-process/config");const agent_instance_data_1=require("../agent-instance-data");class DryRunAgentEventsController extends agent_events_controller_1.AgentEventsController{constructor(logger,proxy){super(new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_contracts_1.AgentTypes.SLNODEJS,agent_events_contracts_1.AgentTechnologies.NODEJS),logger,proxy,null)}submitAgentStartedEvent(packageJsonFile){return Promise.resolve(undefined)}}exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":240,"../config-process/config":243,"./agent-events-contracts":227,"./agent-events-controller":228}],236:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","os","../system-date","../footprints-process-v6/buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;const os=require("os");const system_date_1=require("../system-date");const buffer_size_helper_1=require("../footprints-process-v6/buffer-size-helper");class MachineInfoBuilder{constructor(){this.info={}}fillData(){const currentDate=(0,system_date_1.getSystemDate)();this.info.machineName=os.hostname();const cpus=os.cpus();this.info.cpu=cpus.map(cpu=>`${cpu.model} (${cpu.speed} MHz`).join(", ");this.info.totalMemory=`${os.totalmem()/buffer_size_helper_1.BufferSizeHelper.BYTES_IN_GB} Gb`;this.info.arch=os.arch();this.info.os=os.platform();this.info.localDateTime=currentDate.toString();this.info.localDateTimeUnix_s=currentDate.getTime();this.info.runtime=process.version;this.info.ipAddress=this.extractIpAddresses()}build(){this.fillData();return this.info}extractIpAddresses(){let ipAddresses=[];const interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(key=>{const addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(addressObject=>addressObject.address))});return ipAddresses}}exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../footprints-process-v6/buffer-size-helper":257,"../system-date":275,_process:162,os:160}],237:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./agent-events-controller"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoOpAgentEventsController=void 0;const agent_events_controller_1=require("./agent-events-controller");class NoOpAgentEventsController extends agent_events_controller_1.AgentEventsController{submitAgentStartedEvent(packageJsonFile){return __awaiter(this,void 0,void 0,function*(){})}submitAgentEventRequest(event){return __awaiter(this,void 0,void 0,function*(){return true})}sendMessage(message,code){}submitAgentShutdownEvent(){return __awaiter(this,void 0,void 0,function*(){return null})}submitPingEvent(){}submitEvent(code,data){}submitEventOnce(code){}submitGenericMessage(message){}submitWarning(message){}submitError(message){}submitErrorsBatch(messages){}}exports.NoOpAgentEventsController=NoOpAgentEventsController})},{"./agent-events-controller":228}],238:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NodejsEnvInfoBuilder=void 0;class NodejsEnvInfoBuilder{constructor(agentInstanceData,dependencies){this.agentInstanceData=agentInstanceData;this.info={};this.dependencies=dependencies||{}}fillData(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node;this.info.execArgv=process.execArgv;this.info.allocatedMemoryInMB=this.agentInstanceData.AgentAllocatedMemoryInMb}build(){this.fillData();return this.info}}exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:162}],239:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isSensitive=void 0;const secretKeysRegexes={"Slack Token":"(xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})","RSA private key":"-----BEGIN RSA PRIVATE KEY-----","SSH (DSA) private key":"-----BEGIN DSA PRIVATE KEY-----","SSH (EC) private key":"-----BEGIN EC PRIVATE KEY-----","PGP private key block":"-----BEGIN PGP PRIVATE KEY BLOCK-----","Amazon AWS Access Key ID":"AKIA[0-9A-Z]{16}","Amazon MWS Auth Token":"amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}","AWS API Key":"AKIA[0-9A-Z]{16}","Facebook Access Token":"EAACEdEose0cBA[0-9A-Za-z]+","Facebook OAuth":"[f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|\"][0-9a-f]{32}['|\"]",GitHub:"[g|G][i|I][t|T][h|H][u|U][b|B].*['|\"][0-9a-zA-Z]{35,40}['|\"]","Generic API Key":"[a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Generic Secret":"[s|S][e|E][c|C][r|R][e|E][t|T].*['|\"][0-9a-zA-Z]{32,45}['|\"]","Google API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Cloud Platform OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google Drive API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Drive OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google (GCP) Service-account":'"type": "service_account"',"Google Gmail API Key":"AIza[0-9A-Za-z\\-_]{35}","Google Gmail OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Google OAuth Access Token":"ya29\\.[0-9A-Za-z\\-_]+","Google YouTube API Key":"AIza[0-9A-Za-z\\-_]{35}","Google YouTube OAuth":"[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com","Heroku API Key":"[h|H][e|E][r|R][o|O][k|K][u|U].*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}","MailChimp API Key":"[0-9a-f]{32}-us[0-9]{1,2}","Mailgun API Key":"key-[0-9a-zA-Z]{32}","Password in URL":"[a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}[\"'\\s]","PayPal Braintree Access Token":"access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}","Picatic API Key":"sk_live_[0-9a-z]{32}","Slack Webhook":"https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}","Stripe API Key":"sk_live_[0-9a-zA-Z]{24}","Stripe Restricted API Key":"rk_live_[0-9a-zA-Z]{24}","Square Access Token":"sq0atp-[0-9A-Za-z\\-_]{22}","Square OAuth Secret":"sq0csp-[0-9A-Za-z\\-_]{43}","Twilio API Key":"SK[0-9a-fA-F]{32}","Twitter Access Token":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40}","Twitter OAuth":"[t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|\"][0-9a-zA-Z]{35,44}['|\"]"};function isSensitive(envVar,value,logger){for(const[key,regex]of Object.entries(secretKeysRegexes)){if(new RegExp(regex).test(value)){logger.debug(`Value for key ${envVar} filtered out since it suspected to contains data fpr ${key}`);return true}}return false}exports.isSensitive=isSensitive})},{}],240:[function(require,module,exports){(function(__dirname){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","uuid","./agent-events/agent-events-contracts","./utils/files-utils","fs","./agent-events/agent-instance-info-builder"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentInstanceData=void 0;const uuid=require("uuid");const agent_events_contracts_1=require("./agent-events/agent-events-contracts");const files_utils_1=require("./utils/files-utils");const fs_1=require("fs");const agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");class AgentInstanceData{constructor(agentType,technology,buildSessionId){this.agentType=agentType;this.technology=technology;this.buildSessionId=buildSessionId;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}resolveAgentVersion(){if(this.technology===agent_events_contracts_1.AgentTechnologies.BROWSER){return this.resolveAgentVersionForBrowserAgent()}const packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{const packageJson=(0,fs_1.readFileSync)(packageJsonFilePath).toString();const parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn(`Failed to resolve agent version, Error: '${e}`);return null}}return null}resolveAgentVersionForBrowserAgent(){const windowVar=typeof window!=="undefined"?window:null;return windowVar&&windowVar[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT]&&windowVar[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT].agentVersion||agent_instance_info_builder_1.AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION}set AgentAllocatedMemoryInMb(memory){this.agentAllocatedMemoryInMb=memory}get AgentAllocatedMemoryInMb(){return this.agentAllocatedMemoryInMb}}exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-contracts":227,"./agent-events/agent-instance-info-builder":230,"./utils/files-utils":278,fs:157,uuid:285}],241:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system","./config","../constants/sl-env-vars","fs","jwt-decode","../../cli-parse/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;const config_system_1=require("./config-system");const config_1=require("./config");const sl_env_vars_1=require("../constants/sl-env-vars");const fs=require("fs");const jwtDecode=require("jwt-decode");const contracts_1=require("../../cli-parse/contracts");class ConfigLoader{constructor(logger){this.logger=logger}loadAgentConfiguration(initialJsonConfig){const agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{const jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error(`Error parsing agent configuration ${e}`)}}agentCfg.loadConfiguration(new config_system_1.EnvVariableConfigurationProvider("SL_"));if(initialJsonConfig){agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(initialJsonConfig))}if(!agentCfg.token.hasValue&&agentCfg.tokenFile.hasValue){try{agentCfg.token.value=fs.readFileSync(agentCfg.tokenFile.value).toString()}catch(err){}}if(agentCfg.token.hasValue){this.loadConfigFromToken(agentCfg,agentCfg.token.value)}this.resolveUsingOtel(agentCfg,initialJsonConfig);this.printConfiguration(agentCfg);return agentCfg}printConfiguration(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())}resolveUsingOtel(agentCfg,initialJsonConfig){agentCfg.useOtel.value=sl_env_vars_1.SlEnvVars.shouldUseOtel()||(initialJsonConfig===null||initialJsonConfig===void 0?void 0:initialJsonConfig[contracts_1.COMMAND_ARGS.ENABLE_OPEN_TELEMETRY])}loadConfigFromToken(agentCfg,token){if(!token)return null;try{const tokenData=jwtDecode(token);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}let customerId=tokenData["subject"];const subjectParts=tokenData["subject"].split("@");if(subjectParts.length>=1){customerId=subjectParts[0]}if(!agentCfg.server.hasValue){agentCfg.server.value=tokenData["x-sl-server"]}agentCfg.customerId.value=customerId}catch(err){}}}exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"../../cli-parse/contracts":226,"../constants/sl-env-vars":247,"./config":243,"./config-system":242,_process:162,fs:157,"jwt-decode":284}],242:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseConfiguration=exports.BooleanConfigKey=exports.NumberConfigKey=exports.StringConfigKey=exports.AgentConfigKey=exports.JsonConfigFileConfigurationProvider=exports.ConfigProviderAggregator=exports.EnvVariableConfigurationProvider=exports.JsonObjectConfigurationProvider=void 0;const fs=require("fs");class JsonObjectConfigurationProvider{constructor(configObject){this.configObject=configObject;this.configObject=configObject||{}}getAllKeyValues(callback){return callback(null,this.configObject)}getName(){return"JSON Object"}}exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;class EnvVariableConfigurationProvider{constructor(prefix){this.prefix=prefix}getAllKeyValues(callback){if(this.prefix){const ret={};ret["httpMaxAttempts"]=process.env["SL_HttpMaxAttempts"];ret["httpAttemptInterval"]=process.env["SL_HttpAttemptInterval"];for(const key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substring(this.prefix.length)]=process.env[key]}}return callback(null,ret)}else{return callback(null,process.env)}}getName(){return"Environment Variables"}}exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;class ConfigProviderAggregator{constructor(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}getAllKeyValues(callback){const flattenedConfiguration={};const remainingProviders=[].concat(this.providers);const attemptNext=()=>{if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}const nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues((err,keysAndValues)=>{if(err)return attemptNext();Object.keys(keysAndValues).forEach(k=>{if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()}getName(){return"Aggregated config from multiple providers: "+this.providers.map(t=>t.getName())}}exports.ConfigProviderAggregator=ConfigProviderAggregator;class JsonConfigFileConfigurationProvider{constructor(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}getAllKeyValues(callback){try{const cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}}getName(){return"Config filename: "+this.filename}}exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;class AgentConfigKey{}exports.AgentConfigKey=AgentConfigKey;class StringConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){this.value=s;this.hasValue=true}}exports.StringConfigKey=StringConfigKey;class NumberConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){const parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true}}exports.NumberConfigKey=NumberConfigKey;class BooleanConfigKey{constructor(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}get value(){return this._value}set value(value){this._value=value;this.hasValue=true}loadFromRawData(s){if(s==null)s="";if(typeof s==="boolean")s=String(s);s=s.toLowerCase();switch(s){case"true":this.value=true;this.hasValue=true;return;case"false":this.value=false;this.hasValue=true;return;case"undefined":this.value=false;this.hasValue=false;return;default:throw new Error("Invalid boolean value: "+s)}}}exports.BooleanConfigKey=BooleanConfigKey;class BaseConfiguration{loadConfigurationFromMultipleProviders(configProviders,callback){const provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)}loadConfiguration(configProvider,callback,dbg){try{configProvider.getAllKeyValues((err,keysAndValues)=>{if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};const knownKeys=Object.keys(this);let hadError=false;let keyWithError="";knownKeys.forEach(keyName=>{if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}const cfgKey=this[keyName];if(!cfgKey.isConfigKey)return;const rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){const msg="Required configuration is missing: "+keyName+", provider:"+configProvider.getName();hadError=true;if(callback){callback(new Error(msg))}}if(rawValue==undefined)return;try{cfgKey.loadFromRawData(rawValue)}catch(e){const msg="Invalid configuration for key="+keyName+", value="+rawValue+ +", provider="+configProvider.getName()+": "+e.toString();console.log("[Sealights Test Listener] - "+msg);hadError=true;keyWithError=keyName;if(callback){callback(new Error(msg))}}});if(!hadError){if(callback){callback(null)}return}})}catch(e){if(callback){callback(e)}return}}toJsonObject(){const ret={};const knownKeys=Object.keys(this);knownKeys.forEach(keyName=>{const cfgKey=this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret}getLowerCaseToKeyMap(){const lowerCaseMap={};Object.keys(this).forEach(key=>{lowerCaseMap[key.toLowerCase()]=key});return lowerCaseMap}}exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:162,fs:157}],243:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./config-system"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentConfigWithRuntimeArgs=exports.AgentConfig=void 0;const config_system_1=require("./config-system");class AgentConfig extends config_system_1.BaseConfiguration{constructor(){super(...arguments);this.token=new config_system_1.StringConfigKey(false);this.buildSessionId=new config_system_1.StringConfigKey(false);this.tokenFile=new config_system_1.StringConfigKey(false);this.server=new config_system_1.StringConfigKey(false);this.proxy=new config_system_1.StringConfigKey(false);this.interval=new config_system_1.NumberConfigKey(false,1e4);this.testStatusCheckInterval=new config_system_1.NumberConfigKey(false,3e4);this.enabled=new config_system_1.BooleanConfigKey(false,true);this.useOtel=new config_system_1.BooleanConfigKey(false,false);this.sendFootprints=new config_system_1.BooleanConfigKey(false,true);this.sendEvents=new config_system_1.BooleanConfigKey(false,true);this.sendLogs=new config_system_1.BooleanConfigKey(false,false);this.customerId=new config_system_1.StringConfigKey(false);this.appName=new config_system_1.StringConfigKey(false);this.branch=new config_system_1.StringConfigKey(false);this.build=new config_system_1.StringConfigKey(false);this.environmentName=new config_system_1.StringConfigKey(false);this.useBranchCoverage=new config_system_1.BooleanConfigKey(false,false);this.labId=new config_system_1.StringConfigKey(false);this.testGroupId=new config_system_1.StringConfigKey(false);this.testStage=new config_system_1.StringConfigKey(false);this.httpServerColoring=new config_system_1.BooleanConfigKey(false,false);this.httpClientColoring=new config_system_1.BooleanConfigKey(false,false);this.useInitialColor=new config_system_1.BooleanConfigKey(false,true);this.gzip=new config_system_1.BooleanConfigKey(false,true);this.useIstanbul=new config_system_1.BooleanConfigKey(false,false);this.enableChildProcessPatcher=new config_system_1.BooleanConfigKey(false,false);this.loggers=new config_system_1.StringConfigKey(false,"");this.httpListeningPort=new config_system_1.NumberConfigKey(false,0);this.useFootprintsV3=new config_system_1.BooleanConfigKey(false,true);this.extendedFootprints=new config_system_1.BooleanConfigKey(false,false);this.projectRoot=new config_system_1.StringConfigKey(false);this.enforceFullRun=new config_system_1.BooleanConfigKey(false,false);this.footprintsEnableV6=new config_system_1.BooleanConfigKey(false,true);this.footprintsBufferThresholdMb=new config_system_1.NumberConfigKey(false,10);this.executionQueryIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.footprintsQueueSize=new config_system_1.NumberConfigKey(false,2);this.footprintsSendIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.footprintsCollectIntervalSecs=new config_system_1.NumberConfigKey(false,10);this.shouldCheckForActiveExecutionOnStartUp=new config_system_1.BooleanConfigKey(false,true);this.useTsNode=new config_system_1.BooleanConfigKey(false,false);this.testRecommendationSleepSeconds=new config_system_1.NumberConfigKey(false,1);this.removeSensitiveData=new config_system_1.BooleanConfigKey(false,false);this.httpTimeout=new config_system_1.NumberConfigKey(false,60*1e3*2);this.httpMaxAttempts=new config_system_1.NumberConfigKey(false,6);this.httpAttemptInterval=new config_system_1.NumberConfigKey(false,5*1e3);this.collectorUrl=new config_system_1.StringConfigKey(false)}}exports.AgentConfig=AgentConfig;class AgentConfigWithRuntimeArgs extends AgentConfig{constructor(){super(...arguments);this.cfg=new config_system_1.StringConfigKey(false)}}exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":242}],244:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./config-system","object-assign","jwt-decode"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigProcess=void 0;const events=require("events");const config_system_1=require("./config-system");const assign=require("object-assign");const jwtDecode=require("jwt-decode");class ConfigProcess extends events.EventEmitter{constructor(cfg,watchdog,backendProxy,logger){super();this.cfg=cfg;this.watchdog=watchdog;this.backendProxy=backendProxy;this.logger=logger;this.isRunning=false;if(!cfg)throw new Error("cfg is required");this.initialCfg=assign({},cfg.toJsonObject());if(!watchdog)throw new Error("watchdog is required");if(!backendProxy)throw new Error("backendProxy is required");if(!logger){throw new Error("logger is required")}watchdog.on("alarm",()=>{watchdog.stop();this.reloadConfigFromServer()});this.initCfg()}reloadConfigFromServer(callback){this.backendProxy.getRemoteConfig({appName:this.cfg.appName.value,branch:this.cfg.branch.value,build:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value},(err,updatedCfg)=>{if(!err&&updatedCfg){this.mergeConfigFromServerAndFireEvent(updatedCfg)}this.watchdog.start();if(callback){callback(err)}})}mergeConfigFromServerAndFireEvent(updatedCfgObject){let configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(const key in updatedCfgObject){if(this.cfg[key]&&this.cfg[key].isConfigKey&&this.cfg[key].value!=updatedCfgObject[key]){configChanged=true;break}}if(configChanged){this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(updatedCfgObject));this.emit("configuration_changed",this.cfg)}}getConfiguration(){return this.cfg}initCfg(){if(this.cfg.token.hasValue){try{const tokenData=jwtDecode(this.cfg.token.value);if(!tokenData["x-sl-server"]){throw new Error("Token Is Invalid. Doesn't Contain Server")}if(!this.cfg.server.hasValue)this.cfg.server.value=tokenData["x-sl-server"];if(!tokenData["subject"]){throw new Error("Token Is Invalid. Doesn't Contain Subject")}let customerId=tokenData["subject"];const subjectParts=tokenData["subject"].split("@");customerId=subjectParts[0];this.cfg.customerId.value=this.cfg.customerId.value||customerId}catch(err){this.cfg.enabled.value=false;this.logger.error(`Error loading configuration. Agent will be disabled. ${err}`)}}}start(callback){if(this.isRunning)return;if(!this.cfg.enabled.value)return;if(!this.cfg.server.value||!this.cfg.token.hasValue)return;this.reloadConfigFromServer(callback);this.isRunning=true}stop(callback){this.watchdog.stop();this.isRunning=false;return callback()}}exports.ConfigProcess=ConfigProcess})},{"./config-system":242,events:158,"jwt-decode":284,"object-assign":159}],245:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./index"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopConfigProcess=void 0;const index_1=require("./index");class NoopConfigProcess extends index_1.ConfigProcess{start(callback){return callback===null||callback===void 0?void 0:callback(null)}stop(callback){return callback()}reloadConfigFromServer(callback){return callback===null||callback===void 0?void 0:callback(null)}}exports.NoopConfigProcess=NoopConfigProcess})},{"./index":244}],246:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:true});exports.Constants=void 0;class Constants{}exports.Constants=Constants;Constants.TRUE="true";Constants.FALSE="false";Constants.BUILD_SESSION_ID="buildSessionId";Constants.REQUEST="request";Constants.FOOTPRINTS_PACKET="footprintsPacket";Constants.TEST_STAGE="testStage";Constants.EXECUTION_BSID="executionBsid";Constants.CALLBACK="callback";Constants.PULL_REQUEST_PARAMS="pullRequestParams";Constants.SL_WINDOW_OBJECT="window.$Sealights";Constants.SKIP_BROWSER_AGENT=`${Constants.SL_WINDOW_OBJECT}.skipSlAgent`;Constants.Messages=(_a=class{},_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a)})},{}],247:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../footprints-process-v6/buffer-size-helper","../utils/env-var-parsing"],factory)}})(function(require,exports){"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;const buffer_size_helper_1=require("../footprints-process-v6/buffer-size-helper");const env_var_parsing_1=require("../utils/env-var-parsing");class SlEnvVars{static inProductionListenerMode(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]}static getProductionListenerModes(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")}static getFileStorage(){return process.env[SlEnvVars.FILE_STORAGE]}static getBasePath(){return process.env[SlEnvVars.BASE_PATH]}static isUseNewUniqueId(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)}static isUseIstanbul(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_ISTANBUL)}static enableFootprintsV6(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)}static getFootprintsCollectIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)}static getFootprintsSendMaxIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)}static getFootprintsQueueSize(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)}static getExecutionQueryIntervalSecs(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)}static getFootprintsBufferThresholdMb(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)}static blockBrowserHttpTraffic(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)}static getDisableHookDependencyGuard(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)}static shouldUseOtel(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_OTEL_AGENT)}static useSlMapping(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_SL_MAPPING)}static turnOtelOn(){process.env[SlEnvVars.USE_OTEL_AGENT]="true"}static turnOtelOff(){process.env[SlEnvVars.USE_OTEL_AGENT]="false"}static useSpawnWrap(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.SL_USE_SPAWN_WRAP)}}exports.SlEnvVars=SlEnvVars;SlEnvVars.PRODUCTION_LISTENER="SL_production";SlEnvVars.FILE_STORAGE="SL_fileStorage";SlEnvVars.NEW_UNIQUE_ID="SL_newUniqueId";SlEnvVars.BASE_PATH="SL_basePath";SlEnvVars.USE_ISTANBUL="SL_useIstanbul";SlEnvVars.ENABLE_FOOTPRINTS_V6="SL_footprintsEnableV6";SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS="SL_footprintsCollectIntervalSecs";SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS="SL_footprintsSendIntervalSecs";SlEnvVars.FOOTPRINTS_QUEUE_SIZE="SL_footprintsQueueSize";SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC="SL_executionQueryIntervalSecs";SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB="SL_footprintsBufferThresholdMb";SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC="SL_blockBrowserHttpTraffic";SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD="SL_disableHookDependencyGuard";SlEnvVars.USE_OTEL_AGENT="SL_useOtelAgent";SlEnvVars.USE_SL_MAPPING="SL_useSlMapping";SlEnvVars.SL_USE_SPAWN_WRAP="SL_useSpawnWrap";SlEnvVars.CIA=(_a=class{static getFileExtensions(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]}static getSendCommitTitles(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.SEND_COMMIT_TITLES,true)}static getSourceRoot(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]}static getSlMappingPath(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]}static getSlMappingUrl(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]}static reduceInstrumentedFileSize(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)}static omitInstrumentedFunctionMap(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.OMIT_INSTRUMENTED_FUNCTION_MAP)}static minifyInstrumentedOutput(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)}static inProcessInstrumentation(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)}static useExperimentalSizeReduction(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.USE_EXPERIMENTAL_SIZE_REDUCTION)}static getMaxBuffer(){const bufferInBytes=env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*buffer_size_helper_1.BufferSizeHelper.BYTES_IN_MB}return bufferInBytes}},_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SL_SOURCE_ROOT="SL_sourceRoot",_a.SL_MAPPING_PATH="SL_mappingPath",_a.SL_MAPPING_URL="SL_mappingUrl",_a.REDUCE_INSTRUMENTED_FILE_SIZE="SL_reduceInstrumentedFileSize",_a.OMIT_INSTRUMENTED_FUNCTION_MAP="SL_omitInstrumentedFunctionMap",_a.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.USE_EXPERIMENTAL_SIZE_REDUCTION="SL_experimentalSizeReduction",_a.SEND_COMMIT_TITLES="SL_sendCommitTitles",_a.MAX_BUFFER="SL_maxBuffer",_a)})}).call(this)}).call(this,require("_process"))},{"../footprints-process-v6/buffer-size-helper":257,"../utils/env-var-parsing":277,_process:162}],248:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsMapping=void 0;var FootprintsMapping;(function(FootprintsMapping){FootprintsMapping["SERVER"]="server";FootprintsMapping["AGENT"]="agent"})(FootprintsMapping=exports.FootprintsMapping||(exports.FootprintsMapping={}))})},{}],249:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ElementType=void 0;var ElementType;(function(ElementType){ElementType["METHOD"]="method";ElementType["BRANCH"]="branch"})(ElementType=exports.ElementType||(exports.ElementType={}))})},{}],250:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FileElement=void 0;const validation_utils_1=require("../utils/validation-utils");class FileElement{constructor(type,startPosition,endPosition,uniqueIdKey,filename){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(type,"type");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(startPosition,"startPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(endPosition,"endPosition");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(uniqueIdKey,"uniqueIdKey");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(filename,"filename");this._type=type;this._startPosition=startPosition;this._endPosition=endPosition;this._uniqueIdKey=uniqueIdKey;this._filename=filename}get type(){return this._type}set type(value){this._type=value}get startPosition(){return this._startPosition}set startPosition(value){this._startPosition=value}get endPosition(){return this._endPosition}set endPosition(value){this._endPosition=value}get uniqueIdKey(){return this._uniqueIdKey}set uniqueIdKey(value){this._uniqueIdKey=value}get uniqueIdKey_decl(){return this._uniqueIdKey_decl}set uniqueIdKey_decl(value){this._uniqueIdKey_decl=value}get filename(){return this._filename}set filename(value){this._filename=value}get uniqueId(){return this._uniqueId}set uniqueId(value){this._uniqueId=value}get parentPosition(){return this._parentPosition}set parentPosition(value){this._parentPosition=value}get index(){return this._index}set index(value){this._index=value}isStartsAfter(fileElement){if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())>parseInt(fileElement.startPosition.column.toString())){return true}return false}isStartsBefore(fileElement){if(parseInt(this._startPosition.line.toString())>parseInt(fileElement.startPosition.line.toString())){return false}if(parseInt(this._startPosition.line.toString())<parseInt(fileElement.startPosition.line.toString())){return true}if(parseInt(this._startPosition.column.toString())<parseInt(fileElement.startPosition.column.toString())){return true}return false}isEndsAfter(fileElement){if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())>parseInt(fileElement.endPosition.column.toString())){return true}return false}isEndsBefore(fileElement){if(parseInt(this._endPosition.line.toString())>parseInt(fileElement.endPosition.line.toString())){return false}if(parseInt(this._endPosition.line.toString())<parseInt(fileElement.endPosition.line.toString())){return true}if(parseInt(this._endPosition.column.toString())<parseInt(fileElement.endPosition.column.toString())){return true}return false}}exports.FileElement=FileElement})},{"../utils/validation-utils":280}],251:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulUniqueIdConverter=void 0;const contracts_1=require("./contracts");const unique_id_converter_1=require("./unique-id-converter");class IstanbulUniqueIdConverter extends unique_id_converter_1.UniqueIdConverter{constructor(filename,logger){super(filename,logger)}createElementsArray(file){file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};const methodsArr=Object.keys(file.fnMap).map(key=>this.formatMethod(file.fnMap[key]));const branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)}createElementPosition(position){return position}createBranchElements(branchesMap){const branchesMapArr=Object.keys(branchesMap).map(key=>branchesMap[key]);let branchesArr=[];for(const branch of branchesMapArr){branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr}extractBranchParts(branch){const formattedBranches=[];const locations=branch.locations;for(let i=0;i<locations.length;i++){const element={};element.position=locations[i].start;element.endPosition=locations[i].end;element.uniqueId=this.filename+"|"+this.formatLoc(element.position)+"|"+i;formattedBranches.push(element)}return formattedBranches}formatMethod(method){const element={};element.position=method.loc.start;element.endPosition=method.loc.end;element.uniqueId=this.filename+"@"+this.formatLoc(method.loc.start);if(method.decl&&method.decl.start){element.uniqueId_decl=this.filename+"@"+this.formatLoc(method.decl.start);if(method.decl.start.line<method.loc.start.line){element.position=method.decl.start}}return element}formatLoc(loc){return loc.line+","+loc.column}}exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":249,"./unique-id-converter":254}],252:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","../system-date","../utils/files-utils","./istanbul-unique-id-converter"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveNewId=void 0;const path_1=require("path");const system_date_1=require("../system-date");const files_utils_1=require("../utils/files-utils");const istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=(0,path_1.normalize)(moduleName);const moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug(`building uniqueids map for ${moduleData.path}`);const before=(0,system_date_1.getSystemDateValueOf)();logger.debug(`file ${moduleData.path} not contains uniqueIdMaps, trying to reload`);createSLMapping(moduleData.path,relativePath,coverageObject,logger);const after=(0,system_date_1.getSystemDateValueOf)();logger.debug("*******************************create unique id map ******************************************");logger.debug(after-before);logger.debug("*******************************create unique id map ******************************************")}const newUniqueId=moduleData.uniqueIdsMap[uniqueIdKey];if(!newUniqueId){logger.error(`could not generate new uniqueId for '${uniqueIdKey}'`)}return newUniqueId}exports.resolveNewId=resolveNewId;function resolveModule(coverageObject,moduleName,logger){const withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);const moduleData=coverageObject[moduleName]||coverageObject[withLeftSlashes];if(!moduleData){logger.warn(`Coverage object not contains data for ${moduleName} or ${withLeftSlashes}`)}return moduleData}function createSLMapping(fullPath,relativePath,coverageObject,logger){const module=coverageObject[fullPath];const converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":275,"../utils/files-utils":278,"./istanbul-unique-id-converter":251,path:161}],253:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../utils/files-utils","../source-maps-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OriginalModuleLoader=void 0;const validation_utils_1=require("../utils/validation-utils");const files_utils_1=require("../utils/files-utils");const source_maps_utils_1=require("../source-maps-utils");const BRANCHES_MAP_KEY="branchMap";const METHODS_MAP_KEY="fnMap";class OriginalModuleLoader{constructor(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}load(){const modules=Object.keys(this.coverageObject);modules.map(moduleName=>this.tryLoadOriginalModule(moduleName))}tryLoadOriginalModule(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)}readOriginalModule(moduleName){const sourceMapsReader=this.getSourceMapForFile(moduleName);const module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(key=>this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName));Object.keys(module.fnMap).map(key=>this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName))}resolveAndAddMethod(method,sourceMapsReader,moduleName){const originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;const originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}}resolveAndAddBranch(branch,sourceMapsReader,moduleName){const originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;const originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){const originalLocations=branch.locations.map(locationElement=>this.createElementSourceData(locationElement,sourceMapsReader,moduleName));originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}}loadOriginalDataForElement(sourceMapsReader,element,moduleName,originalElement){const sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);const sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;const originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};const sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);const sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName}addElementToModule(moduleName,element,mapObjectKey){const module=this.getOrCreateIstanbulModule(moduleName);const key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}}createElementSourceData(locationElement,sourceMapsReader,moduleName){const sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);const sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}const sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement}getOrCreateIstanbulModule(moduleName){let module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module}getSourceMapForFile(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}const sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap}readSourceMapData(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{const originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){let originalFilename=originalPosition.source;if(originalFilename.indexOf("webpack:///webpack/")===-1&&originalFilename.indexOf("webpack:///external")===-1){if(originalFilename.indexOf("webpack:///")===0){originalFilename=originalFilename.substring(11)}originalFilename=files_utils_1.FilesUtils.resolveOriginalFullFileName(fullPath,originalFilename);const originalPositionObj={line:originalPosition.line,column:originalPosition.column};const result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null}createElementKey(element){return element.loc.start.line+":"+element.loc.start.column}createEmptyBranchObject(){return{loc:{},locations:[],type:"",line:null}}createEmptyMethodObject(){return{loc:{},name:"",line:null}}createIstanbulModule(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,uniqueIdsMap:null}}get fileToSourceMapConsumer(){return this._fileToSourceMapConsumer}set fileToSourceMapConsumer(value){this._fileToSourceMapConsumer=value}}exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":272,"../utils/files-utils":278,"../utils/validation-utils":280}],254:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./file-element"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.UniqueIdConverter=void 0;const contracts_1=require("./contracts");const file_element_1=require("./file-element");const METHOD_DELIMITER="@";const BRANCH_DELIMITER="|";const NULL_PARAM_MESSAGE="cannot be null or undefined";class UniqueIdConverter{constructor(filename,logger){if(!filename){throw new Error("'filename' "+NULL_PARAM_MESSAGE)}if(!logger){throw new Error("'logger' "+NULL_PARAM_MESSAGE)}this._filename=filename;this.logger=logger;this._uniqueIdsMap={};this._methodsArray=[];this._branchesArray=[]}sortElements(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)}createElementsArray(file){file.methods=file.methods||[];file.branches=file.branches||[];this.fillFileElementsArray(file.methods,this._methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(file.branches,this._branchesArray,contracts_1.ElementType.BRANCH)}createFileElement(element,filename,type){const startPosition=this.createElementPosition(element.position);const endPosition=this.createElementPosition(element.endPosition);const fileElement=new file_element_1.FileElement(type,startPosition,endPosition,element.uniqueId,filename);if(element.uniqueId_decl){fileElement.uniqueIdKey_decl=element.uniqueId_decl}if(element.parentPosition){const index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}return fileElement}process(){this.removeDuplicateElements(this._methodsArray);this.removeDuplicateElements(this._branchesArray);this.sortElements();this.logger.debug(`sorted ${this._branchesArray.length} branches`);this.logger.debug(`sorted ${this._methodsArray.length} methods`);this.fillUniqueIdsMap()}setAndInitFile(file){this.createElementsArray(file)}createElementPosition(position){let line;let column;if(Array.isArray(position)&&position.length===2){line=parseInt(position[0]);column=parseInt(position[1])}else{throw new Error("element has no correct startPosition array, cannot resolve startPosition")}return{column:column,line:line}}fillFileElementsArray(elements,array,type){for(const element of elements){array.push(this.createFileElement(element,this._filename,type))}}fillUniqueIdsMap(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)}createNewUniqueIds(array,delimiter){const aggregatedByLine=this.aggregateElementsByLine(array);const lines=Object.keys(aggregatedByLine);for(const line of lines){const indexesArray=aggregatedByLine[line];for(let i=0;i<indexesArray.length;i++){const currentIndex=indexesArray[i];const currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug(`[UniqueIdConverter] uniqueId ${currentElement.uniqueIdKey} converted to
5
5
  ${currentElement.uniqueId}`);this._uniqueIdsMap[currentElement.uniqueIdKey]=currentElement.uniqueId;if(currentElement.uniqueIdKey_decl){this._uniqueIdsMap[currentElement.uniqueIdKey_decl]=currentElement.uniqueId}}}}comparePosition(elm1,elm2){if(elm1.startPosition.line<elm2.startPosition.line){return-1}if(elm1.startPosition.line>elm2.startPosition.line){return 1}if(elm1.startPosition.column<elm2.startPosition.column){return-1}if(elm1.startPosition.column>elm2.startPosition.column){return 1}if(elm1.index<elm2.index){return-1}if(elm1.index>elm2.index){return 1}return 0}get uniqueIdsMap(){return this._uniqueIdsMap}get methodsArray(){return this._methodsArray}set methodsArray(value){this._methodsArray=value}get branchesArray(){return this._branchesArray}set branchesArray(value){this._branchesArray=value}get filename(){return this._filename}removeDuplicateElements(elementsArray){const existedKeys={};elementsArray=elementsArray.filter(element=>{return this.filterDuplicates(element,existedKeys)})}filterDuplicates(element,existedKeys){if(existedKeys[element.uniqueIdKey]||element.uniqueIdKey_decl&&existedKeys[element.uniqueIdKey_decl]){return false}existedKeys[element.uniqueIdKey]=true;if(element.uniqueIdKey_decl){existedKeys[element.uniqueIdKey_decl]=true}return true}removeBranchesOutOfMethods(){const validBranches=[];let methodsIndex=0;for(const branch of this._branchesArray){for(let i=methodsIndex;i<this._methodsArray.length;i++){const currentMethod=this._methodsArray[i];const branchPosition=this.checkBranchPosition(branch,currentMethod);if(branchPosition===0){validBranches.push(branch);break}if(branchPosition===1){methodsIndex++}}}this._branchesArray=validBranches.sort(this.comparePosition)}checkBranchPosition(branch,method){if(branch.isStartsAfter(method)&&branch.isEndsBefore(method)){return 0}if(branch.isStartsBefore(method)&&branch.isEndsBefore(method)){return-1}if(branch.isStartsAfter(method)&&branch.isEndsAfter(method)){return 1}this.logger.warn(`branch started at '${branch.startPosition.line},${branch.startPosition.column}' in file '${this._filename}' located across methods, probably some error`);return 0}aggregateElementsByLine(elements){const aggregated={};for(let i=0;i<elements.length;i++){const element=elements[i];const lineNumber=element.startPosition.line;if(!aggregated[lineNumber]){aggregated[lineNumber]=[]}aggregated[lineNumber].push(i)}return aggregated}}exports.UniqueIdConverter=UniqueIdConverter})},{"./contracts":249,"./file-element":250}],255:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../utils/validation-utils","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsProcess=void 0;const validation_utils_1=require("../utils/validation-utils");const system_date_1=require("../system-date");class EventsProcess{constructor(configuration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentDataService,backendProxy,eventsQueue,logger,colorContextManager){this.colorContextManager=colorContextManager;this._isRunning=false;this.sequence=0;this._onGoingRequests=[];validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configuration,"configuration");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(sendToServerWatchdog,"sendToServerWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(keepAliveWatchdog,"keepAliveWatchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(environmentDataService,"environmentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(eventsQueue,"eventsQueue");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._configuration=configuration;this._agentInstanceData=agentInstanceData;this._sendToServerWatchdog=sendToServerWatchdog;this.keepAliveWatchdog=keepAliveWatchdog;this.environmentData=environmentDataService;this._backendProxy=backendProxy;this._logger=logger;this._eventsQueue=eventsQueue;this.init()}enqueueEvent(evt){var _a;evt.localTime=evt.localTime||(0,system_date_1.getSystemDateValueOf)();evt.colorName=(_a=this.colorContextManager)===null||_a===void 0?void 0:_a.getTestName();this._eventsQueue.enqueue(evt);if(this.isRunning&&this.configuration.sendEvents.value&&this.configuration.enabled.value){this.ensureKeepaliveThreadRunning()}}start(){if(this._isRunning||!this._configuration.enabled.value){return}this._sendToServerWatchdog.start();if(this._eventsQueue.getQueueSize()>0){this.ensureKeepaliveThreadRunning()}this._isRunning=true}stop(){return __awaiter(this,void 0,void 0,function*(){this._sendToServerWatchdog.stop();this.keepAliveWatchdog.stop();if(this._configuration.enabled.value===false||this._configuration.sendEvents.value===false){return}try{yield Promise.all(this._onGoingRequests);yield this.submitEventsSync()}catch(e){this._logger.warn("Error while stopping EventsProcess: ",e)}this._isRunning=false})}getQueueSize(){return this._eventsQueue.getQueueSize()}submitEvents(){if(!this._isRunning||!this._configuration.sendEvents.value||!this._configuration.enabled.value||this._eventsQueue.getQueueSize()==0){return}const items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);const packet=this.createEventsPacket(items);const promise=this._backendProxy.submitEventsPromise(packet);this._onGoingRequests.push(promise);promise.then(()=>{if(this._eventsQueue.getQueueSize()>0){this.submitEvents()}this.removeRequest(promise)}).catch(err=>{this._logger.warn(`Error while submitting events, ${err}`);this._eventsQueue.requeue(items);this.removeRequest(promise)})}submitEventsSync(){return __awaiter(this,void 0,void 0,function*(){try{while(this._eventsQueue.getQueueSize()>0){const items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);const packet=this.createEventsPacket(items);yield this._backendProxy.submitEventsPromise(packet)}}catch(e){this._logger.warn(`Error while sending events synchronously. ${e}`)}})}createEventsPacket(items){return{customerId:this._configuration.customerId.value,appName:this._configuration.appName.value,build:this._configuration.build.value,branch:this._configuration.branch.value,environment:this.environmentData,configurationData:this._configuration.toJsonObject,testSelectionStatus:this._testSelectionStatus,events:items,meta:{sequence:++this.sequence,generated:(0,system_date_1.getSystemDateValueOf)(),agentId:this._agentInstanceData.agentId}}}init(){this._sendToServerWatchdog.on("alarm",()=>this.submitEvents());this._eventsQueue.on("full",()=>this.submitEvents());this.keepAliveWatchdog.on("alarm",()=>{if(this.eventsQueue.getQueueSize()==0){this.keepAliveWatchdog.stop()}})}ensureKeepaliveThreadRunning(){this.keepAliveWatchdog.start()}removeRequest(request){const index=this._onGoingRequests.indexOf(request);this._onGoingRequests.splice(index,1)}get onGoingRequests(){return this._onGoingRequests}get configuration(){return this._configuration}get logger(){return this._logger}get isRunning(){return this._isRunning}set isRunning(value){this._isRunning=value}get sendToServerWatchdog(){return this._sendToServerWatchdog}get backendProxy(){return this._backendProxy}get eventsQueue(){return this._eventsQueue}set testSelectionStatus(testSelectionStatus){this._testSelectionStatus=testSelectionStatus}get testSelectionStatus(){return this._testSelectionStatus}}exports.EventsProcess=EventsProcess;EventsProcess.ITEMS_TO_DEQUE=1e3})},{"../system-date":275,"../utils/validation-utils":280}],256:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./location-formatter","../../common/footprints-process-v6/hits-converter","../utils/files-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BaseBrowserHitsConverter=void 0;const location_formatter_1=require("./location-formatter");const hits_converter_1=require("../../common/footprints-process-v6/hits-converter");const files_utils_1=require("../utils/files-utils");class BaseBrowserHitsConverter extends hits_converter_1.HitsConverter{constructor(relativePathResolver,buildSessionId,logger){super(relativePathResolver,{},{},logger);this.buildSessionId=buildSessionId}getMethodUniqueId(startLoc,relativePath,absolutePath){const uniqueId=absolutePath+hits_converter_1.HitsConverter.METHOD_ID_DEL+this.formatLoc(startLoc);return this.tryGetUniqueIdFromSlMapping(uniqueId)}getBranchUniqueId(startLoc,relativePath,absolutePath,leaveIndex){const uniqueId=absolutePath+hits_converter_1.HitsConverter.BRANCH_ID_DEL+this.formatLoc(startLoc)+hits_converter_1.HitsConverter.BRANCH_ID_DEL+leaveIndex;return this.tryGetUniqueIdFromSlMapping(uniqueId)}getDeclStart(hit){const decl=this.getDecl(hit);return decl.start||decl.st}getDecl(hit){return hit.decl||hit.d}getStartLoc(hit){const loc=hit.loc||hit.lc;return loc.start||loc.st}getLeaveStartLoc(hit,leaveIdx){const locations=hit.branchData.locations||hit.branchData.lcs;return locations[leaveIdx].start||locations[leaveIdx].st}formatLoc(loc){return(0,location_formatter_1.formatLocation)(loc,this.logger)}tryGetUniqueIdFromSlMapping(rawUniqueId){rawUniqueId=files_utils_1.FilesUtils.adjustPathSlashes(rawUniqueId);const mapping=this.getSlMapping()||{};return mapping[rawUniqueId]||rawUniqueId}}exports.BaseBrowserHitsConverter=BaseBrowserHitsConverter})},{"../../common/footprints-process-v6/hits-converter":262,"../utils/files-utils":278,"./location-formatter":264}],257:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BufferSizeHelper=void 0;class BufferSizeHelper{constructor(){this.uniqueIdsLengthSum=0;this.testNamesCount=0;this.testNamesLengthSum=0;this.hitCount=0;this.indicesCount=0;this.uniqueIdsCount=0}calculateBufferSize(){const sizeInBytes=this.uniqueIdsCount*BufferSizeHelper.FOUR_BYTES+this.uniqueIdsLengthSum+(this.testNamesCount*BufferSizeHelper.FOUR_BYTES+this.testNamesLengthSum)+this.hitCount*BufferSizeHelper.APPROX_HIT_SIZE+this.indicesCount*BufferSizeHelper.EIGHT_BYTES;return sizeInBytes/BufferSizeHelper.BYTES_IN_MB}incrementSizeCounters(testName,methodIndicesSize,branchIndicesSize){this.hitCount++;this.indicesCount+=methodIndicesSize+branchIndicesSize;if(testName){this.testNamesCount++;this.testNamesLengthSum+=testName.length}}}exports.BufferSizeHelper=BufferSizeHelper;BufferSizeHelper.FOUR_BYTES=4;BufferSizeHelper.EIGHT_BYTES=8;BufferSizeHelper.APPROX_HIT_SIZE=128;BufferSizeHelper.BYTES_IN_MB=1024*1024;BufferSizeHelper.BYTES_IN_GB=1024*1024*1024})},{}],258:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../agent-events/agent-events-contracts","../contracts","./footprints-buffer"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CollectorFootprintsBuffer=void 0;const agent_events_contracts_1=require("../agent-events/agent-events-contracts");const contracts_1=require("../contracts");const footprints_buffer_1=require("./footprints-buffer");class CollectorFootprintsBuffer extends footprints_buffer_1.FootprintsBuffer{constructor(agentInstanceData,agentConfig,footprintsMapping){super(agentInstanceData,agentConfig);this.meta.footprintsMapping=footprintsMapping===contracts_1.FootprintsMapping.SERVER?footprintsMapping:contracts_1.FootprintsMapping.AGENT;this.meta.agentConfig={agentId:this.agentInstanceData.agentId,appName:this.agentConfig.appName.value,build:this.agentConfig.build.value,branch:this.agentConfig.branch.value,buildSessionId:this.agentConfig.buildSessionId.value,labId:this.agentConfig.labId.value,agentVersion:this.agentInstanceData.agentVersion,agentType:agent_events_contracts_1.AgentTypes.BROWSER_AGENT}}}exports.CollectorFootprintsBuffer=CollectorFootprintsBuffer})},{"../agent-events/agent-events-contracts":227,"../contracts":248,"./footprints-buffer":260}],259:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports",".","../no-op-state-tracker"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CollectorFootprintsProcess=void 0;const _1=require(".");const no_op_state_tracker_1=require("../no-op-state-tracker");class CollectorFootprintsProcess extends _1.FootprintsProcess{constructor(cfg,sendToServerWatchdog,keepaliveWatchdog,logger,hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker){super(cfg,sendToServerWatchdog,keepaliveWatchdog,logger,hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker)}submitQueuedFootprints(){return __awaiter(this,void 0,void 0,function*(){if(!this.shouldSubmitFootprints()){return}const packet=this.footprintsBuffer.createPacket();if(packet){this.ongoingRequestsCounter++;try{yield this.backendProxy.submitFootprintsToCollector(packet,this.cfg.buildSessionId.value);this.logger.info(`Footprints packet submitted successfully. packet contains ${packet.methods.length} methods, ${packet.branches.length} branches in ${packet.executions.length} executions`)}catch(e){this.logger.error(`Error while submitting footprints '${e}'`)}finally{this.ongoingRequestsCounter--}}else{this.logger.info("No hits collected nothing to submit")}})}stop(){return __awaiter(this,void 0,void 0,function*(){this.sendToServerWatchdog.stop();this.hitsCollector.sendErrors();if(!this.shouldSubmitFootprints()){this.isRunning=false;return}yield this.flushCurrentFootprints(true);const packet=this.footprintsBuffer.createPacket();this.isRunning=false;if(!packet){this.logger.info("No hits collected, nothing to submit");return}this.logger.info("Start submitting footprints, triggered by stop event.");try{yield this.backendProxy.submitFootprintsToCollector(packet,this.cfg.buildSessionId.value);this.logger.info("Final footprints submitted successfully")}catch(e){this.logger.error(`Failed to submit final footprints, error: ${e.message}`);this.logger.debug(e);return}})}flushCurrentFootprints(isFinalFootprints=false){return __awaiter(this,void 0,void 0,function*(){const currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();if(currentTestIdentifier){const testIdentifierParts=no_op_state_tracker_1.NoopStateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug("Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '%s'",currentTestIdentifier);yield this.enqueueCurrentFootprints(this.stateTracker.currentExecution,testIdentifierParts.testName,isFinalFootprints)}else{this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");yield this.enqueueCurrentFootprints(this.stateTracker.currentExecution,null,isFinalFootprints)}})}}exports.CollectorFootprintsProcess=CollectorFootprintsProcess})},{".":263,"../no-op-state-tracker":271}],260:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../agent-events/cockpit-notifier","../agent-events/agent-events-contracts","events","./buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsBuffer=void 0;const cockpit_notifier_1=require("../agent-events/cockpit-notifier");const agent_events_contracts_1=require("../agent-events/agent-events-contracts");const events=require("events");const buffer_size_helper_1=require("./buffer-size-helper");class FootprintsBuffer extends events.EventEmitter{constructor(agentInstanceData,agentConfig){super();this.formatVersion="6.0";this.agentInstanceData=agentInstanceData;this._agentConfig=agentConfig;this.currentBufferSize=0;this.resetState();this.meta={agentId:this.agentInstanceData.agentId,intervals:{timedFootprintsCollectionIntervalSeconds:this._agentConfig.footprintsCollectIntervalSecs.value},labId:this._agentConfig.labId.value}}addHit(footprints,collectionInterval,executionId,testName,isInitFootprints,isFinalFootprints){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_contracts_1.AgentEventCode.FIRST_TIME_COLLECTED_FP);const methodIndices=this.addOrGetIndices(footprints.methods,true);const branchIndices=this.addOrGetIndices(footprints.branches,false);const executionIdx=this.addOrGetExecutionIndex(executionId);this.executions[executionIdx].hits.push({branches:branchIndices,methods:methodIndices,start:collectionInterval.start,end:collectionInterval.end,testName:testName,isInitFootprints:isInitFootprints,isFinalFootprints:isFinalFootprints});this.bufferSizeHelper.incrementSizeCounters(testName,methodIndices.length,branchIndices.length);this.verifyBufferSize()}createPacket(){const packet=this.toJson();this.resetState();return packet}resetState(){this.branches=[];this.methods=[];this.executions=[];this.methodIdToIndex=new Map;this.branchIdToIndex=new Map;this.bufferSizeHelper=new buffer_size_helper_1.BufferSizeHelper}hasHitsInBuffer(){return this.executions.length>0}get agentConfig(){return this._agentConfig}set agentConfig(value){this._agentConfig=value}toJson(){if(!this.executions||!this.executions.length){return null}return{formatVersion:this.formatVersion,branches:this.branches,executions:this.executions,meta:this.meta,methods:this.methods,moduleName:this.moduleName}}addOrGetIndices(elementIds,isMethods){const map=isMethods?this.methodIdToIndex:this.branchIdToIndex;const arr=isMethods?this.methods:this.branches;const indices=[];elementIds.forEach(id=>{if(!map.get(id)){this.bufferSizeHelper.uniqueIdsLengthSum+=id.length;this.bufferSizeHelper.uniqueIdsCount++;const position=arr.push(id);map.set(id,position-1)}indices.push(map.get(id))});return indices}addOrGetExecutionIndex(executionId){let index=-1;this.executions.every((execution,idx)=>{if(executionId==execution.executionId){index=idx;return false}return true});return index!=-1?index:this.executions.push({executionId:executionId,hits:[]})-1}verifyBufferSize(){if(this.bufferSizeHelper.calculateBufferSize()>=this._agentConfig.footprintsBufferThresholdMb.value){this.emit(FootprintsBuffer.BUFFER_FULL)}}}exports.FootprintsBuffer=FootprintsBuffer;FootprintsBuffer.BUFFER_FULL="bufferFull"})},{"../agent-events/agent-events-contracts":227,"../agent-events/cockpit-notifier":234,"./buffer-size-helper":257,events:158}],261:[function(require,module,exports){(function(global){(function(){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader","../agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsCollector=void 0;const sl_env_vars_1=require("../constants/sl-env-vars");const original_module_loader_1=require("../coverage-elements/original-module-loader");const cockpit_notifier_1=require("../agent-events/cockpit-notifier");const GLOBAL_ISTANBUL_CONTAINER_NAMES=["__coverage__"];class HitsCollector{constructor(logger,globalCoverageObject){this.errors=[];this.logger=logger;this._globalCoverageObject=globalCoverageObject;this.latestCoverageSnapshot={}}getHitElements(){return __awaiter(this,void 0,void 0,function*(){const hitFilesData=[];const globalCoverage=this.getGlobalCoverageObject();if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(globalCoverage,this.logger).load()}for(const filename in globalCoverage){const{fileCoverageSnapshot,currentFileCoverage,shouldResolveRelativePath}=this.getFileCoverageObjects(filename);const hitMethods=this.getHitMethods(currentFileCoverage,fileCoverageSnapshot);const hitBranches=this.getHitBranches(currentFileCoverage,fileCoverageSnapshot);if(hitMethods.length||hitBranches.length){hitFilesData.push({filename:filename,hitMethods:hitMethods,hitBranches:hitBranches,shouldResolveRelativePath:shouldResolveRelativePath})}}this.updateCoverageSnapshot(globalCoverage);return hitFilesData})}get latestCoverageSnapshot(){return this._latestCoverageSnapshot}set latestCoverageSnapshot(value){this._latestCoverageSnapshot=value}get globalCoverageObject(){return this._globalCoverageObject}set globalCoverageObject(value){this._globalCoverageObject=value}getHitMethods(currentHits,snapshotHits){const hitMethodsIndices=Object.keys(currentHits.f).filter(id=>{snapshotHits.f[id]=snapshotHits.f[id]||0;return currentHits.f[id]>snapshotHits.f[id]});return hitMethodsIndices.map(id=>currentHits.fnMap[id])}dropHits(){this.updateCoverageSnapshot(this.getGlobalCoverageObject())}getHitLeaves(currentLeaveHits,snapshotLeaveHits){const hitLeavesIndices=[];snapshotLeaveHits=snapshotLeaveHits||Array(currentLeaveHits.length).fill(0);currentLeaveHits.forEach((leaveHit,leaveIdx)=>{if(currentLeaveHits[leaveIdx]>snapshotLeaveHits[leaveIdx]){hitLeavesIndices.push(leaveIdx)}});return hitLeavesIndices}getHitBranches(currentHits,fileHitSnapshot){const hitBranches=[];for(const branchIdx in currentHits.b){const hitLeaves=this.getHitLeaves(currentHits.b[branchIdx],fileHitSnapshot.b[branchIdx]);if(hitLeaves.length>0){const branchData=currentHits.branchMap[branchIdx];hitBranches.push({branchData:branchData,hitLeaves:hitLeaves})}}return hitBranches}createEmptyIstanbulModule(path,useDataKey=false){const emptyModule={f:{},fnMap:{},b:{},branchMap:{},path:path,s:{}};if(useDataKey){return{data:emptyModule}}return emptyModule}getFileCoverageObjects(filename){let fileCoverageSnapshot=this._latestCoverageSnapshot[filename]||this.createEmptyIstanbulModule(filename);let currentFileCoverage=this._globalCoverageObject[filename];let shouldResolveRelativePath=true;if(!fileCoverageSnapshot.f&&fileCoverageSnapshot.data){fileCoverageSnapshot=fileCoverageSnapshot.data;shouldResolveRelativePath=false}if(!currentFileCoverage.f&&currentFileCoverage.data){currentFileCoverage=currentFileCoverage.data}return{fileCoverageSnapshot:fileCoverageSnapshot,currentFileCoverage:currentFileCoverage,shouldResolveRelativePath:shouldResolveRelativePath}}getGlobalCoverageObject(){if(this._globalCoverageObject)return this._globalCoverageObject;this._globalCoverageObject=HitsCollector.resolveGlobalCoverageObject();if(!this._globalCoverageObject){this.logger.warn("Coverage object not found")}return this._globalCoverageObject}static resolveGlobalCoverageObject(){const re=/^\$\$cov_[0-9]+\$\$$/;const keys=Object.keys(global);for(let i=0;i<keys.length;i++){const k=keys[i];if(re.exec(k)!==null||GLOBAL_ISTANBUL_CONTAINER_NAMES.indexOf(k)>=0){return global[k]}}}updateCoverageSnapshot(currentCounters){for(const istanbulModule in currentCounters){const useDataKey=currentCounters[istanbulModule].data!==undefined;this._latestCoverageSnapshot[istanbulModule]=this._latestCoverageSnapshot[istanbulModule]||this.createEmptyIstanbulModule(istanbulModule,useDataKey);const f=currentCounters[istanbulModule].f||currentCounters[istanbulModule].data.f;const b=currentCounters[istanbulModule].b||currentCounters[istanbulModule].data.b;for(const funcId in f){this.setFunctionHit(istanbulModule,funcId,f,useDataKey)}for(const branchId in b){this.setBranchHit(b,branchId,istanbulModule,useDataKey)}}}setBranchHit(b,branchId,istanbulModule,useDataKey){const currentBranchesHits=b[branchId];this._latestCoverageSnapshot[istanbulModule].b[branchId]=this._latestCoverageSnapshot[istanbulModule].b[branchId]||[];for(let i=0;i<currentBranchesHits.length;i++){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.b[branchId][i]=currentBranchesHits[i]}else{this._latestCoverageSnapshot[istanbulModule].b[branchId][i]=currentBranchesHits[i]}}}setFunctionHit(istanbulModule,funcId,f,useDataKey){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.f[funcId]=f[funcId]}else{this._latestCoverageSnapshot[istanbulModule].f[funcId]=f[funcId]}}sendErrors(){if(this.errors.length>0){const data=JSON.stringify(this.errors);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(`Errors during hit collection: ${data}`);this.errors=[]}}}exports.HitsCollector=HitsCollector})}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../agent-events/cockpit-notifier":234,"../constants/sl-env-vars":247,"../coverage-elements/original-module-loader":253}],262:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/sl-env-vars","../coverage-elements/original-module-loader","./hits-collector","../coverage-elements/new-id-resolver","../agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsConverter=void 0;const sl_env_vars_1=require("../constants/sl-env-vars");const original_module_loader_1=require("../coverage-elements/original-module-loader");const hits_collector_1=require("./hits-collector");const new_id_resolver_1=require("../coverage-elements/new-id-resolver");const cockpit_notifier_1=require("../agent-events/cockpit-notifier");class HitsConverter{constructor(relativePathResolver,sourceMapData,projectRoot,logger){this.conversionErrors=[];this._slMapping={};this.relativePathResolver=relativePathResolver;this.sourceMapData=sourceMapData;this.projectRoot=projectRoot;this.logger=logger}convertHits(hitFilesData){let methodUniqueIds=[];let branchUniqueIds=[];if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger).load()}hitFilesData.forEach(fileHit=>{let relativePath=fileHit.filename;if(fileHit.shouldResolveRelativePath){relativePath=this.relativePathResolver.getRelativePath(fileHit.filename)}methodUniqueIds=methodUniqueIds.concat(this.createMethodIds(fileHit.hitMethods,relativePath,fileHit.filename));branchUniqueIds=branchUniqueIds.concat(this.createBranchIds(fileHit.hitBranches,relativePath,fileHit.filename))});this.sendConversionErrors();return{branches:branchUniqueIds,methods:methodUniqueIds}}get slMapping(){return this._slMapping}set slMapping(value){this._slMapping=value}createMethodIds(hitFunctions,relativePath,absolutePath){const methodIds=[];hitFunctions.forEach(hit=>{methodIds.push(this.getMethodUniqueId(this.getStartLoc(hit),relativePath,absolutePath));if(this.getDecl(hit)&&this.getDeclStart(hit)){methodIds.push(this.getMethodUniqueId(this.getDeclStart(hit),relativePath,absolutePath))}});return methodIds}getDeclStart(hit){return hit.decl.start}getDecl(hit){return hit.decl}getStartLoc(hit){return hit.loc.start}getLeaveStartLoc(hit,leaveIdx,absolutePath){var _a;const position=hit.branchData.locations[leaveIdx].start;const parentPosition=(_a=hit.branchData.loc)===null||_a===void 0?void 0:_a.start;if(!parentPosition){if(!sl_env_vars_1.SlEnvVars.isUseIstanbul()){const message=`\'SL_useIstanbul\' was set to \'false\' but could not find \'loc\' object. branch in file '${absolutePath}' at '${JSON.stringify(position)}'`;this.logger.error(message);this.conversionErrors.push(message)}else{this.logger.debug("Using branch position from 'locations' object due to 'SL_useIstanbul' set to 'true'")}return position}const newInstrumentation=parentPosition.line!=position.line||parentPosition.column!=position.column;if(hit.branchData.type==="if"){const message=newInstrumentation?"Instrumented done by istanbul-lib-instrumenter greater or equal than 5.1.0 enforcing parent positions for the else leave":"Instrumented done by istanbul-lib-instrumenter lower than 5.1.0 using parent positions for the else leave";this.logger.debug(message);return parentPosition}return position}createBranchIds(hitFunctions,relativePath,absolutePath){const branchIds=[];hitFunctions.forEach(hit=>{hit.hitLeaves.forEach(leaveIdx=>{branchIds.push(this.getBranchUniqueId(this.getLeaveStartLoc(hit,leaveIdx,absolutePath),relativePath,absolutePath,leaveIdx))})});return branchIds}getMethodUniqueId(startLoc,relativePath,absolutePath){const idParts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){const uniqueIdKey=idParts.relativePath+"@"+this.formatLoc(idParts.start);const uniqueId=(0,new_id_resolver_1.resolveNewId)(uniqueIdKey,idParts.absolutePath,idParts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger);if(uniqueId){return uniqueId}}return this.buildMethodUniqueId(idParts)}getBranchUniqueId(startLoc,relativePath,absolutePath,leaveIndex){let uniqueId;const parts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){const uniqueIdKey=parts.relativePath+"|"+this.formatLoc(parts.start)+"|"+leaveIndex;uniqueId=(0,new_id_resolver_1.resolveNewId)(uniqueIdKey,parts.absolutePath,parts.relativePath,hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger)}if(!uniqueId){uniqueId=parts.relativePath+HitsConverter.BRANCH_ID_DEL+this.formatLoc(parts.start)+HitsConverter.BRANCH_ID_DEL+leaveIndex}return uniqueId}resolveIdParts(startLoc,relativePath,absolutePath){const sourcePosition=this.sourceMapData.getSourcePosition(relativePath,absolutePath,startLoc,this.projectRoot,this.slMapping);return sourcePosition?sourcePosition:{relativePath:relativePath,start:startLoc,absolutePath:absolutePath}}buildMethodUniqueId(parts){return parts.relativePath+HitsConverter.METHOD_ID_DEL+this.formatLoc(parts.start)}sendConversionErrors(){if(this.conversionErrors.length>0){cockpit_notifier_1.CockpitNotifier.sendErrorsBatch(this.conversionErrors);this.conversionErrors=[]}}formatLoc(loc){return loc.line+","+loc.column}}exports.HitsConverter=HitsConverter;HitsConverter.METHOD_ID_DEL="@";HitsConverter.BRANCH_ID_DEL="|"})},{"../agent-events/cockpit-notifier":234,"../constants/sl-env-vars":247,"../coverage-elements/new-id-resolver":252,"../coverage-elements/original-module-loader":253,"./hits-collector":261}],263:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./footprints-buffer","../footprints-process/collection-interval","../state-tracker","../agent-events/cockpit-notifier","../agent-events/agent-events-contracts","../constants/sl-env-vars","../agent-events/agent-events-guard"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsProcess=void 0;const footprints_buffer_1=require("./footprints-buffer");const collection_interval_1=require("../footprints-process/collection-interval");const state_tracker_1=require("../state-tracker");const cockpit_notifier_1=require("../agent-events/cockpit-notifier");const agent_events_contracts_1=require("../agent-events/agent-events-contracts");const sl_env_vars_1=require("../constants/sl-env-vars");const agent_events_guard_1=require("../agent-events/agent-events-guard");class FootprintsProcess{constructor(cfg,sendToServerWatchdog,keepaliveWatchdog,logger,hitsCollector,hitsConverter,footprintsBuffer,backendProxy,stateTracker){this.isRunning=false;this._ongoingRequestsCounter=0;this.footprintsEnqueueOnce=false;this.cfg=cfg;this.sendToServerWatchdog=sendToServerWatchdog;this.keepaliveWatchdog=keepaliveWatchdog;this.footprintsBuffer=footprintsBuffer;this.hitsConverter=hitsConverter;this.hitsCollector=hitsCollector;this.backendProxy=backendProxy;this.collectionInterval=new collection_interval_1.CollectionInterval(cfg.interval.value);this.stateTracker=stateTracker;this.logger=logger;this.delegateEvents()}enqueueCurrentFootprints(execution,testName,isFinalFootprints=false){var _a,_b;return __awaiter(this,void 0,void 0,function*(){this.currentExecutionBsid=execution.buildSessionId;this.collectionInterval.next();const hitFilesData=yield this.hitsCollector.getHitElements();if(hitFilesData.length){this.logger.info(`Collecting hits for '${hitFilesData.length}' files`);const convertedHits=this.hitsConverter.convertHits(hitFilesData);this.logger.debug(`Converted total ${(_a=convertedHits===null||convertedHits===void 0?void 0:convertedHits.branches)===null||_a===void 0?void 0:_a.length} branches and ${(_b=convertedHits===null||convertedHits===void 0?void 0:convertedHits.methods)===null||_b===void 0?void 0:_b.length} methods.`);this.footprintsBuffer.addHit(convertedHits,this.collectionInterval.toJson(),execution.executionId,testName,this.isInitFootprints(),isFinalFootprints);this.logger.debug(`Hits added successfully for execution ${execution.executionId} and test ${testName}.`)}else{this.logger.info("No files were hits, not collecting footprints")}if(this.isRunning&&this.cfg.sendFootprints.value&&this.cfg.enabled.value){this.ensureKeepaliveThreadRunning();this.sendToServerWatchdog.startIfNotRunning()}this.footprintsEnqueueOnce=true})}updateConfig(updatedCfg){return __awaiter(this,void 0,void 0,function*(){this.cfg=updatedCfg;yield this.stopIfNeededAfterConfigChanged(updatedCfg);this.sendToServerWatchdog.setInterval(this.cfg.footprintsSendIntervalSecs.value);this.footprintsBuffer.agentConfig=updatedCfg})}getBufferPacket(){return __awaiter(this,void 0,void 0,function*(){yield this.flushCurrentFootprints(true);return this.footprintsBuffer.toJson()})}stopIfNeededAfterConfigChanged(updatedCfg){return __awaiter(this,void 0,void 0,function*(){if(updatedCfg.sendFootprints.value===false||updatedCfg.enabled.value===false){cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_contracts_1.AgentEventCode.AGENT_MUTED);this.footprintsBuffer.resetState();try{yield this.stop()}catch(e){this.logger.error(`Error stopping footprints process ${e.message}`);this.logger.debug(e.stackTrace)}}})}ensureKeepaliveThreadRunning(){this.keepaliveWatchdog.start()}submitQueuedFootprints(execution){return __awaiter(this,void 0,void 0,function*(){this.hitsCollector.sendErrors();if(!this.shouldSubmitFootprints()){return}const packet=this.footprintsBuffer.createPacket();if(packet){this.ongoingRequestsCounter++;try{yield this.backendProxy.submitFootprintsV6(packet,execution.buildSessionId,execution.testStage,this.cfg.buildSessionId.value);this.logger.info(`Footprints packet submitted successfully. packet contains ${packet.methods.length} methods, ${packet.branches.length} branches in ${packet.executions.length} executions`)}catch(e){this.logger.error(`Error while submitting footprints '${e}'`);agent_events_guard_1.AgentEventsGuard.notifyIfNeeded(agent_events_contracts_1.AgentEventCode.FOOTPRINTS_SUBMISSION_ERROR,e)}finally{this.ongoingRequestsCounter--}}else{this.logger.info("No hits collected nothing to submit")}})}shouldSubmitFootprints(){if(!this.isRunning){this.logger.info("Agent is not running, not sending footprints");return false}if(this.cfg.sendFootprints.value===false){this.logger.info("Not sending footprints since agent is configured to not send.");return false}return true}start(){if(this.isRunning)return;if(this.cfg.enabled.value==false)return;this.isRunning=true;this.sendToServerWatchdog.start();if(this.footprintsBuffer.hasHitsInBuffer()){this.ensureKeepaliveThreadRunning()}}stop(){return __awaiter(this,void 0,void 0,function*(){this.sendToServerWatchdog.stop();this.hitsCollector.sendErrors();if(!this.shouldSubmitFootprints()){this.isRunning=false;return}yield this.flushCurrentFootprints(true);const packet=this.footprintsBuffer.createPacket();this.isRunning=false;if(!packet){this.logger.info("No hits collected, nothing to submit");return}this.logger.info("Start submitting footprints, triggered by stop event.");try{yield this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value);this.logger.info("Final footprints submitted successfully")}catch(e){this.logger.error(`Failed to submit final footprints, error: ${e.message}`);this.logger.debug(e);return}})}handleTestIdChanged(newTestIdentifier,previousTestIdentifier){if(previousTestIdentifier==null){this.logger.info("Test identifier changed, previous identifier wasn't set, meaning that we didn't have active test. Skip enqueuing footprints process.")}else{const{shouldCollectHits,message}=this.stateTracker.getCollectHitsState();if(!shouldCollectHits){this.logger.info(`Test identifier changed. ${message}`);return}this.logger.debug("Test identifier changed, start enqueuing footprints process.");const prevTestIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(previousTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution,prevTestIdentifierParts.testName)}}delegateEvents(){this.sendToServerWatchdog.on(FootprintsProcess.ALARM_FIRED,()=>{this.logger.debug("Start submitting footprints, triggered by send to server watchdog.");this.submitQueuedFootprints(this.stateTracker.currentExecution)});this.keepaliveWatchdog.on(FootprintsProcess.ALARM_FIRED,()=>{if(!this.hasOngoingRequests()&&!this.footprintsBuffer.hasHitsInBuffer()){this.keepaliveWatchdog.stop()}});this.footprintsBuffer.on(footprints_buffer_1.FootprintsBuffer.BUFFER_FULL,()=>{this.submitQueuedFootprints(this.stateTracker.currentExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_BSID_CHANGED,(prevExecution,newBuildSession)=>{this.logger.warn(`Execution points to different build session '${newBuildSession}'. Collecting and submitting previous footprints`);this.enqueueAndSubmit(prevExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_ID_CHANGED,(prevExecution,newExecutionId)=>{this.logger.warn(`Execution id changed to'${newExecutionId}'. Collecting previous footprints`);this.enqueueCurrentFootprints(prevExecution,null)});this.stateTracker.on(state_tracker_1.StateTracker.TEST_STAGE_CHANGED,(prevExecution,newTestStage)=>{this.logger.warn(`Execution points to different test stage '${newTestStage}'. Collecting and submitting previous footprints`);this.enqueueAndSubmit(prevExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_STATUS_PENDING_DELETE,execution=>{this.enqueueAndSubmit(execution)})}enqueueAndSubmit(executionData,isFinalFootprints=false){return __awaiter(this,void 0,void 0,function*(){yield this.enqueueCurrentFootprints(executionData,null,isFinalFootprints);yield this.submitQueuedFootprints(executionData)})}flushCurrentFootprints(isFinalFootprints=false){return __awaiter(this,void 0,void 0,function*(){const currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();const{shouldCollectHits,message,reason}=this.stateTracker.getCollectHitsState();if(!shouldCollectHits){this.logger.info(`Enqueue footprints interval - ${message}`);this.checkShouldUpdateCoverageSnapshot(reason);return}if(currentTestIdentifier){const testIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug(`Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '${currentTestIdentifier}'`);yield this.enqueueCurrentFootprints(this.stateTracker.currentExecution,testIdentifierParts.testName,isFinalFootprints)}else{this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");yield this.enqueueCurrentFootprints(this.stateTracker.currentExecution,null,isFinalFootprints)}})}checkShouldUpdateCoverageSnapshot(reason){if(this.stateTracker.openExecutionFoundOnce){this.logger.debug(`Did not collect hits - reason: ${reason} and not in initFootprints mode, updating coverage snapshot`);this.hitsCollector.dropHits()}}isInitFootprints(){return this.stateTracker.openExecutionFoundOnce&&!this.footprintsEnqueueOnce}hasOngoingRequests(){return this.ongoingRequestsCounter>0}loadSlMapping(){return __awaiter(this,void 0,void 0,function*(){if(!sl_env_vars_1.SlEnvVars.useSlMapping()){return}const mappingsArr=yield this.backendProxy.getBlobsAsJson(this.cfg.buildSessionId.value);let flatted={};mappingsArr.forEach(mapping=>{flatted=Object.assign(Object.assign({},flatted),mapping)});this.hitsConverter.slMapping=flatted})}set ongoingRequestsCounter(value){this._ongoingRequestsCounter=value}get backendProxy(){return this._backendProxy}set backendProxy(value){this._backendProxy=value}get cfg(){return this._cfg}set cfg(value){this._cfg=value}get sendToServerWatchdog(){return this._sendToServerWatchdog}set sendToServerWatchdog(value){this._sendToServerWatchdog=value}get keepaliveWatchdog(){return this._keepaliveWatchdog}set keepaliveWatchdog(value){this._keepaliveWatchdog=value}}exports.FootprintsProcess=FootprintsProcess;FootprintsProcess.ALARM_FIRED="alarm"})},{"../agent-events/agent-events-contracts":227,"../agent-events/agent-events-guard":229,"../agent-events/cockpit-notifier":234,"../constants/sl-env-vars":247,"../footprints-process/collection-interval":266,"../state-tracker":274,"./footprints-buffer":260}],264:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.formatLocation=void 0;function formatLocation(position,logger){if(position.hasOwnProperty("line")&&position.hasOwnProperty("column")){return position.line+","+position.column}else if(position.hasOwnProperty("l")&&position.hasOwnProperty("c")){return position.l+","+position.c}logger.error(`Position is not in a valid format got '${tryStringifyPosition(position)}', returning -1 for line and column`);return"-1,-1"}exports.formatLocation=formatLocation;function tryStringifyPosition(position){try{return JSON.stringify(position)}catch(e){`failed to stringify position '${e}'`}}})},{}],265:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RelativePathResolver=void 0;class RelativePathResolver{constructor(projectRoot){this.absoluteToRelativePath=new Map;this.projectRoot=projectRoot}getRelativePath(absolutePath){if(!this.absoluteToRelativePath.get(absolutePath)){absolutePath=this.adjustPathSlashes(absolutePath);let relativePath=absolutePath.replace(this.resolveProjectRoot(),"");if(relativePath.indexOf("/")===0){relativePath=relativePath.substring(1)}this.absoluteToRelativePath.set(absolutePath,relativePath)}return this.absoluteToRelativePath.get(absolutePath)}adjustPathSlashes(filePath){return(filePath||"").replace(/\\/g,"/")}resolveProjectRoot(){return(this.projectRoot||process.cwd()).replace(/\\/g,"/")}}exports.RelativePathResolver=RelativePathResolver})}).call(this)}).call(this,require("_process"))},{_process:162}],266:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CollectionInterval=void 0;const system_date_1=require("../system-date");class CollectionInterval{constructor(intervalInMS){this.intervalInSeconds=this.toSeconds(intervalInMS);this.start=this.toSeconds((0,system_date_1.getSystemDateValueOf)())}next(){if(this.end){this.start=this.end}this.end=this.toSeconds((0,system_date_1.getSystemDateValueOf)());if(this.end-this.start>this.intervalInSeconds){this.start=this.end-this.intervalInSeconds}}toJson(){return{start:this.start,end:this.end}}toSeconds(time){return Math.floor(time/1e3)}}exports.CollectionInterval=CollectionInterval})},{"../system-date":275}],267:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts","./sl-routes","../utils/validation-utils","./entities-mapper","../constants/constants","../utils/timer-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BackendProxy=void 0;const contracts_1=require("./contracts");const sl_routes_1=require("./sl-routes");const validation_utils_1=require("../utils/validation-utils");const entities_mapper_1=require("./entities-mapper");const constants_1=require("../constants/constants");const timer_utils_1=require("../utils/timer-utils");class BackendProxy{get httpMaxAttemps(){return this.config.httpMaxAttemps||BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS}get httpAttemptInterval(){return this.config.httpAttemptInterval||BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL}constructor(agentInstanceData,config,logger,client){this.agentInstanceData=agentInstanceData;this.config=config;this.logger=logger;this.client=client}getBuildSession(buildSessionId,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);const url=sl_routes_1.SLRoutes.buildSessionV2(buildSessionId);this.client.get(url,(err,body)=>{this.invokeCallback(callback,err,body)})}createBuildSessionId(request,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=sl_routes_1.SLRoutes.buildSessionV2();this.client.post(request,url,(err,body)=>{this.invokeCallback(callback,err,body,entities_mapper_1.EntitiesMapper.toCreateBuildSessionIdResponse)})}createBuildSessionIdPromise(request){return __awaiter(this,void 0,void 0,function*(){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=constants_1.Constants.PULL_REQUEST_PARAMS in request?sl_routes_1.SLRoutes.prBuildSession():sl_routes_1.SLRoutes.buildSessionV2();return new Promise((resolve,reject)=>{this.client.post(request,url,(err,body)=>{if(err){return reject(err)}return resolve(body)})})})}getRecommendedVersion(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=sl_routes_1.SLRoutes.recommendedAgentV2(request.componentName,request.customerId,request.appName,request.branchName,request.testStage);return new Promise((resolve,reject)=>{this.client.get(url,(err,body)=>{if(err){return reject(err)}else if(body&&body.agent&&body.agent){return resolve(body.agent)}else{return reject(new Error("Failed to get recommended version due to unexpected response from the server."))}})})}submitBuildMapping(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=sl_routes_1.SLRoutes.buildMappingV4();return this.submitPostRequestWithRetries(request,url)}submitLogs(request,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=sl_routes_1.SLRoutes.logSubmissionV2();this.client.post(request,url,(err,body)=>{this.invokeCallback(callback,err,body)})}getRemoteConfig(request,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);const url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,(err,body)=>{this.invokeCallback(callback,err,body)})}getRemoteConfigPromise(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);return new Promise((resolve,reject)=>{const url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,(err,body)=>{if(err){reject(err)}resolve(body)})})}startExecution(request,callback){const url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,(err,body)=>{this.invokeCallback(callback,err,body)})}startColoredExecution(request){return new Promise((resolve,reject)=>{const url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,err=>{if(err){reject(err)}resolve()})})}testExecutionV4(labId,async=true,executionId){return new Promise((resolve,reject)=>{const url=sl_routes_1.SLRoutes.testExecutionV4(labId);this.client.get(url,(err,body)=>{if(err){reject(err)}resolve(body)},false,async)})}uploadReport(request,callback){const url=sl_routes_1.SLRoutes.externalData();this.client.postMultipart(request,url,(err,body)=>{this.invokeCallback(callback,err,body)})}externalReport(request,callback){const url=sl_routes_1.SLRoutes.externalReport();this.client.post(request,url,(err,body)=>{this.invokeCallback(callback,err,body)})}endExecution(request,callback){const url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);const body=request.executionIds?{executionIds:request.executionIds}:null;this.client.delete(body,url,(err,body)=>{this.invokeCallback(callback,err,body)})}endExecutionPromise(request){const url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);const body=request.executionIds?{executionIds:request.executionIds}:null;return new Promise((resolve,reject)=>{this.client.delete(body,url,err=>{err?reject(err):resolve()})})}submitEvents(packetToSend,callback,async=true){const url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,callback)}submitEventsPromise(packetToSend){return new Promise((resolve,reject)=>{const url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,err=>{if(err){reject(err)}resolve()})})}submitBlobAsync(body,buildSessionId,blobId,blobType="unspecified"){const url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId,blobType);return new Promise((resolve,reject)=>{this.client.post(body,url,(error,statusCode)=>{this.logger.debug(`Blob ${blobId} uploaded with status code ${statusCode}`);if(error){this.logger.error(`Error while submitting a blob, '${error}'`);return reject(error)}else{this.logger.info("blob submitted successfully");return resolve({})}},true,contracts_1.ContentType.OCTET_STREAM)})}submitBlob(body,buildSessionId,blobId,callback){const url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);this.client.post(body,url,callback,true,contracts_1.ContentType.OCTET_STREAM)}getBlobsAsJson(buildSessionId,blobType="unspecified"){return __awaiter(this,void 0,void 0,function*(){let slMapping=[];try{const url=sl_routes_1.SLRoutes.blobsForBsidAsJson(buildSessionId,blobType);slMapping=yield this.submitGetRequestWithRetries(url)}catch(e){this.logger.error(e)}return slMapping})}getSlMappingFromServer(buildSessionId){return __awaiter(this,void 0,void 0,function*(){return this.getBlobsAsJson(buildSessionId,"unspecified")})}submitAgentEvent(body){const url=sl_routes_1.SLRoutes.agentEvents();return new Promise((resolve,reject)=>{this.client.post(body,url,(error,response)=>{if(error){return reject(error)}return resolve()})})}getTestsRecommendation(buildSessionId,stage,testGroupId){const url=sl_routes_1.SLRoutes.testsRecommendations(buildSessionId,stage,testGroupId);return this.submitGetRequestWithRetries(url,null,null,[400,404],false)}addOrUpdateIntegrationBuildComponents(buildSessionId,components,agentId){const url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitPutRequestWithRetries({components:components,agentId:agentId},url)}deleteIntegrationBuildComponents(buildSessionId,components,agentId){const url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitDelRequestWithRetries({components:components,agentId:agentId},url)}buildEnd(data){return this.submitPostRequestWithRetries(data,sl_routes_1.SLRoutes.buildEnd())}submitFootprintsV6(footprintsPacket,executionBsid,testStage,buildSessionId){return __awaiter(this,void 0,void 0,function*(){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(footprintsPacket,constants_1.Constants.FOOTPRINTS_PACKET);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(executionBsid,constants_1.Constants.EXECUTION_BSID);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(testStage,constants_1.Constants.TEST_STAGE);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);const url=sl_routes_1.SLRoutes.footprintsV6(executionBsid,testStage,buildSessionId);return this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.OCTET_STREAM)})}submitFootprintsToCollector(footprintsPacket,buildSessionId){return __awaiter(this,void 0,void 0,function*(){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(footprintsPacket,constants_1.Constants.FOOTPRINTS_PACKET);validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);const url=sl_routes_1.SLRoutes.footprintsToCollector(buildSessionId);return this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.JSON)})}getBuildSessionData(buildSessionId){return __awaiter(this,void 0,void 0,function*(){return new Promise((resolve,reject)=>{this.getBuildSession(buildSessionId,(err,response)=>{err?reject(err):resolve(response)})})})}getRecommendedAgent(configuration){return __awaiter(this,void 0,void 0,function*(){return{}})}getBuildSessionDataFromLabId(labid){return __awaiter(this,void 0,void 0,function*(){const url=sl_routes_1.SLRoutes.activeBuildSessionId(labid);return this.submitGetRequestWithRetries(url)})}updateMetadata(metadata){this.client.updateMetadata(metadata)}invokeCallback(callback,err,body,map){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,constants_1.Constants.CALLBACK);if(err!=null){return callback(err,body)}if(map==null){return callback(null,body)}const apiResponse=map(body);return callback(null,apiResponse)}submitPostRequestWithRetries(body,url,retries,delayBetweenRetires,async,contentType){return this.makeRequestWithRetries(callback=>{this.client.post(body,url,callback,async,contentType)},retries,delayBetweenRetires)}submitPutRequestWithRetries(body,url,retries,delayBetweenRetires){return this.makeRequestWithRetries(callback=>{this.client.put(body,url,callback)},retries,delayBetweenRetires)}submitDelRequestWithRetries(body,url,retries,delayBetweenRetires){return this.makeRequestWithRetries(callback=>{this.client.delete(body,url,callback)},retries,delayBetweenRetires)}submitGetRequestWithRetries(url,retries,delayBetweenRetires,statusesForRetry,isNotFoundAcceptable=true){return this.makeRequestWithRetries(callback=>{this.client.get(url,callback,isNotFoundAcceptable)},retries,delayBetweenRetires,statusesForRetry)}makeRequestWithRetries(doSingleRequest,retries,delayBetweenRetires,statusesForRetry){return __awaiter(this,void 0,void 0,function*(){let retriesLeft=retries||this.httpMaxAttemps;const intervalBetweenRetries=delayBetweenRetires||this.httpAttemptInterval;let lastError=undefined;do{try{retriesLeft--;const bodyAndStatusCode=yield new Promise((resolve,reject)=>{doSingleRequest((err,body,statusCode)=>{err?reject({err:err,statusCode:statusCode}):resolve({body:body,statusCode:statusCode})})});return bodyAndStatusCode.body}catch(errAndStatusCode){this.logger.info(errAndStatusCode);lastError=errAndStatusCode.err;if(!this.shouldRetryRequest(errAndStatusCode.statusCode,statusesForRetry)){break}}yield timer_utils_1.TimerUtils.sleep(intervalBetweenRetries)}while(retriesLeft>0);throw lastError})}shouldRetryRequest(statusCode,statusesForRetry=[]){if(statusCode>=500||statusCode&&statusesForRetry.includes(statusCode))return true;return false}}exports.BackendProxy=BackendProxy;BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS=6;BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL=5*1e3})},{"../constants/constants":246,"../utils/timer-utils":279,"../utils/validation-utils":280,"./contracts":268,"./entities-mapper":269,"./sl-routes":270}],268:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SealightsHaderValues=exports.SealightsHeaderNames=exports.ContentType=exports.RecommendationSetStatus=exports.RecommendedTestReason=exports.UploadReportsBody=exports.EnvironmentData=exports.AgentData=exports.UploadReportRequest=exports.EndExecutionRequest=exports.StartExecutionRequest=exports.BaseRequest=exports.SubmitLogsRequest=exports.GetRemoteConfigRequest=exports.FileData=exports.DependencyData=exports.BuildMappingRequest=exports.VersionMetaQuery=exports.VersionMeta=exports.AgentInfo=exports.GetVersionResponse=exports.GetVersionRequest=exports.CreateBuildSessionIdResponse=exports.SlAgentMetadata=exports.IHttpClientConfigData=void 0;const system_date_1=require("../system-date");class IHttpClientConfigData{}exports.IHttpClientConfigData=IHttpClientConfigData;class SlAgentMetadata{}exports.SlAgentMetadata=SlAgentMetadata;class CreateBuildSessionIdResponse{}exports.CreateBuildSessionIdResponse=CreateBuildSessionIdResponse;class GetVersionRequest{}exports.GetVersionRequest=GetVersionRequest;class GetVersionResponse{}exports.GetVersionResponse=GetVersionResponse;class AgentInfo{}exports.AgentInfo=AgentInfo;class VersionMeta{}exports.VersionMeta=VersionMeta;class VersionMetaQuery{}exports.VersionMetaQuery=VersionMetaQuery;class BuildMappingRequest{}exports.BuildMappingRequest=BuildMappingRequest;class DependencyData{}exports.DependencyData=DependencyData;class FileData{}exports.FileData=FileData;class GetRemoteConfigRequest{}exports.GetRemoteConfigRequest=GetRemoteConfigRequest;class SubmitLogsRequest{constructor(){this.creationTime=(0,system_date_1.getSystemDateValueOf)()}}exports.SubmitLogsRequest=SubmitLogsRequest;class BaseRequest{}exports.BaseRequest=BaseRequest;class StartExecutionRequest extends BaseRequest{}exports.StartExecutionRequest=StartExecutionRequest;class EndExecutionRequest extends BaseRequest{}exports.EndExecutionRequest=EndExecutionRequest;class UploadReportRequest extends BaseRequest{}exports.UploadReportRequest=UploadReportRequest;class AgentData{}exports.AgentData=AgentData;class EnvironmentData{}exports.EnvironmentData=EnvironmentData;class UploadReportsBody{}exports.UploadReportsBody=UploadReportsBody;var RecommendedTestReason;(function(RecommendedTestReason){RecommendedTestReason["PINNED"]="pinned";RecommendedTestReason["IMPACTED"]="impacted";RecommendedTestReason["FAILED"]="failed"})(RecommendedTestReason=exports.RecommendedTestReason||(exports.RecommendedTestReason={}));var RecommendationSetStatus;(function(RecommendationSetStatus){RecommendationSetStatus["NOT_READY"]="notReady";RecommendationSetStatus["READY"]="ready";RecommendationSetStatus["NO_HISTORY"]="noHistory";RecommendationSetStatus["ERROR"]="error";RecommendationSetStatus["WONT_BE_READY"]="wontBeReady"})(RecommendationSetStatus=exports.RecommendationSetStatus||(exports.RecommendationSetStatus={}));var ContentType;(function(ContentType){ContentType["OCTET_STREAM"]="application/octet-stream";ContentType["JSON"]="application/json"})(ContentType=exports.ContentType||(exports.ContentType={}));var SealightsHeaderNames;(function(SealightsHeaderNames){SealightsHeaderNames["CONTENT_TYPE"]="Content-Type";SealightsHeaderNames["AUTHOTIZARTION"]="Authorization";SealightsHeaderNames["MODE"]="X-Sealights-Agent-Mode";SealightsHeaderNames["META_DATA"]="sl-metadata";SealightsHeaderNames["LAB_ID"]="x-sl-labId";SealightsHeaderNames["APP_NAME"]="x-sl-appName";SealightsHeaderNames["BRANCH_NAME"]="x-sl-branchName";SealightsHeaderNames["BUILD_NAME"]="x-sl-buildName";SealightsHeaderNames["BSID"]="x-sl-bsid";SealightsHeaderNames["EXECUTION_ID"]="x-sl-executionId";SealightsHeaderNames["AGENT_ID"]="x-sl-agentId";SealightsHeaderNames["MESSAGE_TYPE"]="x-sl-messageType"})(SealightsHeaderNames=exports.SealightsHeaderNames||(exports.SealightsHeaderNames={}));var SealightsHaderValues;(function(SealightsHaderValues){SealightsHaderValues["LIGHT_AGENT_MODE"]="light"})(SealightsHaderValues=exports.SealightsHaderValues||(exports.SealightsHaderValues={}))})},{"../system-date":275}],269:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EntitiesMapper=void 0;const contracts_1=require("./contracts");class EntitiesMapper{static toCreateBuildSessionIdResponse(body){if(body==null)return null;const response=new contracts_1.CreateBuildSessionIdResponse;response.buildSessionId=body;return response}}exports.EntitiesMapper=EntitiesMapper})},{"./contracts":268}],270:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SLRoutes=void 0;const constants_1=require("../constants/constants");const validation_utils_1=require("../utils/validation-utils");class SLRoutes{static agentsV1(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)}static agentsV2(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.AGENTS)}static agentsV3(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.AGENTS)}static agentsV4(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.AGENTS)}static agentsV5(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V5)+SLRoutes.toUri(SLRoutes.AGENTS)}static agentsV6(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V6)+SLRoutes.toUri(SLRoutes.AGENTS)}static testExecution(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)}static testExecutionV4(labId,executionId){let url=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)+SLRoutes.toUri(labId);if(executionId){url+=SLRoutes.buildQueryParams({executionId:executionId})}return url}static endExecution(customerId,appName,buildName,branchName,environment){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(appName,"appName");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(customerId,"customerId");let result=SLRoutes.testExecution();const query={customerId:customerId,appName:appName,buildName:buildName,branchName:branchName,environment:environment};result+=SLRoutes.buildQueryParams(query);return result}static externalData(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.EXTERNAL_DATA)}static externalReport(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.EXTERNAL_REPORT)}static configV3(agentInstanceData,appName,branchName,buildName,testStage,labId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");let result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.CONFIG;const query={agentType:agentInstanceData.agentType,agentVersion:agentInstanceData.agentVersion,agentId:agentInstanceData.agentId};if(appName)query.appName=appName;if(branchName)query.branchName=branchName;if(buildName)query.buildName=buildName;if(testStage)query.testStage=testStage;if(labId)query.labId=labId;result+=SLRoutes.buildQueryParams(query);return result}static buildSessionV2(buildSessionId){const result=SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.BUILD_SESSION_ID)+SLRoutes.toUri(buildSessionId);return result}static prBuildSession(){return SLRoutes.buildSessionV2()+SLRoutes.toUri(SLRoutes.PULL_REQUEST)}static logSubmissionV2(){const result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.LOG_SUBMISSION;return result}static buildMappingV4(){const result=SLRoutes.agentsV4()+SLRoutes.toUri(SLRoutes.BUILD_MAPPING);return result}static footprintsV5(){const result=SLRoutes.agentsV5()+SLRoutes.toUri(SLRoutes.FOOTPRINTS);return result}static footprintsV6(executionBsid,testStage,buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(executionBsid)+SLRoutes.toUri(SLRoutes.FOOTPRINTS)+SLRoutes.toUri(testStage)+SLRoutes.toUri(buildSessionId)}static footprintsToCollector(buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(buildSessionId)+encodeURIComponent(SLRoutes.FOOTPRINTS)}static eventsV2(){return SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.EVENTS)}static productionV1(buildSessionId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,"buildSessionId");const result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)+SLRoutes.toUri(SLRoutes.PRODUCTION)+SLRoutes.toUri(SLRoutes.BSID)+SLRoutes.toUri(buildSessionId);return result}static recommendedAgentV2(component,customerId,appName,branchName,testStage){if(!component){throw new Error(`'component' ${constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED}.`)}let result=SLRoutes.agentsV2()+SLRoutes.toUri(component)+SLRoutes.toUri(SLRoutes.RECOMMENDED_VERSION);const query={customerId:customerId,appName:appName,branch:branchName,envName:testStage};result+=SLRoutes.buildQueryParams(query);return result}static blobs(buildSessionId,blobId,blobType){let route=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(blobId);if(blobType){route=route.slice(0,-1);route+=SLRoutes.buildQueryParams({blobType:blobType})}return route}static blobsForBsidAsJson(buildSessionId,blobType){let url=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId);url=url.slice(0,-1);return url+SLRoutes.buildQueryParams({view:"concatJson",blobType:blobType})}static agentEvents(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.AGENT_EVENTS)}static testsRecommendations(buildSessionId,stage,testGroupId){if(testGroupId===null||testGroupId===void 0?void 0:testGroupId.length){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)+SLRoutes.toUri(testGroupId)}return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)}static integrationBuildComponents(buildSessionId){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.AGENTS+SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.INTEGRATION_BUILDS)+SLRoutes.toUri(buildSessionId)+SLRoutes.COMPONENTS}static buildEnd(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.BUILD_END)}static activeBuildSessionId(labid){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.LAB_IDS)+SLRoutes.toUri(labid)+SLRoutes.toUri(SLRoutes.BUILD_SESSIONS)+SLRoutes.toUri(SLRoutes.ACTIVE)}static toUri(uri){if(uri==null||uri.length==null||uri.length===0){return""}return encodeURIComponent(uri)+SLRoutes.SLASH}static buildQueryParams(paramsMap){if(!paramsMap){throw new Error("'paramsMap' cannot be null or undefined.")}let queryString="";for(const key in paramsMap){const value=paramsMap[key];queryString+=SLRoutes.addQueryStringValue(key,value)}queryString="?"+queryString;queryString=queryString.substring(0,queryString.length-1);return queryString}static addQueryStringValue(key,value){if(!key&&!value)return"";if(!value){value=""}let paramString="";paramString+=encodeURIComponent(key);paramString+="=";paramString+=encodeURIComponent(value);paramString+="&";return paramString}}exports.SLRoutes=SLRoutes;SLRoutes.SLASH="/";SLRoutes.V1="v1";SLRoutes.V2="v2";SLRoutes.V3="v3";SLRoutes.V4="v4";SLRoutes.V5="v5";SLRoutes.V6="v6";SLRoutes.AGENTS="agents";SLRoutes.EVENTS="events";SLRoutes.PRODUCTION="productiondata";SLRoutes.BSID="bsid";SLRoutes.BUILD_SESSION_ID="buildsession";SLRoutes.BUILD_MAPPING="buildmapping";SLRoutes.RECOMMENDED_VERSION="recommended";SLRoutes.CONFIG="config";SLRoutes.LOG_SUBMISSION="logsubmission";SLRoutes.FOOTPRINTS="footprints";SLRoutes.TEST_EXECUTION="testExecution";SLRoutes.EXTERNAL_DATA="externaldata";SLRoutes.EXTERNAL_REPORT="externalreport";SLRoutes.BLOBS="blobs";SLRoutes.AGENT_EVENTS="agent-events";SLRoutes.PULL_REQUEST="pull-request";SLRoutes.TEST_EXCLUSIONS="test-exclusions";SLRoutes.INTEGRATION_BUILDS="integration-builds";SLRoutes.COMPONENTS="components";SLRoutes.BUILD_END="buildend";SLRoutes.LAB_IDS="lab-ids";SLRoutes.BUILD_SESSIONS="build-sessions";SLRoutes.ACTIVE="active"})},{"../constants/constants":246,"../utils/validation-utils":280}],271:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker-fpv6"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NoopStateTracker=void 0;const state_tracker_fpv6_1=require("./state-tracker-fpv6");class NoopStateTracker extends state_tracker_fpv6_1.StateTrackerFpv6{constructor(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){super(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger)}start(){}stop(){}getCollectHitsState(){return{shouldCollectHits:true}}startCheckingTestStatusAtServer(){}checkTestStatusAtServer(async=true){}get currentExecution(){return{}}}exports.NoopStateTracker=NoopStateTracker})},{"./state-tracker-fpv6":273}],272:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","fs","source-map"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SourceMapsUtils=void 0;const fs=require("fs");const sourceMap=require("source-map");class SourceMapsUtils{static readSourceMaps(fullFilename){if(!fullFilename)return;const sourceMapsFilename=fullFilename+".map";let contents,rawSourceMapJsonData,consumer;try{contents=fs.readFileSync(sourceMapsFilename).toString()}catch(e){return null}try{rawSourceMapJsonData=JSON.parse(contents)}catch(e){console.error("[Sealights] Ignoring invalid source map: "+sourceMapsFilename);return null}try{consumer=new sourceMap.SourceMapConsumer(rawSourceMapJsonData);return consumer}catch(e){console.error("[Sealights] Error processing source maps for file: "+sourceMapsFilename);return null}}}exports.SourceMapsUtils=SourceMapsUtils})},{fs:157,"source-map":174}],273:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","./state-tracker"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTrackerFpv6=void 0;const state_tracker_1=require("./state-tracker");class StateTrackerFpv6 extends state_tracker_1.StateTracker{switchToAnonFootprints(){}isAnonymousColor(testIdentifier){return testIdentifier==null}checkTestStatusAtServer(async=true){this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(response=>{this.fireExecutionEvents(response.execution);this.notifyCockpit(response.execution);this.currentExecution=response.execution}).catch(err=>{this.logger.warn(`Error while checking test execution status ${err}`)})}}exports.StateTrackerFpv6=StateTrackerFpv6})},{"./state-tracker":274}],274:[function(require,module,exports){var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events","./constants/sl-env-vars","./utils/validation-utils","./agent-events/cockpit-notifier","./agent-events/agent-events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;const events=require("events");const sl_env_vars_1=require("./constants/sl-env-vars");const validation_utils_1=require("./utils/validation-utils");const cockpit_notifier_1=require("./agent-events/cockpit-notifier");const agent_events_contracts_1=require("./agent-events/agent-events-contracts");const INITIAL_COLOR="00000000-0000-0000-0000-000000000000/__init";class StateTracker extends events.EventEmitter{constructor(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){super();this.cfg=cfg;this.configProcess=configProcess;this.checkTestStatusWatchdog=checkTestStatusWatchdog;this.backendProxy=backendProxy;this.logger=logger;this.currentTestIdentifier=null;this.isRunning=false;this._openExecutionFoundOnce=false;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(configProcess,"configProcess");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(checkTestStatusWatchdog,"watchdog");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(backendProxy,"backendProxy");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");if(this.cfg.useInitialColor.value&&this.currentTestIdentifier==null){this.switchToAnonFootprints()}configProcess.on("configuration_changed",newCfg=>{if(newCfg.useInitialColor.value&&this.currentTestIdentifier==null){this.switchToAnonFootprints()}this.cfg=newCfg;this.checkTestStatusWatchdog.setInterval(newCfg.executionQueryIntervalSecs.value)});this.startCheckingTestStatusAtServer()}startCheckingTestStatusAtServer(){if(sl_env_vars_1.SlEnvVars.inProductionListenerMode()){this.logger.debug("In production listener, no need to check test status in server");return}this.checkTestStatusWatchdog.on("alarm",()=>{this.checkTestStatusAtServer()});if(this.cfg.shouldCheckForActiveExecutionOnStartUp.value){this.checkTestStatusAtServer(false)}}checkTestStatusAtServer(async=true){if(!this.currentTestIdentifier){this.logger.info("'currentTestIdentifier' is null. That means that footprints will not be sent.")}else{this.getActiveExecution(async).then(response=>{this.fireExecutionEvents(response.execution);this.notifyCockpit(response.execution);this._currentExecution=response.execution}).catch(err=>{this.logger.warn(`Error while checking test execution status ${err}`)})}}loadExecutionSync(){return __awaiter(this,void 0,void 0,function*(){try{const executionResponse=yield this.getActiveExecution();this.fireExecutionEvents(executionResponse.execution);this.notifyCockpit(executionResponse.execution);this._currentExecution=executionResponse.execution}catch(err){this.logger.warn(`Error while checking test execution status ${err}`)}})}getActiveExecution(async=true){return this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery())}getExecutionIdForQuery(){if(this.isAnonymousColor(this.currentTestIdentifier)||!this.currentExecution){return null}return this.currentExecution.executionId}hasMappingAtServer(){return this._currentExecution!=null}getCollectHitsState(){var _a;const NO_EXECUTION_HITS_DATA={shouldCollectHits:false,reason:StateTracker.NO_ACTIVE_EXECUTION,message:"State tracker has no active execution, agent will not collect hits."};const PENDING_EXECUTION_DELETE_DATA={shouldCollectHits:false,reason:StateTracker.EXECUTION_STATUS_PENDING_DELETE,message:"State tracker active execution is currently pending for delete, agent will not collect hits."};if(!this.hasMappingAtServer()){return NO_EXECUTION_HITS_DATA}else if(((_a=this.currentExecution)===null||_a===void 0?void 0:_a.executionId)===this.pendingDeleteExecId){return PENDING_EXECUTION_DELETE_DATA}return{shouldCollectHits:true}}get currentExecution(){return this._currentExecution}set currentExecution(value){this._currentExecution=value}get openExecutionFoundOnce(){return this._openExecutionFoundOnce}isAnonymousColor(testIdentifier){return INITIAL_COLOR==testIdentifier}switchToAnonFootprints(){this.logger.info("Switching to anonymous footprints.");this.setTestIdentifier(INITIAL_COLOR,false)}getCurrentTestIdentifier(){return this.currentTestIdentifier}setTestIdentifier(newTestIdentifier,silent){this.logger.info("setting test identifier: "+newTestIdentifier);if(this.currentTestIdentifier==null&&newTestIdentifier!=null||this.currentTestIdentifier!=null&&this.currentTestIdentifier!=newTestIdentifier&&newTestIdentifier!=INITIAL_COLOR){const previousTestIdentifier=this.currentTestIdentifier;this.currentTestIdentifier=newTestIdentifier;if(this.isRunning){if(!silent){this.emit("test_identifier_changed",this.currentTestIdentifier,previousTestIdentifier)}else{this.logger.info("Test identifier changed, running in silent mode not enqueuing footprints")}this.checkTestStatusWatchdog.reset()}}else{this.logger.info("Not setting the color. newTestIdentifier is '"+newTestIdentifier+"' "+"and currentTestIdentifier is '"+this.currentTestIdentifier+"'")}}setCurrentTestIdentifier(newTestIdentifier){this.setTestIdentifier(newTestIdentifier)}start(){if(!this.isRunning){this.checkTestStatusWatchdog.start();this.isRunning=true}}stop(){try{if(!this.isRunning){return}this.checkTestStatusWatchdog.stop();this.isRunning=false}catch(err){this.logger.error(`Error while stopping StateTracker. '${err}'`);return}}getTestStage(){var _a;return(_a=this.currentExecution)===null||_a===void 0?void 0:_a.testStage}static splitTestIdToExecutionAndTestName(testId){testId=testId||"";const executionId=testId.split("/")[0];let testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId){testName=""}return{executionId:executionId,testName:testName}}static combineExecutionIdAndTestName(executionId,testName){testName=testName||"";if(!executionId){return""}return executionId+"/"+testName}startColoredExecution(executionId){return __awaiter(this,void 0,void 0,function*(){try{const request={appName:this.cfg.appName.value,branchName:this.cfg.branch.value,buildName:this.cfg.build.value,labId:this.cfg.labId.value,testStage:this.cfg.testStage.value,executionId:executionId};if(this.cfg.testGroupId.value){request.testGroupId=this.cfg.testGroupId.value}yield this.backendProxy.startColoredExecution(request);this.currentExecution=Object.assign(Object.assign({},request),{buildSessionId:this.cfg.buildSessionId.value,status:StateTracker.EXECUTION_STATUS_CREATED})}catch(e){this.logger.error(`Failed to create execution, error '${e}'. Footprints will not be sent`)}})}fireExecutionEvents(executionData){if(!executionData){return}if(executionData.status==StateTracker.EXECUTION_STATUS_PENDING_DELETE){if(executionData.executionId!==this.pendingDeleteExecId){this.currentExecution=executionData;this.emit(StateTracker.EXECUTION_STATUS_PENDING_DELETE,executionData);this.pendingDeleteExecId=executionData.executionId}return}if(!this.currentExecution){return}if(this.currentExecution.buildSessionId!=executionData.buildSessionId){this.emit(StateTracker.EXECUTION_BSID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.executionId!=executionData.executionId){this.emit(StateTracker.EXECUTION_ID_CHANGED,this.currentExecution,executionData.buildSessionId);return}if(this.currentExecution.testStage!=executionData.testStage){this.emit(StateTracker.TEST_STAGE_CHANGED,this.currentExecution,executionData.testStage);return}}notifyCockpit(execution){if(!execution){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_contracts_1.AgentEventCode.FIRST_TIME_NO_EXECUTION)}else{cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_contracts_1.AgentEventCode.FIRST_TIME_HAS_EXECUTION);this._openExecutionFoundOnce=true}}}exports.StateTracker=StateTracker;StateTracker.EXECUTION_ENDS="executionEnds";StateTracker.EXECUTION_BSID_CHANGED="executionBsidChanged";StateTracker.EXECUTION_ID_CHANGED="executionIdChanged";StateTracker.TEST_STAGE_CHANGED="testStageChanged";StateTracker.EXECUTION_STATUS_CREATED="created";StateTracker.EXECUTION_STATUS_PENDING_DELETE="pendingDelete";StateTracker.NO_ACTIVE_EXECUTION="noActiveExecution"})},{"./agent-events/agent-events-contracts":227,"./agent-events/cockpit-notifier":234,"./constants/sl-env-vars":247,"./utils/validation-utils":280,events:158}],275:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSystemDateValueOf=exports.getSystemDate=void 0;const SystemDate=Date;const SystemDateValueOf=Date.prototype.valueOf;function getSystemDate(){return new SystemDate}exports.getSystemDate=getSystemDate;function getSystemDateValueOf(){const date=getSystemDate();return SystemDateValueOf.call(date)}exports.getSystemDateValueOf=getSystemDateValueOf})},{}],276:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DataCleansingUtils=void 0;class DataCleansingUtils{static removeSensitiveData(request){if(request&&typeof request==="object"){const cloneRequest=Object.assign({},request);DataCleansingUtils.removeSensitiveDataForFieldsAccordingToPatternWithSideEffects(cloneRequest,DataCleansingUtils.sensitiveFieldPattern);return cloneRequest}return request}static removeSensitiveDataForFieldsAccordingToPatternWithSideEffects(request,pattern){Object.keys(request).forEach(fieldKey=>{if(request[fieldKey]){Object.keys(request[fieldKey]).forEach(key=>{if(!request[fieldKey][key])return;if(pattern.test(key)){if(typeof request[fieldKey][key]==="object"&&!Array.isArray(request[fieldKey][key])){request[fieldKey][key]={}}else if(Array.isArray(request[fieldKey][key])){request[fieldKey][key]=[]}else{request[fieldKey][key]=DataCleansingUtils.REMOVED_VALUE_TEXT}}});if(typeof request[fieldKey]==="object"){DataCleansingUtils.removeSensitiveDataForFieldsAccordingToPatternWithSideEffects(request[fieldKey],pattern)}}})}static removeSensitiveDataForFieldWithSideEffects(request,field){const fieldPath=field.split(".");let requestField=request;while(fieldPath.length&&requestField){const fieldPart=fieldPath.shift();if(!fieldPath.length&&requestField[fieldPart]){requestField[fieldPart]=DataCleansingUtils.REMOVED_VALUE_TEXT}else{requestField=requestField[fieldPart]}}}}exports.DataCleansingUtils=DataCleansingUtils;DataCleansingUtils.sensitiveFieldPattern=/\b(proxy|machineName|ipAddress|ci_dependency_proxy_server|ci_environment_url|ci_server_url|ci_server_host|ci_server_name|circle_repository_url|jenkins_url)\b/i;DataCleansingUtils.REMOVED_VALUE_TEXT="<real value removed due to security configuration>"})},{}],277:[function(require,module,exports){(function(process){(function(){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvVarParsing=void 0;class EnvVarParsing{static parseNumber(key){let valueFromEnv=process.env[key];if(valueFromEnv!=null){const valueAsNumber=Number.parseFloat(valueFromEnv);if(!isNaN(valueAsNumber)){valueFromEnv=valueAsNumber}else{valueFromEnv=null}}return valueFromEnv}static parseBoolean(key,defaultValue=false){var _a;const normalizedEnvVar=(_a=process.env[key])===null||_a===void 0?void 0:_a.toLowerCase();const isValidValue=normalizedEnvVar==="true"||normalizedEnvVar==="false";return isValidValue?normalizedEnvVar==="true":defaultValue}}exports.EnvVarParsing=EnvVarParsing})}).call(this)}).call(this,require("_process"))},{_process:162}],278:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","path","fs"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FilesUtils=void 0;const path=require("path");const fs=require("fs");class FilesUtils{static resolveOriginalFullFileName(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}const generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename}fixPathAndSpecialChar(path){if(path){if(path[0]==="/"||path[0]==="\\"){return path.substr(1).split("\\").join("/")}return path.split("\\").join("/")}return path}static adjustPathSlashes(filePath){filePath=(filePath||"").replace(/\\/g,"/");return filePath}static findFileUp(file,folder){const parsed=path.parse(folder);const filePath=path.join(folder,file);if(fs.existsSync(filePath)){return filePath}if(path.resolve(folder)===parsed.root||folder==="."){return null}let parentFolder=path.join(folder,"..");parentFolder=path.normalize(parentFolder);return FilesUtils.findFileUp(file,parentFolder)}}exports.FilesUtils=FilesUtils})},{fs:157,path:161}],279:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.TimerUtils=void 0;class TimerUtils{static sleep(timeout){return new Promise(resolve=>{setTimeout(resolve,timeout)})}}exports.TimerUtils=TimerUtils})},{}],280:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","../constants/constants"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ValidationUtils=void 0;const constants_1=require("../constants/constants");class ValidationUtils{static verifyNotNullOrEmpty(value,paramName){if(value===undefined||value===null){throw new Error(`${paramName} ${constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED}.`)}if(typeof value==="string"&&value.length===0){throw new Error(`${paramName} ${constants_1.Constants.Messages.CANNOT_BE_EMPTY_STRING}.`)}}static verifyNotNullOrEmptyMultiParams(params){for(const param of params){const{value,paramName}=param;ValidationUtils.verifyNotNullOrEmpty(value,paramName)}}}exports.ValidationUtils=ValidationUtils})},{"../constants/constants":246}],281:[function(require,module,exports){(function(factory){if(typeof module==="object"&&typeof module.exports==="object"){var v=factory(require,exports);if(v!==undefined)module.exports=v}else if(typeof define==="function"&&define.amd){define(["require","exports","events"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Watchdog=exports.WatchdogOptions=void 0;const events=require("events");class WatchdogOptions{}exports.WatchdogOptions=WatchdogOptions;class Watchdog extends events.EventEmitter{constructor(options,timers){super();this.options=options;this.timers=timers;this.handle=null;this.pendingAlarmDuringSuspended=false;this.suspended=false;this.stopped=true;if(!options){throw new Error("options is required")}if(!timers){throw new Error("timers is required")}}abort(){if(this.handle){this.timers.clearTimeout(this.handle);this.handle=null;this.pendingAlarmDuringSuspended=false}}reset(){this.abort();if(!this.stopped){this.handle=this.timers.setTimeout(this.fireAlarm.bind(this),this.options.interval);if(this.options.unref&&this.handle.unref){this.handle.unref()}}}stop(){this.stopped=true;this.abort()}start(){this.stopped=false;this.reset()}startIfNotRunning(){if(this.stopped||!this.handle){this.start()}}getStatus(){return{pendingAlarmDuringSuspended:this.pendingAlarmDuringSuspended,running:!this.stopped,suspended:this.suspended}}suspend(){this.suspended=true}resume(){this.suspended=false;if(this.pendingAlarmDuringSuspended){this.pendingAlarmDuringSuspended=false;this.fireAlarm()}}fireAlarm(){this.handle=null;if(this.suspended){this.pendingAlarmDuringSuspended=true}else{try{this.emit("alarm",this)}catch(err){}}if(this.options.autoReset){this.reset()}}setInterval(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.options.interval=newInterval}getInterval(){return this.options.interval}}exports.Watchdog=Watchdog})},{events:158}],282:[function(require,module,exports){var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function InvalidCharacterError(message){this.message=message}InvalidCharacterError.prototype=new Error;InvalidCharacterError.prototype.name="InvalidCharacterError";function polyfill(input){var str=String(input).replace(/=+$/,"");if(str.length%4==1){throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.")}for(var bc=0,bs,buffer,idx=0,output="";buffer=str.charAt(idx++);~buffer&&(bs=bc%4?bs*64+buffer:buffer,bc++%4)?output+=String.fromCharCode(255&bs>>(-2*bc&6)):0){buffer=chars.indexOf(buffer)}return output}module.exports=typeof window!=="undefined"&&window.atob&&window.atob.bind(window)||polyfill},{}],283:[function(require,module,exports){var atob=require("./atob");function b64DecodeUnicode(str){return decodeURIComponent(atob(str).replace(/(.)/g,function(m,p){var code=p.charCodeAt(0).toString(16).toUpperCase();if(code.length<2){code="0"+code}return"%"+code}))}module.exports=function(str){var output=str.replace(/-/g,"+").replace(/_/g,"/");switch(output.length%4){case 0:break;case 2:output+="==";break;case 3:output+="=";break;default:throw"Illegal base64url string!"}try{return b64DecodeUnicode(output)}catch(err){return atob(output)}}},{"./atob":282}],284:[function(require,module,exports){"use strict";var base64_url_decode=require("./base64_url_decode");function InvalidTokenError(message){this.message=message}InvalidTokenError.prototype=new Error;InvalidTokenError.prototype.name="InvalidTokenError";module.exports=function(token,options){if(typeof token!=="string"){throw new InvalidTokenError("Invalid token specified")}options=options||{};var pos=options.header===true?0:1;try{return JSON.parse(base64_url_decode(token.split(".")[pos]))}catch(e){throw new InvalidTokenError("Invalid token specified: "+e.message)}};module.exports.InvalidTokenError=InvalidTokenError},{"./base64_url_decode":283}],285:[function(require,module,exports){var v1=require("./v1");var v4=require("./v4");var uuid=v4;uuid.v1=v1;uuid.v4=v4;module.exports=uuid},{"./v1":288,"./v4":289}],286:[function(require,module,exports){var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+256).toString(16).substr(1)}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;return bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]}module.exports=bytesToUuid},{}],287:[function(require,module,exports){(function(global){(function(){var rng;var crypto=global.crypto||global.msCrypto;if(crypto&&crypto.getRandomValues){var rnds8=new Uint8Array(16);rng=function whatwgRNG(){crypto.getRandomValues(rnds8);return rnds8}}if(!rng){var rnds=new Array(16);rng=function(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;rnds[i]=r>>>((i&3)<<3)&255}return rnds}}module.exports=rng}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],288:[function(require,module,exports){var rng=require("./lib/rng");var bytesToUuid=require("./lib/bytesToUuid");var _seedBytes=rng();var _nodeId=[_seedBytes[0]|1,_seedBytes[1],_seedBytes[2],_seedBytes[3],_seedBytes[4],_seedBytes[5]];var _clockseq=(_seedBytes[6]<<8|_seedBytes[7])&16383;var _lastMSecs=0,_lastNSecs=0;function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;var msecs=options.msecs!==undefined?options.msecs:(new Date).getTime();var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;var tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;var node=options.node||_nodeId;for(var n=0;n<6;++n){b[i+n]=node[n]}return buf?buf:bytesToUuid(b)}module.exports=v1},{"./lib/bytesToUuid":286,"./lib/rng":287}],289:[function(require,module,exports){var rng=require("./lib/rng");var bytesToUuid=require("./lib/bytesToUuid");function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options=="binary"?new Array(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii]}}return buf||bytesToUuid(rnds)}module.exports=v4},{"./lib/bytesToUuid":286,"./lib/rng":287}]},{},[175]);