slnodejs 6.1.222 → 6.1.225
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.
- package/browser-agent/dist/browser-agent-all.js +90 -85
- package/browser-agent/dist/browser-agent-all.min.js +6 -6
- package/browser-agent/package.json +1 -1
- package/package.json +3 -3
- package/tsOutputs/build-scanner/build-diff-process.js +7 -2
- package/tsOutputs/build-scanner/build-diff-process.js.map +1 -1
- package/tsOutputs/build-scanner/instrumentation/browser-instrumenter.js +1 -1
- package/tsOutputs/build-scanner/instrumentation/browser-instrumenter.js.map +1 -1
- package/tsOutputs/build-scanner/instrumentation/file-instrumenter.js +12 -1
- package/tsOutputs/build-scanner/instrumentation/file-instrumenter.js.map +1 -1
- package/tsOutputs/cli-parse/cli.js +19 -0
- package/tsOutputs/cli-parse/cli.js.map +1 -1
- package/tsOutputs/cli-parse/executors/base-executor.js +4 -0
- package/tsOutputs/cli-parse/executors/base-executor.js.map +1 -1
- package/tsOutputs/cli-parse/executors/dry-run/dry-run-executor.js +1 -0
- package/tsOutputs/cli-parse/executors/dry-run/dry-run-executor.js.map +1 -1
- package/tsOutputs/common/agent-events/agent-instance-info-builder.js +1 -1
- package/tsOutputs/common/agent-events/agent-instance-info-builder.js.map +1 -1
- package/tsOutputs/common/agent-instance-data.js +2 -1
- package/tsOutputs/common/agent-instance-data.js.map +1 -1
- package/tsOutputs/common/constants/sl-env-vars.js +19 -19
- package/tsOutputs/common/constants/sl-env-vars.js.map +1 -1
- package/tsOutputs/common/http/http-client.d.ts +5 -1
- package/tsOutputs/common/http/http-client.js +16 -12
- package/tsOutputs/common/http/http-client.js.map +1 -1
- package/tsOutputs/common/ignored-files-handler.js +7 -2
- package/tsOutputs/common/ignored-files-handler.js.map +1 -1
- package/tsOutputs/common/utils/{parsing-utils.d.ts → env-var-parsing.d.ts} +1 -1
- package/tsOutputs/common/utils/{parsing-utils.js → env-var-parsing.js} +8 -8
- package/tsOutputs/common/utils/env-var-parsing.js.map +1 -0
- package/tsOutputs/common/utils/parsing-utils.js.map +0 -1
|
@@ -25,12 +25,12 @@ var configProcess=this.createConfigProcess(window,configuration,agentInstanceDat
|
|
|
25
25
|
;return __generator(this,function(_a){this.isRunning=false;this.sendToServerWatchdog.stop();if(this.configuration.enabled.value===false||this.configuration.sendEvents.value===false){return[2]}callback=function(err){if(err){_this.logger.error("Failed to submit final events, Error : '"+err+"'")}};while(this.eventsQueue.getQueueSize()>0){items=this.eventsQueue.dequeue(events_process_1.EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);this.backendProxy.submitEvents(packet,callback,false)}return[2]})})};return BrowserEventsProcess}(events_process_1.EventsProcess);exports.BrowserEventsProcess=BrowserEventsProcess})},{"../../common/events-process":314}],253:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var hits_collector_1=require("../../common/footprints-process-v6/hits-collector");var BrowserHitsCollector=function(_super){__extends(BrowserHitsCollector,_super);function BrowserHitsCollector(buildSessionId,logger,globalCoverageObject){var _this=_super.call(this,logger,globalCoverageObject)||this;_this.buildSessionId=buildSessionId;return _this}BrowserHitsCollector.prototype.getGlobalCoverageObject=function(){if(!this.globalCoverageObject){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.buildSessionId;this.globalCoverageObject=window[coverageObjectForBSID]||window[coverageObject]}return this.globalCoverageObject};return BrowserHitsCollector}(hits_collector_1.HitsCollector);exports.BrowserHitsCollector=BrowserHitsCollector})},{"../../common/footprints-process-v6/hits-collector":318}],254:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var base_browser_hits_converter_1=require("../../common/footprints-process-v6/base-browser-hits-converter");var BrowserHitsConverter=function(_super){__extends(BrowserHitsConverter,_super);function BrowserHitsConverter(relativePathResolver,window,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,buildSessionId,logger)||this;_this.window=window;return _this}BrowserHitsConverter.prototype.getSlMapping=function(){return this.window.slMappings[this.buildSessionId]||{}};return BrowserHitsConverter}(base_browser_hits_converter_1.BaseBrowserHitsConverter);exports.BrowserHitsConverter=BrowserHitsConverter})},{"../../common/footprints-process-v6/base-browser-hits-converter":315}],255:[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;var CodeCoverageManager=function(){function CodeCoverageManager(convertor,configuration){this.convertor=convertor;this.configuration=configuration;this.aggregatedCoverage={};this.isDestroyed=false}CodeCoverageManager.prototype.findCoverageContainer=function(){var coverageObject="$SealightsCoverage";var coverageObjectForBSID=coverageObject+"_"+this.configuration.buildSessionId;return window[coverageObjectForBSID]||window[coverageObject]};CodeCoverageManager.prototype.getFootprints=function(testInfo){var counters=this.getCounters(true);return this.convertor.convert(counters,testInfo.testName,testInfo.executionId)};CodeCoverageManager.prototype._clearCounters=function(istanbulCoverageObject){if(!istanbulCoverageObject)return;if(this.isDestroyed)return;var context=this;this.forEachProp(istanbulCoverageObject,function(moduleName,m){context.aggregatedCoverage[moduleName]=context.aggregatedCoverage[moduleName]||{s:{},b:{},f:{}};var 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(var 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})})};CodeCoverageManager.prototype.cloneCodeMetrics=function(o){var cloned={};for(var i in o){cloned[i]=this.cloneModule(o[i])}return cloned};CodeCoverageManager.prototype.cloneModule=function(m){var cm={b:{},f:{},s:{}};for(var i in m.s){cm.s[i]=m.s[i]}for(var i in m.f){cm.f[i]=m.f[i]}for(var 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};CodeCoverageManager.prototype.forEachProp=function(obj,func){Object.keys(obj).forEach(function(k){func(k,obj[k])})};CodeCoverageManager.prototype.clearCounters=function(){if(this.isDestroyed)return;var ct=this.findCoverageContainer();if(ct){this._clearCounters(ct)}};CodeCoverageManager.prototype.getCounters=function(clearAfterwards){if(this.isDestroyed)return{};var ct=this.findCoverageContainer();if(ct){var ret=this.cloneCodeMetrics(ct);if(clearAfterwards)this._clearCounters(ct);return ret}};return CodeCoverageManager}();exports.CodeCoverageManager=CodeCoverageManager})},{}],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","./state-tracker"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ColorCookieHandler=void 0;var state_tracker_1=require("./state-tracker");var ColorCookieHandler=function(){function ColorCookieHandler(window){this.window=window;this.COOKIE_KEY="x-sl-testid"}ColorCookieHandler.prototype.setCookie=function(color){var cookie=this.COOKIE_KEY+"="+color;this.window.document.cookie=cookie};ColorCookieHandler.prototype.handleColorChange=function(color){if(color!=null&&color!=state_tracker_1.StateTracker.ANONYMOUS_FOOTPRINTS_COLOR){this.setCookie(color)}else{this.removeCookie()}};ColorCookieHandler.prototype.removeCookie=function(){this.window.document.cookie=this.COOKIE_KEY+"=;expires=Thu, 01 Jan 1970 00:00:01 GMT;"};ColorCookieHandler.prototype.getCookie=function(){return this.window.document.cookie};return ColorCookieHandler}();exports.ColorCookieHandler=ColorCookieHandler})},{"./state-tracker":284}],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.SL_AGENT_TYPE=exports.SL_AGENT_VERSION=void 0;exports.SL_AGENT_VERSION="1.0.0";exports.SL_AGENT_TYPE="browser"})},{}],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","./entities/configuration-data"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigurationManager=void 0;var configuration_data_1=require("./entities/configuration-data");var ConfigurationManager=function(){function ConfigurationManager(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")}ConfigurationManager.prototype.getConfiguration=function(){if(this.currentConfiguration)return this.currentConfiguration;var configurationData=this.getDefaults();this.overrideConfiguration(configurationData);configurationData.labId=this.resolveLabId();this.currentConfiguration=configurationData;this.printConfiguration(configurationData);this.validateConfiguration(configurationData);return configurationData};ConfigurationManager.prototype.getDefaults=function(){var 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};ConfigurationManager.prototype.resolveLabId=function(){var 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"};ConfigurationManager.prototype.overrideConfiguration=function(configurationData){for(var p in this.basicConfiguration){configurationData[p]=this.basicConfiguration[p]}this.logger.info("[TO CS] - TODO: Send request to server to get the configuration.")};ConfigurationManager.prototype.printConfiguration=function(configurationData){this.logger.info("***********************************************************");this.logger.info("Current configuration:");this.logger.info("------------------------------------------------");for(var prop in configurationData){this.logger.info(prop+": '"+configurationData[prop])+"'"}this.logger.info("***********************************************************")};ConfigurationManager.prototype.validateConfiguration=function(configurationData){var _this=this;var 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(function(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};ConfigurationManager.prototype.isValidConfiguration=function(){return this._isValidConfiguration};ConfigurationManager.prototype.readLabIdFromSessionStorage=function(){var labId=null;if(this.window.sessionStorage&&typeof this.window.sessionStorage==="function"){labId=this.window.sessionStorage.getItem(ConfigurationManager.LAB_ID_KEY)}return labId};ConfigurationManager.prototype.readLabIdFromWindow=function(){return this.window[ConfigurationManager.LAB_ID_KEY]};ConfigurationManager.LAB_ID_KEY="__sl.labId__";return ConfigurationManager}();exports.ConfigurationManager=ConfigurationManager})},{"./entities/configuration-data":263}],259:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var EventEmitter=require("events");var console_logger_1=require("./logger/console-logger");var ConfigChangedEvents;(function(ConfigChangedEvents){ConfigChangedEvents["LOG_LEVEL_CHANGED"]="logLevelChanged"})(ConfigChangedEvents=exports.ConfigChangedEvents||(exports.ConfigChangedEvents={}));var ConfigurationOverride=function(_super){__extends(ConfigurationOverride,_super);function ConfigurationOverride(initialConfig){var _this=_super.call(this)||this;_this._logLevel=console_logger_1.LogLevels.INFO;_this.setMaxListeners(500);_this.loadInitialConfig(initialConfig);return _this}Object.defineProperty(ConfigurationOverride.prototype,"logLevel",{get:function(){return this._logLevel},set:function(value){this._logLevel=value;this.emit(ConfigChangedEvents.LOG_LEVEL_CHANGED,value)},enumerable:false,configurable:true});ConfigurationOverride.prototype.loadInitialConfig=function(initialConfig){if(initialConfig===void 0){initialConfig={}}for(var prop in initialConfig){var descriptor=Object.getOwnPropertyDescriptor(this.constructor.prototype,prop);if(descriptor&&typeof descriptor.set==="function"){this[prop]=initialConfig[prop]}}};ConfigurationOverride.create=function(configuration){if(configuration instanceof ConfigurationOverride){return configuration}return new ConfigurationOverride(configuration)};return ConfigurationOverride}(EventEmitter);exports.ConfigurationOverride=ConfigurationOverride})},{"./logger/console-logger":271,events:110}],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"],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={}))})},{}],261:[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;var Delegate=function(){function Delegate(){this.functions=new Array}Delegate.prototype.addListener=function(func){if(!func)return;if(this.functions)this.functions.push(func)};Delegate.prototype.fire=function(){if(!this.functions)return;for(var i=0;i<this.functions.length;i++){this.functions[i]()}};return Delegate}();exports.Delegate=Delegate})},{}],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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BasicConfigurationData=void 0;var BasicConfigurationData=function(){function BasicConfigurationData(){}return BasicConfigurationData}();exports.BasicConfigurationData=BasicConfigurationData})},{}],263:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var basic_configuation_data_1=require("./basic-configuation-data");var ConfigurationData=function(_super){__extends(ConfigurationData,_super);function ConfigurationData(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.registerShutdownHook=true;_this.enabled=true;return _this}return ConfigurationData}(basic_configuation_data_1.BasicConfigurationData);exports.ConfigurationData=ConfigurationData})},{"./basic-configuation-data":262}],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","../config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EnvironmentData=void 0;var config_1=require("../config");var EnvironmentData=function(){function EnvironmentData(){}EnvironmentData.create=function(configuration){var 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};return EnvironmentData}();exports.EnvironmentData=EnvironmentData})},{"../config":257}],265:[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;var FootprintsItemData=function(){function FootprintsItemData(){}return FootprintsItemData}();exports.FootprintsItemData=FootprintsItemData})},{}],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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FeatureDetection=void 0;var FeatureDetection=function(){function FeatureDetection(window){this.window=window;if(!window)throw new Error("'window' cannot be null or undefined")}FeatureDetection.prototype.hasBeaconAPI=function(){var result=window.navigator&&this.isFunction(window.navigator["sendBeacon"]);return result};FeatureDetection.prototype.hasConsoleLogAPI=function(){var result=window.console&&this.isFunction(window.console.log);return result};FeatureDetection.prototype.hasJsonAPI=function(){var result=JSON&&this.isFunction(JSON.stringify)&&this.isFunction(JSON.parse);return result};FeatureDetection.prototype.isFunction=function(o){return o&&typeof o==="function"};return FeatureDetection}();exports.FeatureDetection=FeatureDetection})},{}],267:[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","../../common/agent-events/cockpit-notifier"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsQueueSender=void 0;var footprints_item_data_1=require("./entities/footprints-item-data");var system_date_1=require("../../common/system-date");var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var FootprintsQueueSender=function(){function FootprintsQueueSender(watchdog,lightBackendProxy,codeCoverageManager,stateTracker,testStateHelper,environmentData,configuration,footprintsQueue,window,logger,slMappingLoader){var _this=this;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(function(){_this.context.onTimerTick()})}FootprintsQueueSender.prototype.onTimerTick=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.start=function(){if(this.isStarted)return;this.watchdog.start();this.slMappingLoader.loadSlMapping(this.configuration.buildSessionId);this.isStarted=true};FootprintsQueueSender.prototype.stop=function(){if(!this.isStarted)return;this.watchdog.stop();this.isStarted=false};FootprintsQueueSender.prototype.send=function(footprintsData,async,shouldRequeue){if(async===void 0){async=true}if(shouldRequeue===void 0){shouldRequeue=true}if(!footprintsData){this.logger.info("No need to send footprints as the 'footprintsData' is null or undefined.");return}var request=this.createRequest(footprintsData);if(request==null){this.logger.info("No need to send footprints as the request is empty.");return}var context=this;var onSuccess=function(){context.logger.info("Sent footprints successfully")};var 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)};FootprintsQueueSender.prototype.sendAllSync=function(){if(!this.stateTracker.shouldCollectFootprints()){return}this.logger.info("Sending all remaining footprints synchronously.");this.delayIfHasRequestsInProgress();var async=false;var footprints=this.getCurrentFootprints();this.send(footprints,async)};FootprintsQueueSender.prototype.sendAll=function(){var footprints=this.getCurrentFootprints();this.send(footprints)};FootprintsQueueSender.prototype.delayIfHasRequestsInProgress=function(){var 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)}};FootprintsQueueSender.prototype.pushCurrentFootprints=function(){if(!this.stateTracker.shouldCollectFootprints()){return}var testId=this.stateTracker.getCurrentTestIdentifier();var testInfo=this.testStateHelper.splitTestIdToExecutionAndTestName(testId);var footprints=this.codeCoverageManager.getFootprints(testInfo);if(this.configuration.resolveWithoutHash){this.enqueueV5Footprints(footprints)}else{this.enqueueV2Footprints(footprints,testInfo)}};FootprintsQueueSender.prototype.enqueueV2Footprints=function(appsAndFootprintsArray,testInfo){if(appsAndFootprintsArray&&appsAndFootprintsArray.length){var queueItem=new footprints_item_data_1.FootprintsItemData;queueItem.testName=testInfo.testName;queueItem.executionId=testInfo.executionId;queueItem.apps=appsAndFootprintsArray;this.footprintsQueue.enqueueItem(queueItem)}};FootprintsQueueSender.prototype.enqueueV5Footprints=function(footprintsRequest){if(!footprintsRequest)return;if(!footprintsRequest.apps||footprintsRequest.apps.length==0)return;if(!footprintsRequest.tests||footprintsRequest.tests.length==0)return;this.footprintsQueue.enqueueItem(footprintsRequest)};FootprintsQueueSender.prototype.getCurrentFootprints=function(){this.pushCurrentFootprints();var footprints=this.footprintsQueue.getQueueContentsAndEmptyQueue();return footprints};FootprintsQueueSender.prototype.createRequest=function(data){if(this.configuration.resolveWithoutHash){return this.createV5FootprintsRequest(data)}return this.createV2FootprintsRequest(data)};FootprintsQueueSender.prototype.createV5FootprintsRequest=function(footprintsData){var originalRequest=footprintsData[0];if(!originalRequest){return null}if(!this.hasApps(originalRequest)||!this.hasTests(originalRequest)){return null}var 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};FootprintsQueueSender.prototype.createV2FootprintsRequest=function(appsAndFootprintsArray){if(!appsAndFootprintsArray||!appsAndFootprintsArray.length){return null}var request={};request.customerId=this.configuration.customerId;request.items=appsAndFootprintsArray;request.environment=this.environmentData;request.configurationData=this.configuration;return request};FootprintsQueueSender.prototype.sleep=function(millis){var start=system_date_1.getSystemDateValueOf();var end=null;do{end=system_date_1.getSystemDateValueOf()}while(end-start<millis)};FootprintsQueueSender.prototype.hasApps=function(request){return request.apps&&request.apps.length>0};FootprintsQueueSender.prototype.hasTests=function(request){return request.tests&&request.tests.length>0};FootprintsQueueSender.prototype.loadSlMapping=function(){var _this=this;this.window.slMappings=this.window.slMappings||{};if(!this.window.slMappings[this.configuration.buildSessionId]){this.lightBackendProxy.getSlMappingFromServer(this.configuration.buildSessionId).then(function(mapping){return _this.window.slMappings[_this.configuration.buildSessionId]=mapping},function(err){var errMsg="Error while trying to load slMapping from server '"+err+"'";_this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);_this.window.slMappings[_this.configuration.buildSessionId]={}})}};return FootprintsQueueSender}();exports.FootprintsQueueSender=FootprintsQueueSender})},{"../../common/agent-events/cockpit-notifier":294,"../../common/system-date":333,"./entities/footprints-item-data":265}],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","./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;var log_factory_1=require("./logger/log-factory");var location_formatter_1=require("../../common/footprints-process-v6/location-formatter");var collection_interval_1=require("../../common/footprints-process/collection-interval");var system_date_1=require("../../common/system-date");var IstanbulToFootprintsConvertorV3=function(){function IstanbulToFootprintsConvertorV3(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")}IstanbulToFootprintsConvertorV3.prototype.resetState=function(){this.totalTests=0;this.eidToHitsIndex={};this.uniqueIdToElement={};this.testNameToTestData={};this.fileNameToAppFile={};this.collectionInterval.next()};IstanbulToFootprintsConvertorV3.prototype.convert=function(istanbulFootprints,testName,executionId,mockTime){this.resetState();var result=this.createFootprintsFile();var app=result.apps[0];var localTime=mockTime?mockTime:system_date_1.getSystemDateValueOf();var test=this.getOrCreateTestData(testName,executionId,localTime,result);for(var moduleName in istanbulFootprints){
|
|
26
26
|
var istanbulModule=istanbulFootprints[moduleName];if(!istanbulModule){continue}var 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};IstanbulToFootprintsConvertorV3.prototype.filterAppsWithoutHits=function(apps){var _this=this;if(!apps)return apps;return apps.filter(function(app){return _this.filterFilesWithoutHits(app)})};IstanbulToFootprintsConvertorV3.prototype.filterFilesWithoutHits=function(app){var _this=this;var hasFiles=false;if(!app||!app.files){return hasFiles}app.files=app.files.filter(function(file){return _this.filterElementsWithoutHits(file)});hasFiles=app.files.length>0;return hasFiles};IstanbulToFootprintsConvertorV3.prototype.filterElementsWithoutHits=function(file){var hasMethodHits=this.filterElementWithoutHits(file,"methods");var hasBranchHits=this.filterElementWithoutHits(file,"branches");var hasLineHits=this.filterElementWithoutHits(file,"lines");var hasHits=hasMethodHits||hasBranchHits||hasLineHits;return hasHits};IstanbulToFootprintsConvertorV3.prototype.filterElementWithoutHits=function(file,coverageType){var _this=this;var fileObject=file;var arrayOfCodeElements=fileObject[coverageType]||[];arrayOfCodeElements=arrayOfCodeElements.filter(function(ce){return _this.hasHit(ce)});fileObject[coverageType]=arrayOfCodeElements;var hasHits=arrayOfCodeElements.length>0;return hasHits};IstanbulToFootprintsConvertorV3.prototype.hasHit=function(element){var hasHitInAnyTest=element.hits.some(function(hitToTest){return hitToTest[1]>0});return hasHitInAnyTest};IstanbulToFootprintsConvertorV3.prototype.addMethodsWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var methodId in istanbulModule.f){var hits=istanbulModule.f[methodId];if(hits>0){var methodData=istanbulModule.fnMap[methodId];this.addOrUpdateMethodElement(scopeData,methodData,hits)}}};IstanbulToFootprintsConvertorV3.prototype.addBranchesWithHits=function(scopeData){var istanbulModule=scopeData.istanbulModule;for(var branchId in istanbulModule.b){var probesArray=istanbulModule.b[branchId];for(var idx=0;idx<probesArray.length;idx++){var hits=probesArray[idx];if(hits>0){var branchData=istanbulModule.branchMap[branchId];this.addOrUpdateBranchElement(scopeData,branchData,idx,hits)}}}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateMethodElement=function(scopeData,methodData,hits){var loc=methodData.loc||methodData.lc;var decl=methodData.decl||methodData.d;this.addOrUpdateElement(scopeData,loc,hits,this.getOrCreateMethodElement,false);if(decl){this.addOrUpdateElement(scopeData,decl,hits,this.getOrCreateMethodElement,false)}};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateBranchElement=function(scopeData,branchData,probeIndex,hits){var locations=branchData.locations||branchData.lcs;var probePositionData=locations[probeIndex];this.addOrUpdateElement(scopeData,probePositionData,hits,this.getOrCreateBranchElement,true,probeIndex)};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElement=function(scopeData,startPositionData,hits,getOrCreateElement,isBranch,probIndex){var file=this.getOrCreateFootprintsAppFile(scopeData.modulePath,scopeData.app);var startPosition=startPositionData.start||startPositionData.st;var uniqueId=this.createUniqueId(startPosition,scopeData.modulePath,isBranch,probIndex);if(!uniqueId){return}var element=getOrCreateElement.call(this,uniqueId,file);this.addOrUpdateElementHits(scopeData.test,uniqueId,element,hits)};IstanbulToFootprintsConvertorV3.prototype.createUniqueId=function(startPosition,fullFilePath,isBranch,probIndex){var delimiter=isBranch?"|":"@";var uniqueId=fullFilePath+delimiter+this.formatLoc(startPosition);if(probIndex!=null){uniqueId+="|"+probIndex}var mapping=this.window.slMappings[this.cfg.buildSessionId];if(mapping){uniqueId=mapping[uniqueId]||uniqueId}return uniqueId};IstanbulToFootprintsConvertorV3.prototype.addOrUpdateElementHits=function(testData,elementUniqueId,element,hits){var HITS_INDEX=1;var eid=elementUniqueId+"|"+testData.index;var index=this.eidToHitsIndex[eid];if(index!=null){var testIndexAndHits=element.hits[index];var elementHits=testIndexAndHits[HITS_INDEX];elementHits=elementHits+hits;testIndexAndHits[HITS_INDEX]=elementHits}else{var testIndexAndHits=new Array;testIndexAndHits.push(testData.index);testIndexAndHits.push(hits);var length_1=element.hits.push(testIndexAndHits);this.eidToHitsIndex[eid]=length_1-1}};IstanbulToFootprintsConvertorV3.prototype.getOrCreateTestData=function(testName,executionId,localTime,result){if(!this.testNameToTestData[testName]){var test_1={executionId:executionId,localTime:localTime,testName:testName,collectionInterval:this.collectionInterval.toJson()};result.tests.push(test_1);this.testNameToTestData[testName]={index:this.totalTests++,test:test_1}}return this.testNameToTestData[testName]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateMethodElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;file.methods.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateBranchElement=function(uniqueId,file){if(!this.uniqueIdToElement[uniqueId]){var x={hits:new Array,uniqueId:uniqueId};this.uniqueIdToElement[uniqueId]=x;if(file.branches)file.branches.push(x)}return this.uniqueIdToElement[uniqueId]};IstanbulToFootprintsConvertorV3.prototype.getOrCreateFootprintsAppFile=function(fileName,app){if(this.fileNameToAppFile[fileName]){return this.fileNameToAppFile[fileName]}var file={methods:new Array,branches:new Array,lines:new Array,path:fileName};app.files.push(file);this.fileNameToAppFile[fileName]=file;return file};IstanbulToFootprintsConvertorV3.prototype.createFootprintsFile=function(){var result={configurationData:{},customerId:this.cfg.customerId,environment:{},tests:[],apps:[],meta:{}};this.fileNameToAppFile={};this.testNameToTestData={};var 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};IstanbulToFootprintsConvertorV3.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};return IstanbulToFootprintsConvertorV3}();exports.IstanbulToFootprintsConvertorV3=IstanbulToFootprintsConvertorV3})},{"../../common/footprints-process-v6/location-formatter":321,"../../common/footprints-process/collection-interval":323,"../../common/system-date":333,"./logger/log-factory":272}],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","./utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.IstanbulToFootprintsConverter=void 0;var utils_1=require("./utils");var IstanbulToFootprintsConverter=function(){function IstanbulToFootprintsConverter(window,configuration){this.window=window;this.configuration=configuration;if(configuration==null)throw new Error("'configuration' cannot be null or undefined")}IstanbulToFootprintsConverter.prototype.convert=function(istanbulFootprints){var apps={};var appsArray=new Array;if(istanbulFootprints){var context_1=this;Object.keys(istanbulFootprints).forEach(function(moduleName){var m=istanbulFootprints[moduleName];context_1.configuration.appName=context_1.configuration.appName||"";var a=apps[context_1.configuration.appName];var isNewApp=false;if(!a){a={appName:context_1.configuration.appName,build:context_1.configuration.buildName,branch:context_1.configuration.branchName,footprints:[]};isNewApp=true}var footprints=a.footprints;var filename=m.path;filename=filename.replace(/\\/g,"/");Object.keys(m.f).forEach(function(funcId){var funcInfo=m.fnMap[funcId];if(!funcInfo||funcInfo.skip)return;if(m.f[funcId]>0){var mn=context_1.getMethodName(funcInfo.name,funcInfo.guessedName);var pos=context_1.formatLoc(funcInfo.loc.originalStart||funcInfo.loc.start);if(m.inputSourceMap&&context_1.window["sourceMap"]){var sourceMapConsumer=new context_1.window["sourceMap"].SourceMapConsumer(m.inputSourceMap);pos=context_1.formatLoc(sourceMapConsumer.originalPositionFor(funcInfo.loc.start))}filename=funcInfo.originalFilename||filename;filename=context_1.getRelativeModulePath(filename);var fqmn=[mn,filename,pos].join("@");var hash=funcInfo.hash&&funcInfo.hash.hash;var footprintsItem_1={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){var fileBranch=branchArray[0];var branchIndex=branchArray[1];if(m.b[fileBranch.toString()][branchIndex]>0){footprintsItem_1.branches.push(index)}})}footprints.push(footprintsItem_1)}});if(footprints.length&&isNewApp){appsArray.push(a);apps[a.appName]=a}})}return appsArray};IstanbulToFootprintsConverter.prototype.getMethodName=function(name,guessedName){var mn=name||guessedName||"(Anonymous)";if(mn.indexOf("(anonymous")>=0){mn="(Anonymous)"}return mn};IstanbulToFootprintsConverter.prototype.formatLoc=function(loc){return[loc.line,loc.column].join(",")};IstanbulToFootprintsConverter.prototype.getRelativeModulePath=function(path){var workspacepath=utils_1.Utils.adjustPathSlashes(this.configuration.workspacepath);path=utils_1.Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};return IstanbulToFootprintsConverter}();exports.IstanbulToFootprintsConverter=IstanbulToFootprintsConverter})},{"./utils":286}],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","./browser-agent-instance","../../common/utils/validation-utils","../../common/events-process/events-creator","../../common/events-process/events-contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.KarmaHandler=void 0;var browser_agent_instance_1=require("./browser-agent-instance");var validation_utils_1=require("../../common/utils/validation-utils");var events_creator_1=require("../../common/events-process/events-creator");var events_contracts_1=require("../../common/events-process/events-contracts");var KarmaHandler=function(){function KarmaHandler(window,agent,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(window,"window");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agent,"agent");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.window=window;this.agent=agent;this.logger=logger}KarmaHandler.prototype.overrideKarmaMethods=function(){if(!this.window.__karma__){this.logger.warn("Could not find '__karma__' object on window, skip overriding methods");return}var that=this;var originalResult=this.window.__karma__.result;var originalComplete=this.window.__karma__.complete;this.window.__karma__.result=function(resultObject){var testResult=that.resolveTestResult(resultObject);var testStartEvent=events_creator_1.EventsCreator.createTestStartedEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,resultObject.time);var testEndEvent=events_creator_1.EventsCreator.createTestEndEvent(browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma",resultObject.fullName,testResult,resultObject.time);that.agent.enqueueEvent(testStartEvent);that.agent.enqueueEvent(testEndEvent);var currentTestIdentifier=browser_agent_instance_1.BrowserAgentInstance.getExecutionId()+"/"+resultObject.fullName;that.agent.setCurrentTestIdentifier(currentTestIdentifier);if(originalResult instanceof Function){originalResult.apply(this,arguments)}};this.window.__karma__.complete=function(){var executionEndEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdEnded,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");that.agent.enqueueEvent(executionEndEvent);that.agent.stop();if(originalComplete instanceof Function){originalComplete.apply(this,arguments)}}};KarmaHandler.prototype.start=function(){var agentStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.AgentStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");var executionStartedEvent=events_creator_1.EventsCreator.createEvent(events_contracts_1.EventTypes.ExecutionIdStarted,browser_agent_instance_1.BrowserAgentInstance.getExecutionId(),"karma");this.agent.enqueueEvent(agentStartedEvent);this.agent.enqueueEvent(executionStartedEvent)};KarmaHandler.prototype.resolveTestResult=function(result){if(result.skipped){return"skipped"}if(result.success){return"passed"}return"failed"};return KarmaHandler}();exports.KarmaHandler=KarmaHandler})},{"../../common/events-process/events-contracts":312,"../../common/events-process/events-creator":313,"../../common/utils/validation-utils":337,"./browser-agent-instance":250}],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","../../../common/system-date","../configuration-override"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConsoleLogger=exports.LogLevels=void 0;var system_date_1=require("../../../common/system-date");var 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={}));var ConsoleLogger=function(){function ConsoleLogger(level,selectedLogLevels){if(level===void 0){level=LogLevels.INFO}if(selectedLogLevels===void 0){selectedLogLevels=null}var _a,_b;this.level=level;this.selectedLogLevels=selectedLogLevels;this.logFn=function(){};this.stringifyFn=function(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()}ConsoleLogger.prototype.withLogLevel=function(level){var c=new ConsoleLogger(this.level);c.context=this.context;return c};ConsoleLogger.prototype.initLogFn=function(){var _this=this;if(console&&typeof console.log=="function"){this.logFn=function(o){var line=_this.stringifyFn(o);console.log(line)}}else{}};ConsoleLogger.prototype.initStringifyFn=function(){if(JSON&&typeof JSON.stringify=="function"){this.stringifyFn=JSON.stringify}else{this.stringifyFn=this.crudeStringifier}};ConsoleLogger.prototype.crudeStringifier=function(o){var strParts=Array();for(var p in o){strParts.push(p+"="+o[p].toString())}return strParts.join(", ")};ConsoleLogger.prototype.initLogLevels=function(level){var orderedLogLevels=[LogLevels.TRACE,LogLevels.DEBUG,LogLevels.INFO,LogLevels.WARNING,LogLevels.ERROR,LogLevels.CRITICAL,LogLevels.FATAL];var logLevel=level.toLowerCase();var minIdx=orderedLogLevels.indexOf(logLevel);if(minIdx===-1){this.handleLevelNotFound(level)}else{this.selectedLogLevels={};for(var i=0;i<orderedLogLevels.length;i++){this.selectedLogLevels[orderedLogLevels[i]]=i>=minIdx}}};ConsoleLogger.prototype.handleLevelNotFound=function(logLevel){if(logLevel=="off"){this.selectedLogLevels={}}};ConsoleLogger.prototype.internalLog=function(logLevel,logMsg,obj){if(!this.selectedLogLevels||!this.selectedLogLevels[logLevel])return;var logObject={level:logLevel.toUpperCase(),ts:system_date_1.getSystemDate().toISOString(),msg:logMsg?logMsg.toString():undefined};var ctx=this.context;for(var p in ctx){logObject[p]=ctx[p]}if(obj){if(obj instanceof Error){logObject.error=obj.toString()}else if(obj instanceof Object){for(var p in obj){logObject[p]=obj[p]}}else{logObject.data=obj}}this.logFn(logObject)};ConsoleLogger.prototype.clone=function(){var c=new ConsoleLogger(this.level,this.selectedLogLevels);var _t=this.context;for(var p in _t){c.context[p]=_t[p]}return c};ConsoleLogger.prototype.withClass=function(className){var c=this.clone();c.context.className=className;delete c.context.methodName;return c};ConsoleLogger.prototype.withMethod=function(methodName){var c=this.clone();c.context.methodName=methodName;return c};ConsoleLogger.prototype.withTx=function(tx){var c=this.clone();c.context.tx=tx;return c};ConsoleLogger.prototype.withComponent=function(componentName,componentVersion){var c=this.clone();c.context.componentName=componentName;c.context.componentVersion=componentVersion;return c};ConsoleLogger.prototype.withActivity=function(activityName){var c=this.clone();c.context.activityName=activityName;return c};ConsoleLogger.prototype.withProperty=function(propName,propValue){var c=this.clone();c.context[propName]=propValue;return c};ConsoleLogger.prototype.withProperties=function(objWithProperties,propNames){var c=this.clone();if(!propNames){propNames=Object.keys(objWithProperties)}propNames.forEach(function(pn){c.context[pn]=objWithProperties[pn]});return c};ConsoleLogger.prototype.fatal=function(logMsg,obj){this.internalLog(LogLevels.FATAL,logMsg,obj)};ConsoleLogger.prototype.critical=function(logMsg,obj){this.internalLog(LogLevels.CRITICAL,logMsg,obj)};ConsoleLogger.prototype.error=function(logMsg,obj){this.internalLog(LogLevels.ERROR,logMsg,obj)};ConsoleLogger.prototype.warn=function(logMsg,obj){this.internalLog(LogLevels.WARNING,logMsg,obj)};ConsoleLogger.prototype.info=function(logMsg,obj){this.internalLog(LogLevels.INFO,logMsg,obj)};ConsoleLogger.prototype.debug=function(logMsg,obj){this.internalLog(LogLevels.DEBUG,logMsg,obj)};ConsoleLogger.prototype.trace=function(logMsg,obj){this.internalLog(LogLevels.TRACE,logMsg,obj)};return ConsoleLogger}();exports.ConsoleLogger=ConsoleLogger})},{"../../../common/system-date":333,"../configuration-override":259}],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","./null-logger","./console-logger"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LogFactory=void 0;var null_logger_1=require("./null-logger");var console_logger_1=require("./console-logger");var LogFactory=function(){function LogFactory(){}LogFactory.createLogger=function(className,logLevel){try{var logger=new console_logger_1.ConsoleLogger(logLevel);logger.withClass(className);return logger}catch(e){return null_logger_1.NullLogger.INSTANCE}};return LogFactory}();exports.LogFactory=LogFactory})},{"./console-logger":271,"./null-logger":273}],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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NullLogger=void 0;var NullLogger=function(){function NullLogger(){}NullLogger.prototype.fatal=function(logMsg,obj){};NullLogger.prototype.critical=function(logMsg,obj){};NullLogger.prototype.error=function(logMsg,obj){};NullLogger.prototype.warn=function(logMsg,obj){};NullLogger.prototype.info=function(logMsg,obj){};NullLogger.prototype.debug=function(logMsg,obj){};NullLogger.prototype.trace=function(logMsg,obj){};NullLogger.prototype.withClass=function(className){return NullLogger.INSTANCE};NullLogger.prototype.withMethod=function(methodName){return NullLogger.INSTANCE};NullLogger.prototype.withTx=function(tx){return NullLogger.INSTANCE};NullLogger.prototype.withComponent=function(componentName,componentVersion){return NullLogger.INSTANCE};NullLogger.prototype.withActivity=function(activityName){return NullLogger.INSTANCE};NullLogger.prototype.withProperty=function(propName,propValue){return NullLogger.INSTANCE};NullLogger.prototype.withProperties=function(objWithProperties,propNames){return NullLogger.INSTANCE};NullLogger.prototype.withLogLevel=function(level){return NullLogger.INSTANCE};NullLogger.INSTANCE=new NullLogger;return NullLogger}();exports.NullLogger=NullLogger})},{}],274:[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;var footprints_item_data_1=require("../entities/footprints-item-data");var delegate_1=require("../delegate");var system_date_1=require("../../../common/system-date");var FootprintsItemsQueue=function(){function FootprintsItemsQueue(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}FootprintsItemsQueue.prototype.setEnabled=function(isEnabled){isEnabled=!!isEnabled;if(isEnabled!==this.enabled){this.enabled=isEnabled}if(!isEnabled){this.queue=new Array}};FootprintsItemsQueue.prototype.getEnabled=function(){return this.enabled};FootprintsItemsQueue.prototype.enqueueItem=function(footprintsItem){if(!this.enabled){return}footprintsItem=footprintsItem||new footprints_item_data_1.FootprintsItemData;footprintsItem.localTime=system_date_1.getSystemDateValueOf();this.queue.push(footprintsItem);this.queueSize++;this.checkQueueSize()};FootprintsItemsQueue.prototype.checkQueueSize=function(){if(this.isQueueFull()){this.onQueueFull.fire()}};FootprintsItemsQueue.prototype.getCurrentQueueSize=function(){return this.queueSize};FootprintsItemsQueue.prototype.requeueItems=function(footprintsItems){if(!this.enabled){return}var context=this;footprintsItems.forEach(function(item){context.queue.push(item);context.queueSize+=1});this.checkQueueSize()};FootprintsItemsQueue.prototype.getQueueContentsAndEmptyQueue=function(){var returnedItems=this.queue;this.queue=new Array;this.queueSize=0;return returnedItems};return FootprintsItemsQueue}();exports.FootprintsItemsQueue=FootprintsItemsQueue})},{"../../../common/system-date":333,"../delegate":261,"../entities/footprints-item-data":265}],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","../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Queue=void 0;var validation_utils_1=require("../../../common/utils/validation-utils");var Queue=function(){function Queue(onQueueFull){this.queue=[];this._maxItemsInQueue=Queue.DEFAULT_MAX_ITEMS_IN_QUEUE;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(onQueueFull,"onQueueFull");this.onQueueFull=onQueueFull}Queue.prototype.requeue=function(items){if(!items||!items.length){return}this.queue=items.concat(this.queue)};Queue.prototype.enqueue=function(item){this.queue.push(item);if(this._maxItemsInQueue===this.queue.length){this.onQueueFull.fire()}};Queue.prototype.getQueueSize=function(){return this.queue.length};Queue.prototype.dequeue=function(size){if(!size){size=this.queue.length}if(this.queue.length===0){return[]}if(size>this.queue.length){size=this.queue.length}var dequeuedItems=this.queue.splice(0,size);return dequeuedItems};Queue.prototype.clear=function(){this.queue=[]};Queue.prototype.on=function(event,listener){this.onQueueFull.addListener(listener);return this};Object.defineProperty(Queue.prototype,"maxItemsInQueue",{get:function(){return this._maxItemsInQueue},set:function(value){this._maxItemsInQueue=value},enumerable:false,configurable:true});Queue.DEFAULT_MAX_ITEMS_IN_QUEUE=1e3;return Queue}();exports.Queue=Queue})},{"../../../common/utils/validation-utils":337}],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","./http-response"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var http_response_1=require("./http-response");var HttpClient=function(){function HttpClient(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")}HttpClient.prototype.send=function(request,onSuccess,onError){if(!request.url)return;var url=request.url;var httpMethod=request.httpMethod;var httpRequest=new XMLHttpRequest;httpRequest.open(httpMethod,url,request.async);if(request.headers){for(var i=0;i<request.headers.length;i++){var header=request.headers[i];if(header&&header.name&&header.value){httpRequest.setRequestHeader(header.name,header.value)}}}httpRequest.onreadystatechange=function(){if(httpRequest.readyState===XMLHttpRequest.DONE){var 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)};return HttpClient}();exports.HttpClient=HttpClient})},{"./http-response":278}],277:[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;var HttpRequest=function(){function HttpRequest(){this.async=true}return HttpRequest}();exports.HttpRequest=HttpRequest})},{}],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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpResponse=void 0;var HttpResponse=function(){function HttpResponse(){}return HttpResponse}();exports.HttpResponse=HttpResponse})},{}],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","../../../../common/utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClientAdapter=void 0;var validation_utils_1=require("../../../../common/utils/validation-utils");var JsonClientAdapter=function(){function JsonClientAdapter(jsonClient,serverUrl){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(jsonClient,"jsonClient");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(serverUrl,"serverUrl");this.jsonClient=jsonClient;this.serverUrl=serverUrl}JsonClientAdapter.prototype.delete=function(body,urlPath,callback){throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.get=function(urlPath,callback,isNotFoundAcceptable,async){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}if(async===void 0){async=false}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.get(urlPath,onSuccess,onError,async)};JsonClientAdapter.prototype.put=function(requestData,urlPath,callback,async){if(async===void 0){async=true}throw new Error("'delete' not implemented yet")};JsonClientAdapter.prototype.post=function(requestData,urlPath,callback,async,contentType){if(async===void 0){async=true}urlPath=this.serverUrl+urlPath;var onSuccess=function(response){return callback(null,response,response.statusCode)};var onError=function(response){var error=new Error(response.responseText);callback(error,null,response.statusCode)};this.jsonClient.post(urlPath,requestData,onSuccess,onError,async,contentType)};JsonClientAdapter.prototype.postMultipart=function(requestData,urlPath,callback){throw new Error("'postMultipart' not implemented yet")};return JsonClientAdapter}();exports.JsonClientAdapter=JsonClientAdapter})},{"../../../../common/utils/validation-utils":337}],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","../http/http-request","../../../../common/http/contracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.JsonClient=void 0;var http_request_1=require("../http/http-request");var contracts_1=require("../../../../common/http/contracts");var JsonClient=function(){function JsonClient(httpClient,configuration,agentInstanceData){this.httpClient=httpClient;this.configuration=configuration;this.agentInstanceData=agentInstanceData;this.requestsInProgress=0;this.requestsInProgress=0}JsonClient.prototype.sendHttpRequest=function(request,onSuccess,onError,contentType){var context=this;try{this.requestsInProgress++;var httpRequest=new http_request_1.HttpRequest;httpRequest.headers=this.getHeaders(contentType);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{var object=void 0;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)}}}}
|
|
27
27
|
;JsonClient.prototype.post=function(url,data,onSuccess,onError,async,contentType){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"POST",contentType)};JsonClient.prototype.get=function(url,onSuccess,onError,async,data){if(async===void 0){async=true}this.send(url,data,onSuccess,onError,async,"GET")};JsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}var request=new http_request_1.HttpRequest;request.url=url;request.data=data;request.httpMethod=httpMethod;request.async=async;this.sendHttpRequest(request,onSuccess,onError,contentType)};JsonClient.prototype.hasRequestsInProgress=function(){return this.requestsInProgress>0};JsonClient.prototype.getHeaders=function(contentType){var _a,_b;var headers=[{name:"Content-Type",value:contentType||contracts_1.ContentType.JSON}];headers.push({name:"sl-metadata",value:JSON.stringify(this.getSlMetadataHeaders())});if((_a=this===null||this===void 0?void 0:this.configuration)===null||_a===void 0?void 0:_a.token){headers.push({name:"Authorization",value:"Bearer "+((_b=this===null||this===void 0?void 0:this.configuration)===null||_b===void 0?void 0:_b.token)})}return headers};JsonClient.prototype.getSlMetadataHeaders=function(){var _a;return{agentId:this.agentInstanceData.agentId,buildSessionId:(_a=this.configuration)===null||_a===void 0?void 0:_a.buildSessionId,agentType:"browser"}};return JsonClient}();exports.JsonClient=JsonClient})},{"../../../../common/http/contracts":325,"../http/http-request":277}],281:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var json_client_1=require("./json-client");var log_factory_1=require("../../logger/log-factory");var NoopJsonClient=function(_super){__extends(NoopJsonClient,_super);function NoopJsonClient(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.logger=log_factory_1.LogFactory.createLogger("NoopJsonClient");return _this}NoopJsonClient.prototype.send=function(url,data,onSuccess,onError,async,httpMethod,contentType){if(async===void 0){async=true}this.logger.info("noop json client not executing http request for url '"+url);onSuccess({})};return NoopJsonClient}(json_client_1.JsonClient);exports.NoopJsonClient=NoopJsonClient})},{"../../logger/log-factory":272,"./json-client":280}],282:[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;var LightBackendProxy=function(){function LightBackendProxy(configuration,jsonClient,logger){this.configuration=configuration;this.jsonClient=jsonClient;this.logger=logger}LightBackendProxy.prototype.submitRequest=function(request,onSuccess,onError,async){if(async===void 0){async=true}var url=this.createServerUrl(this.configuration);this.jsonClient.post(url,request,onSuccess,onError,async)};LightBackendProxy.prototype.hasRequestsInProgress=function(){return this.jsonClient.hasRequestsInProgress()};LightBackendProxy.prototype.getRequestsInProgressCount=function(){return this.jsonClient.requestsInProgress};LightBackendProxy.prototype.getSlMappingFromServer=function(buildSessionId){var _this=this;var url=[this.configuration.server,"v1","agents","blobs",buildSessionId].join("/")+"?view=concatJson";url=encodeURI(url);return new Promise(function(resolve,reject){_this.jsonClient.get(url,resolve,reject,false)})};LightBackendProxy.prototype.createServerUrl=function(configuration){if(configuration.token){var apiVersion=configuration.resolveWithoutHash?"/v5":"/v3";return configuration.server+apiVersion+"/agents/footprints/"}return configuration.server+"/v1/testfootprints/"};return LightBackendProxy}();exports.LightBackendProxy=LightBackendProxy})},{}],283:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlMappingLoader=void 0;var cockpit_notifier_1=require("../../common/agent-events/cockpit-notifier");var SlMappingLoader=function(){function SlMappingLoader(lightBackendProxy,window,logger){this.lightBackendProxy=lightBackendProxy;this.window=window;this.logger=logger}SlMappingLoader.prototype.loadSlMapping=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var flatted_1,slMappingArr,err_1,errMsg;return __generator(this,function(_a){switch(_a.label){case 0:this.window.slMappings=this.window.slMappings||{};if(!!this.window.slMappings[buildSessionId])return[3,4];_a.label=1;case 1:_a.trys.push([1,3,,4]);flatted_1={};return[4,this.lightBackendProxy.getSlMappingFromServer(buildSessionId)];case 2:slMappingArr=_a.sent();slMappingArr.forEach(function(mapping){flatted_1=__assign(__assign({},flatted_1),mapping)});this.window.slMappings[buildSessionId]=flatted_1;return[3,4];case 3:err_1=_a.sent();errMsg="Error while trying to load slMapping from server '"+err_1+"'";this.logger.error(errMsg);cockpit_notifier_1.CockpitNotifier.sendGenericMessage(errMsg);this.window.slMappings[buildSessionId]={};return[3,4];case 4:return[2]}})})};return SlMappingLoader}();exports.SlMappingLoader=SlMappingLoader})},{"../../common/agent-events/cockpit-notifier":294}],284:[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;var delegate_1=require("./delegate");var contracts_1=require("./contracts");var StateTracker=function(){function StateTracker(configuration,jsonClient,watchdog,logger){var _this=this;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(function(){_this.checkForActiveExecution()});this.checkForActiveExecution(false);this.watchdog.start()}StateTracker.prototype.setCurrentTestIdentifier=function(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()}};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentColorOnWindow};StateTracker.prototype.addOnColorChangedListener=function(listener){this.colorChanged.addListener(listener)};StateTracker.prototype.getCurrentColor=function(){return this.currentColorOnWindow};StateTracker.prototype.checkForActiveExecution=function(async){var _this=this;if(async===void 0){async=true}var url=this.configuration.server+("/v4/testExecution/"+this.configuration.labId);this.logger.info("[TO TST] - checkMappingStatus. Url '"+url+"'.");var onSuccess=function(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}};var onError=function(response){_this.logger.error("[ACTIVE EXECUTION] Error checking for active execution: %s",response.responseText);_this.hasActiveExecution=false};this.jsonClient.get(url,onSuccess,onError,async)};StateTracker.prototype.shouldCollectFootprints=function(){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};StateTracker.prototype.setActiveExecution=function(value){this.hasActiveExecution=value};StateTracker.prototype.stopWatchdog=function(){if(this.watchdog.getStatus().running){this.watchdog.stop()}};StateTracker.prototype.startWatchdog=function(){if(!this.watchdog.getStatus().running){this.watchdog.start()}};StateTracker.ANONYMOUS_FOOTPRINTS_COLOR="00000000-0000-0000-0000-000000000000/__init";return StateTracker}();exports.StateTracker=StateTracker})},{"./contracts":260,"./delegate":261}],285:[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;var TestStateHelper=function(){function TestStateHelper(){this.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId)return"";return executionId+"/"+testName};this.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId)testName="";return{executionId:executionId,testName:testName}}}return TestStateHelper}();exports.TestStateHelper=TestStateHelper})},{}],286:[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;var path=require("path");var Utils=function(){function Utils(){}Utils.adjustPathSlashes=function(path){path=(path||"").replace(/\\/g,"/");return path};Utils.getRelativeModulePath=function(path,workspacepath){workspacepath=Utils.adjustPathSlashes(workspacepath);path=Utils.adjustPathSlashes(path);if(workspacepath){return path.replace(workspacepath,"")}return path};Utils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};Utils.parseBooleanValue=function(value){if(value&&typeof value=="boolean"){return value}if(value&&typeof value=="string"){return value.toLowerCase()=="true"}return false};return Utils}();exports.Utils=Utils})},{path:171}],287:[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;var delegate_1=require("./delegate");var Watchdog=function(){function Watchdog(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||{}}Watchdog.prototype.abortTimer=function(){if(this.handle){this.timersWrapper.clearTimeout(this.handle);this.handle=null}};Watchdog.prototype.fireAlarm=function(){this.handle=null;try{this.alarm.fire()}catch(e){this.logger.error("Alarm caught an exception: ",e)}if(this.options.autoReset){this.context.reset()}};Watchdog.prototype.addOnAlarmListener=function(listener){this.alarm.addListener(listener)};Watchdog.prototype.reset=function(){var _this=this;this.abortTimer();if(!this.stopped){this.handle=this.timersWrapper.setTimeout(function(){_this.fireAlarm()},this.timeout)}};Watchdog.prototype.stop=function(){this.stopped=true;this.abortTimer()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{running:!this.stopped}};Watchdog.prototype.on=function(event,listener){this.addOnAlarmListener(listener)};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.timeout=newInterval};return Watchdog}();exports.Watchdog=Watchdog})},{"./delegate":261}],288:[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;var WindowTimersWrapper=function(){function WindowTimersWrapper(window){this.window=window;if(!this.window)throw new Error("'window' cannot be null or undefined")}WindowTimersWrapper.prototype.clearInterval=function(handle){this.window.clearInterval(handle)};WindowTimersWrapper.prototype.clearTimeout=function(handle){this.window.clearTimeout(handle)};WindowTimersWrapper.prototype.setInterval=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setInterval(handler,timeout,args)};WindowTimersWrapper.prototype.setTimeout=function(handler,timeout){var args=[];for(var _i=2;_i<arguments.length;_i++){args[_i-2]=arguments[_i]}return this.window.setTimeout(handler,timeout,args)};return WindowTimersWrapper}();exports.WindowTimersWrapper=WindowTimersWrapper})},{}],289:[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.Technology=exports.AgentEventCode=exports.AgentType=void 0;var AgentType;(function(AgentType){AgentType["BUILD_SCANNER"]="BuildScanner";AgentType["TEST_LISTENER"]="TestListener";AgentType["PRODUCTION_LISTENER"]="ProductionListener";AgentType["BROWSER_AGENT"]="BrowserAgent";AgentType["SLNODEJS"]="slnodejs"})(AgentType=exports.AgentType||(exports.AgentType={}));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["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["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["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 Technology;(function(Technology){Technology["NODEJS"]="nodejs";Technology["BROWSER"]="browser"})(Technology=exports.Technology||(exports.Technology={}))})},{}],290:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};var __spreadArrays=this&&this.__spreadArrays||function(){for(var s=0,i=0,il=arguments.length;i<il;i++)s+=arguments[i].length;for(var r=Array(s),k=0,i=0;i<il;i++)for(var a=arguments[i],j=0,jl=a.length;j<jl;j++,k++)r[k]=a[j];return r};(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-conracts","./agent-instance-info-builder","./machine-info-builder","./nodejs-env-info-builder","./agent-start-info-builder","./ci-info-builder","../http/backend-proxy","../utils/validation-utils","../watchdog","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AgentEventsController=void 0;var agent_events_conracts_1=require("./agent-events-conracts");var agent_instance_info_builder_1=require("./agent-instance-info-builder");var machine_info_builder_1=require("./machine-info-builder");var nodejs_env_info_builder_1=require("./nodejs-env-info-builder");var agent_start_info_builder_1=require("./agent-start-info-builder");var ci_info_builder_1=require("./ci-info-builder");var backend_proxy_1=require("../http/backend-proxy");var validation_utils_1=require("../utils/validation-utils");var watchdog_1=require("../watchdog");var system_date_1=require("../system-date");var AgentEventsController=function(){function AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags){this.active=false;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentConfig,"agentConfig");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this._agentConfig=agentConfig;this._logger=logger;this._agentInstanceData=agentInstanceData;this.shutDownRetries=0;this.backendProxy=backendProxy||this.createBackendProxy();this.addTags(tags);this.addTool(tool);this.initWatchdog();this.submittedEventsMap=new Map}AgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return __awaiter(this,void 0,void 0,function(){var event,result;return __generator(this,function(_a){switch(_a.label){case 0:this.active=true;this.startRequestStatus=StartRequestStatus.PENDING;event=this.buildAgentStartEvent(packageJsonFile||{});return[4,this.submitAgentEventRequest(event)];case 1:result=_a.sent();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()}return[2]}})})};AgentEventsController.prototype.submitAgentEventRequest=function(event){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.active){this._logger.debug("Agent not active - not submitting event");return[2,false]}request={agentId:this._agentInstanceData.agentId,events:Array.isArray(event)?event:[event],appName:this._agentConfig.appName.value,buildSessionId:this._agentConfig.buildSessionId.value};_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.backendProxy.submitAgentEvent(request)];case 2:_a.sent();this._logger.info("Submitted '"+request.events.length+"' events successfully");return[2,true];case 3:e_1=_a.sent();this._logger.warn("Failed to submit '"+request.events.length+"' events. Error "+e_1);return[2,false];case 4:return[2]}})})};AgentEventsController.prototype.buildAgentStartEvent=function(packageJsonFile){var agentInstanceInfoBuilder=new agent_instance_info_builder_1.AgentInstanceInfoBuilder(this);var machineInfoBuilder=new machine_info_builder_1.MachineInfoBuilder;var dependencies=__assign(__assign({},packageJsonFile.dependencies),packageJsonFile.devDependencies);var nodejsEnvInfoBuilder=new nodejs_env_info_builder_1.NodejsEnvInfoBuilder(dependencies);var ciInfoBuilder=new ci_info_builder_1.CiInfoBuilder;var agentStartInfoBuilder=new agent_start_info_builder_1.AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,nodejsEnvInfoBuilder,ciInfoBuilder);var agentStartInfo=agentStartInfoBuilder.build();return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_STARTED,agentStartInfo)};AgentEventsController.prototype.buildAgentShutdownEvent=function(){return this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_SHUTDOWN)};AgentEventsController.prototype.submitAgentShutdownEvent=function(){return __awaiter(this,void 0,void 0,function(){var event,result;var _this=this;return __generator(this,function(_a){switch(_a.label){case 0:this.shutDownRetries++;if(this.startRequestStatus==StartRequestStatus.FAILED){this._logger.debug("Agent start not submitted - not sending shut down events");return[2]}if(this.shutDownRetries>AgentEventsController.MAX_SHUTDOWN_RETRIES){this._logger.debug("Stop trying to send shutdown event after 60 seconds ");return[2]}this._pingWatchdog.stop();event=this.buildAgentShutdownEvent();if(!(this.startRequestStatus==StartRequestStatus.PENDING))return[3,1];setTimeout(function(){return _this.submitAgentShutdownEvent.call(_this)},1e3);return[3,3];case 1:return[4,this.submitAgentEventRequest(event)];case 2:result=_a.sent();this.active=false;return[2,result];case 3:return[2]}})})};AgentEventsController.prototype.submitPingEvent=function(){return this.submitEvent(agent_events_conracts_1.AgentEventCode.AGENT_PING,{agentInfo:{labId:this.agentConfig.labId.value}})};AgentEventsController.prototype.submitEvent=function(code,data){var _this=this;this.submittedEventsMap.set(code,true);this._logger.debug("About to send event with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var event=this.buildEvent(code,data);this.submitAgentEventRequest(event).then(function(){return _this._logger.debug("Event with code '"+code+"' submitted successfully")})};AgentEventsController.prototype.submitEventOnce=function(code){if(!this.submittedEventsMap.get(code)){this.submitEvent(code)}};AgentEventsController.prototype.submitGenericMessage=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_MESSAGE)};AgentEventsController.prototype.submitWarning=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.WARN)};AgentEventsController.prototype.submitError=function(message){this.sendMessage(message,agent_events_conracts_1.AgentEventCode.GENERIC_ERROR)};AgentEventsController.prototype.submitErrorsBatch=function(messages){var _this=this;if(!messages||!messages.length){return}var events=messages.map(function(msg){return _this.buildEvent(agent_events_conracts_1.AgentEventCode.GENERIC_ERROR,msg)});this.submitAgentEventRequest(events).then(function(){return _this.logger.debug("'"+events.length+"' events were submitted successfully")})};AgentEventsController.prototype.sendMessage=function(message,code){var _this=this;this.logger.debug("About to send message '"+message+"' with code '"+code+"', current time: "+system_date_1.getSystemDateValueOf());var messageEvent=this.buildEvent(code,message);this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Message submitted successfully")})};AgentEventsController.prototype.submitConfigChanged=function(){var _this=this;var messageEvent=this.buildEvent(agent_events_conracts_1.AgentEventCode.AGENT_CONFIG_CHANGED,this._agentConfig.toJsonObject());this.submitAgentEventRequest(messageEvent).then(function(){return _this.logger.debug("Config changed event submitted successfully")})};Object.defineProperty(AgentEventsController.prototype,"watchdog",{get:function(){return this._pingWatchdog},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"agentConfig",{get:function(){return this._agentConfig},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(AgentEventsController.prototype,"tools",{get:function(){return this._tools},enumerable:false,configurable:true});AgentEventsController.prototype.resolveTags=function(){return this._tags||[]};AgentEventsController.prototype.addTags=function(tags){if(!tags)return
|
|
28
|
-
;this._tags=__spreadArrays(this._tags||[],tags||[])};AgentEventsController.prototype.addTool=function(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)};AgentEventsController.prototype.createBackendProxy=function(){var httpConfig={token:this._agentConfig.token.value,proxy:this._agentConfig.proxy.value,server:this._agentConfig.server.value,compressRequests:this._agentConfig.gzip.value};return new backend_proxy_1.BackendProxy(this._agentInstanceData,httpConfig,this._logger)};AgentEventsController.prototype.initWatchdog=function(){var watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};var timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))};AgentEventsController.prototype.getTimers=function(){if(this._agentInstanceData.technology===agent_events_conracts_1.Technology.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}};AgentEventsController.prototype.buildEvent=function(type,data){return{type:type,utcTimestamp_ms:system_date_1.getSystemDateValueOf(),data:data}};Object.defineProperty(AgentEventsController.prototype,"agentInstanceData",{get:function(){return this._agentInstanceData},enumerable:false,configurable:true});AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;return AgentEventsController}();exports.AgentEventsController=AgentEventsController;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../http/backend-proxy":324,"../system-date":333,"../utils/validation-utils":337,"../watchdog":338,"./agent-events-conracts":289,"./agent-instance-info-builder":291,"./agent-start-info-builder":292,"./ci-info-builder":293,"./machine-info-builder":296,"./nodejs-env-info-builder":297}],291:[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;var sensitive_data_filter_1=require("./sensitive-data-filter");var SEALIGHTS_ENV_VAR_PREFIX="SL_";var AgentInstanceInfoBuilder=function(){function AgentInstanceInfoBuilder(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.agentId=agentEventsController.agentInstanceData.agentId;this.agentType=agentEventsController.agentInstanceData.agentType;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}}AgentInstanceInfoBuilder.prototype.fillData=function(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()};AgentInstanceInfoBuilder.prototype.build=function(){this.fillData();return this.info};AgentInstanceInfoBuilder.prototype.fillFromAgentConfig=function(){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()};AgentInstanceInfoBuilder.prototype.fillFromProcessObject=function(){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()};AgentInstanceInfoBuilder.prototype.extractSealightsEnvVars=function(){var _this=this;var slEnvVars={};Object.keys(process.env).forEach(function(key){if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0){slEnvVars[key]=sensitive_data_filter_1.isSensitive(key,process.env[key],_this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars};AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********";return AgentInstanceInfoBuilder}();exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":298,_process:179}],292:[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.AgentStartInfoBuilder=void 0;var AgentStartInfoBuilder=function(){function AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}AgentStartInfoBuilder.prototype.fillData=function(){};AgentStartInfoBuilder.prototype.build=function(){return{agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()}};return AgentStartInfoBuilder}();exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{}],293:[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;var JENKINS_JOB_NAME_ENV="JOB_NAME";var JENKINS_JOB_ID_ENV="BUILD_ID";var JENKINS_JOB_URL_ENV="BUILD_URL";var CiInfoBuilder=function(){function CiInfoBuilder(){this.info={}}CiInfoBuilder.prototype.fillData=function(){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]}};CiInfoBuilder.prototype.isJenkins=function(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]};CiInfoBuilder.prototype.build=function(){this.fillData();return this.info};return CiInfoBuilder}();exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],294:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;var agent_events_controller_1=require("./agent-events-controller");var dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");var CockpitNotifier=function(){function CockpitNotifier(){}CockpitNotifier.notifyStart=function(agentConfig,agentInstanceData,logger,packageJsonFile,backendProxy,tool,tags){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags);return[4,CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)];case 1:_a.sent();return[2]}})})};CockpitNotifier.notifyShutdown=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.verifyControllerInitialized();return[4,CockpitNotifier.controller.submitAgentShutdownEvent()];case 1:_a.sent();return[2]}})})};CockpitNotifier.sendGenericMessage=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)};CockpitNotifier.sendWarning=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)};CockpitNotifier.sendError=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)};CockpitNotifier.sendErrorsBatch=function(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)};CockpitNotifier.sendEvent=function(code,data){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code,data)};CockpitNotifier.sendEventOnce=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)};CockpitNotifier.verifyControllerInitialized=function(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}};CockpitNotifier.reset=function(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false};CockpitNotifier.setDryRunMode=function(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)};CockpitNotifier.controllerNullLogged=false;return CockpitNotifier}();exports.CockpitNotifier=CockpitNotifier})},{"./agent-events-controller":290,"./dry-run-agent-events-controller":295}],295:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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-conracts","./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;var agent_events_conracts_1=require("./agent-events-conracts");var agent_events_controller_1=require("./agent-events-controller");var config_1=require("../config-process/config");var agent_instance_data_1=require("../agent-instance-data");var DryRunAgentEventsController=function(_super){__extends(DryRunAgentEventsController,_super);function DryRunAgentEventsController(logger,proxy){return _super.call(this,new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.SLNODEJS,agent_events_conracts_1.Technology.NODEJS),logger,proxy,null)||this}DryRunAgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return Promise.resolve(undefined)};return DryRunAgentEventsController}(agent_events_controller_1.AgentEventsController);exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":299,"../config-process/config":302,"./agent-events-conracts":289,"./agent-events-controller":290}],296:[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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;var os=require("os");var system_date_1=require("../system-date");var MachineInfoBuilder=function(){function MachineInfoBuilder(){this.info={}}MachineInfoBuilder.prototype.fillData=function(){var currentDate=system_date_1.getSystemDate();this.info.machineName=os.hostname();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()};MachineInfoBuilder.prototype.build=function(){this.fillData();return this.info};MachineInfoBuilder.prototype.extractIpAddresses=function(){var ipAddresses=[];var interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(function(key){var addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(function(addressObject){return addressObject.address}))});return ipAddresses};return MachineInfoBuilder}();exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../system-date":333,_process:179,os:154}],297:[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;var NodejsEnvInfoBuilder=function(){function NodejsEnvInfoBuilder(dependencies){this.info={};this.dependencies=dependencies||{}}NodejsEnvInfoBuilder.prototype.fillData=function(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node};NodejsEnvInfoBuilder.prototype.build=function(){this.fillData();return this.info};return NodejsEnvInfoBuilder}();exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],298:[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;var 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(var _i=0,_a=Object.entries(secretKeysRegexes);_i<_a.length;_i++){var _b=_a[_i],key=_b[0],regex=_b[1];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})},{}],299:[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-conracts","./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;var uuid=require("uuid");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var files_utils_1=require("./utils/files-utils");var fs_1=require("fs");var agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");var AgentInstanceData=function(){function AgentInstanceData(agentType,technology){this.agentType=agentType;this.technology=technology;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}AgentInstanceData.prototype.resolveAgentVersion=function(){if(this.technology===agent_events_conracts_1.Technology.BROWSER){return this.resolveAgentVersionForBrowserAgent()}var packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{var packageJson=fs_1.readFileSync(packageJsonFilePath).toString();var parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn("Failed to resolve agent version, Error: '"+e);return null}}return null};AgentInstanceData.prototype.resolveAgentVersionForBrowserAgent=function(){return window&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT]&&window[agent_instance_info_builder_1.AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT].agentVersion||agent_instance_info_builder_1.AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION};return AgentInstanceData}();exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-conracts":289,"./agent-events/agent-instance-info-builder":291,"./utils/files-utils":334,fs:69,uuid:507}],300:[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","fs","jwt-decode","./config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;var config_system_1=require("./config-system");var fs=require("fs");var jwtDecode=require("jwt-decode");var config_1=require("./config");var ConfigLoader=function(){function ConfigLoader(logger){this.logger=logger}ConfigLoader.prototype.loadAgentConfiguration=function(initialJsonConfig){var agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{var jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error("Error parsing agent configuration %s",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.printConfiguration(agentCfg);return agentCfg};ConfigLoader.prototype.printConfiguration=function(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())};ConfigLoader.prototype.loadConfigFromToken=function(agentCfg,token){if(!token)return null;try{var 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")}var customerId=tokenData["subject"];var 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){}};return ConfigLoader}();exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"./config":302,"./config-system":301,_process:179,fs:69,"jwt-decode":441}],301:[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;var fs=require("fs");var JsonObjectConfigurationProvider=function(){function JsonObjectConfigurationProvider(configObject){this.configObject=configObject;this.configObject=configObject||{}}JsonObjectConfigurationProvider.prototype.getAllKeyValues=function(callback){return callback(null,this.configObject)};JsonObjectConfigurationProvider.prototype.getName=function(){return"JSON Object"};return JsonObjectConfigurationProvider}();exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;var EnvVariableConfigurationProvider=function(){function EnvVariableConfigurationProvider(prefix){this.prefix=prefix}EnvVariableConfigurationProvider.prototype.getAllKeyValues=function(callback){if(this.prefix){var ret={};for(var key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substr(this.prefix.length)]=process.env[key]}}callback(null,ret)}else{return callback(null,process.env)}};EnvVariableConfigurationProvider.prototype.getName=function(){return"Environment Variables"};return EnvVariableConfigurationProvider}();exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;var ConfigProviderAggregator=function(){function ConfigProviderAggregator(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}ConfigProviderAggregator.prototype.getAllKeyValues=function(callback){var flattenedConfiguration={};var remainingProviders=[].concat(this.providers);var attemptNext=function(){if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}var nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues(function(err,keysAndValues){if(err)return attemptNext();Object.keys(keysAndValues).forEach(function(k){if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()};ConfigProviderAggregator.prototype.getName=function(){return"Aggregated config from multiple providers: "+this.providers.map(function(t){return t.getName()})};return ConfigProviderAggregator}();exports.ConfigProviderAggregator=ConfigProviderAggregator;var JsonConfigFileConfigurationProvider=function(){function JsonConfigFileConfigurationProvider(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}JsonConfigFileConfigurationProvider.prototype.getAllKeyValues=function(callback){try{var cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}};JsonConfigFileConfigurationProvider.prototype.getName=function(){return"Config filename: "+this.filename};return JsonConfigFileConfigurationProvider}();exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;var AgentConfigKey=function(){function AgentConfigKey(){}return AgentConfigKey}();exports.AgentConfigKey=AgentConfigKey;var StringConfigKey=function(){function StringConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(StringConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});StringConfigKey.prototype.loadFromRawData=function(s){this.value=s;this.hasValue=true};return StringConfigKey}();exports.StringConfigKey=StringConfigKey;var NumberConfigKey=function(){function NumberConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(NumberConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});NumberConfigKey.prototype.loadFromRawData=function(s){var parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true};return NumberConfigKey}();exports.NumberConfigKey=NumberConfigKey;var BooleanConfigKey=function(){function BooleanConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(BooleanConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});BooleanConfigKey.prototype.loadFromRawData=function(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)}};return BooleanConfigKey}();exports.BooleanConfigKey=BooleanConfigKey;var BaseConfiguration=function(){function BaseConfiguration(){}BaseConfiguration.prototype.loadConfigurationFromMultipleProviders=function(configProviders,callback){var provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)};BaseConfiguration.prototype.loadConfiguration=function(configProvider,callback,dbg){var _this=this;try{configProvider.getAllKeyValues(function(err,keysAndValues){if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};var knownKeys=Object.keys(_this);var hadError=false;var keyWithError="";knownKeys.forEach(function(keyName){if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}var cfgKey=_this[keyName];if(!cfgKey.isConfigKey)return;var rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){var 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){var 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}};BaseConfiguration.prototype.toJsonObject=function(){var _this=this;var ret={};var knownKeys=Object.keys(this);knownKeys.forEach(function(keyName){var cfgKey=_this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret};BaseConfiguration.prototype.getLowerCaseToKeyMap=function(){var lowerCaseMap={};Object.keys(this).forEach(function(key){lowerCaseMap[key.toLowerCase()]=key})
|
|
29
|
-
;return lowerCaseMap};return BaseConfiguration}();exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:179,fs:69}],302:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var config_system_1=require("./config-system");var AgentConfig=function(_super){__extends(AgentConfig,_super);function AgentConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this;_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.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.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);return _this}return AgentConfig}(config_system_1.BaseConfiguration);exports.AgentConfig=AgentConfig;var AgentConfigWithRuntimeArgs=function(_super){__extends(AgentConfigWithRuntimeArgs,_super);function AgentConfigWithRuntimeArgs(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cfg=new config_system_1.StringConfigKey(false);return _this}return AgentConfigWithRuntimeArgs}(AgentConfig);exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":301}],303:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var events=require("events");var config_system_1=require("./config-system");var assign=require("object-assign");var jwtDecode=require("jwt-decode");var ConfigProcess=function(_super){__extends(ConfigProcess,_super);function ConfigProcess(cfg,watchdog,backendProxy,logger){var _this=_super.call(this)||this;_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",function(){watchdog.stop();_this.reloadConfigFromServer()});_this.initCfg();return _this}ConfigProcess.prototype.reloadConfigFromServer=function(callback){var _this=this;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},function(err,updatedCfg){if(!err&&updatedCfg){_this.mergeConfigFromServerAndFireEvent(updatedCfg)}_this.watchdog.start();if(callback){callback(err)}})};ConfigProcess.prototype.mergeConfigFromServerAndFireEvent=function(updatedCfgObject){var configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(var 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)}};ConfigProcess.prototype.getConfiguration=function(){return this.cfg};ConfigProcess.prototype.initCfg=function(){if(this.cfg.token.hasValue){try{var 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")}var customerId=tokenData["subject"];var 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. %s",err)}}};ConfigProcess.prototype.start=function(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};ConfigProcess.prototype.stop=function(callback){this.watchdog.stop();this.isRunning=false;return callback()};return ConfigProcess}(events.EventEmitter);exports.ConfigProcess=ConfigProcess})},{"./config-system":301,events:110,"jwt-decode":441,"object-assign":153}],304:[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.Constants=void 0;var Constants=function(){function Constants(){}var _a;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=function(){function class_1(){}return class_1}(),_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a);return Constants}();exports.Constants=Constants})},{}],305:[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","../utils/parsing-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;var parsing_utils_1=require("../utils/parsing-utils");var SlEnvVars=function(){function SlEnvVars(){}SlEnvVars.getHttpTimeout=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_TIMEOUT)};SlEnvVars.getHttpMaxAttempts=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_MAX_ATTEMPTS)};SlEnvVars.getHttpAttemptInterval=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.HTTP_ATTEMPT_INTERVAL)};SlEnvVars.inProductionListenerMode=function(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]};SlEnvVars.getProductionListenerModes=function(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")};SlEnvVars.getFileStorage=function(){return process.env[SlEnvVars.FILE_STORAGE]};SlEnvVars.getBasePath=function(){return process.env[SlEnvVars.BASE_PATH]};SlEnvVars.isUseNewUniqueId=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)};SlEnvVars.isUseIstanbul=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.USE_ISTANBUL)};SlEnvVars.enableFootprintsV6=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)};SlEnvVars.getFootprintsCollectIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)};SlEnvVars.getFootprintsSendMaxIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)};SlEnvVars.getFootprintsQueueSize=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)};SlEnvVars.getExecutionQueryIntervalSecs=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)};SlEnvVars.getFootprintsBufferThresholdMb=function(){return parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)};SlEnvVars.blockBrowserHttpTraffic=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)};SlEnvVars.getDisableHookDependencyGuard=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)};SlEnvVars.useSlMapping=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.USE_SL_MAPPING)};var _a;SlEnvVars.HTTP_TIMEOUT="SL_httpTimeout";SlEnvVars.HTTP_MAX_ATTEMPTS="SL_HttpMaxAttempts";SlEnvVars.HTTP_ATTEMPT_INTERVAL="SL_HttpAttemptInterval";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_SL_MAPPING="SL_useSlMapping";SlEnvVars.CIA=(_a=function(){function class_1(){}class_1.getFileExtensions=function(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]};class_1.getScmPrefix=function(){return process.env[SlEnvVars.CIA.SCM_PREFIX]};class_1.getSourceRoot=function(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]};class_1.getSlMappingPath=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]};class_1.getSlMappingUrl=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]};class_1.reduceInstrumentedFileSize=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)};class_1.minifyInstrumentedOutput=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)};class_1.inProcessInstrumentation=function(){return parsing_utils_1.ParsingUtils.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)};class_1.getMaxBuffer=function(){var oneMB=1024*1024;var bufferInBytes=parsing_utils_1.ParsingUtils.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*oneMB}return bufferInBytes};return class_1}(),_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SCM_PREFIX="SL_scmPrefix",_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.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.MAX_BUFFER="SL_maxBuffer",_a);return SlEnvVars}();exports.SlEnvVars=SlEnvVars})}).call(this)}).call(this,require("_process"))},{"../utils/parsing-utils":335,_process:179}],306:[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={}))})},{}],307:[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;var validation_utils_1=require("../utils/validation-utils");var FileElement=function(){function FileElement(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}Object.defineProperty(FileElement.prototype,"type",{get:function(){return this._type},set:function(value){this._type=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"startPosition",{get:function(){return this._startPosition},set:function(value){this._startPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"endPosition",{get:function(){return this._endPosition},set:function(value){this._endPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey",{get:function(){return this._uniqueIdKey},set:function(value){this._uniqueIdKey=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey_decl",{get:function(){return this._uniqueIdKey_decl},set:function(value){this._uniqueIdKey_decl=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"filename",{get:function(){return this._filename},set:function(value){this._filename=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueId",{get:function(){return this._uniqueId},set:function(value){this._uniqueId=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"parentPosition",{get:function(){return this._parentPosition},set:function(value){this._parentPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"index",{get:function(){return this._index},set:function(value){this._index=value},enumerable:false,configurable:true});FileElement.prototype.isStartsAfter=function(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};FileElement.prototype.isStartsBefore=function(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};FileElement.prototype.isEndsAfter=function(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};FileElement.prototype.isEndsBefore=function(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};return FileElement}();exports.FileElement=FileElement})},{"../utils/validation-utils":337}],308:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var contracts_1=require("./contracts");var unique_id_converter_1=require("./unique-id-converter");var IstanbulUniqueIdConverter=function(_super){__extends(IstanbulUniqueIdConverter,_super);function IstanbulUniqueIdConverter(filename,logger){return _super.call(this,filename,logger)||this}IstanbulUniqueIdConverter.prototype.createElementsArray=function(file){var _this=this;file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};var methodsArr=Object.keys(file.fnMap).map(function(key){return _this.formatMethod(file.fnMap[key])});var branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)};IstanbulUniqueIdConverter.prototype.createElementPosition=function(position){return position};IstanbulUniqueIdConverter.prototype.createBranchElements=function(branchesMap){var branchesMapArr=Object.keys(branchesMap).map(function(key){return branchesMap[key]});var branchesArr=[];for(var _i=0,branchesMapArr_1=branchesMapArr;_i<branchesMapArr_1.length;_i++){var branch=branchesMapArr_1[_i];branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr};IstanbulUniqueIdConverter.prototype.extractBranchParts=function(branch){var formattedBranches=[];var locations=branch.locations;for(var i=0;i<locations.length;i++){var 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};IstanbulUniqueIdConverter.prototype.formatMethod=function(method){var 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};IstanbulUniqueIdConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};return IstanbulUniqueIdConverter}(unique_id_converter_1.UniqueIdConverter);exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":306,"./unique-id-converter":311}],309:[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;var path_1=require("path");var system_date_1=require("../system-date");var files_utils_1=require("../utils/files-utils");var istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=path_1.normalize(moduleName);var moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug("building uniqueids map for "+moduleData.path);var before_1=system_date_1.getSystemDateValueOf();logger.debug("file "+moduleData.path+" not contains uniqueIdMaps, trying to reload");createSLMapping(moduleData.path,relativePath,coverageObject,logger);var after_1=system_date_1.getSystemDateValueOf();logger.debug("*******************************create unique id map ******************************************");logger.debug(after_1-before_1);logger.debug("*******************************create unique id map ******************************************")}var 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){var withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);var 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){var module=coverageObject[fullPath];var converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":333,"../utils/files-utils":334,"./istanbul-unique-id-converter":308,path:171}],310:[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;var validation_utils_1=require("../utils/validation-utils");var files_utils_1=require("../utils/files-utils");var source_maps_utils_1=require("../source-maps-utils");var BRANCHES_MAP_KEY="branchMap";var METHODS_MAP_KEY="fnMap";var OriginalModuleLoader=function(){function OriginalModuleLoader(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}OriginalModuleLoader.prototype.load=function(){var _this=this;var modules=Object.keys(this.coverageObject);modules.map(function(moduleName){return _this.tryLoadOriginalModule(moduleName)})};OriginalModuleLoader.prototype.tryLoadOriginalModule=function(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)};OriginalModuleLoader.prototype.readOriginalModule=function(moduleName){var _this=this;var sourceMapsReader=this.getSourceMapForFile(moduleName);var module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(function(key){return _this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName)});Object.keys(module.fnMap).map(function(key){return _this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName)})};OriginalModuleLoader.prototype.resolveAndAddMethod=function(method,sourceMapsReader,moduleName){var originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}};OriginalModuleLoader.prototype.resolveAndAddBranch=function(branch,sourceMapsReader,moduleName){var _this=this;var originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){var originalLocations=branch.locations.map(function(locationElement){return _this.createElementSourceData(locationElement,sourceMapsReader,moduleName)});originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}};OriginalModuleLoader.prototype.loadOriginalDataForElement=function(sourceMapsReader,element,moduleName,originalElement){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;var originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};var sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);var sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName};OriginalModuleLoader.prototype.addElementToModule=function(moduleName,element,mapObjectKey){var module=this.getOrCreateIstanbulModule(moduleName);var key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}};OriginalModuleLoader.prototype.createElementSourceData=function(locationElement,sourceMapsReader,moduleName){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}var sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement};OriginalModuleLoader.prototype.getOrCreateIstanbulModule=function(moduleName){var module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module};OriginalModuleLoader.prototype.getSourceMapForFile=function(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}var sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap};OriginalModuleLoader.prototype.readSourceMapData=function(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{var originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){var 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);var originalPositionObj={line:originalPosition.line,column:originalPosition.column};var result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null};OriginalModuleLoader.prototype.createElementKey=function(element){return element.loc.start.line+":"+element.loc.start.column};OriginalModuleLoader.prototype.createEmptyBranchObject=function(){return{loc:{},locations:[],type:"",line:null}};OriginalModuleLoader.prototype.createEmptyMethodObject=function(){return{loc:{},name:"",line:null}};OriginalModuleLoader.prototype.createIstanbulModule=function(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,uniqueIdsMap:null}};Object.defineProperty(OriginalModuleLoader.prototype,"fileToSourceMapConsumer",{get:function(){
|
|
30
|
-
return this._fileToSourceMapConsumer},set:function(value){this._fileToSourceMapConsumer=value},enumerable:false,configurable:true});return OriginalModuleLoader}();exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":330,"../utils/files-utils":334,"../utils/validation-utils":337}],311:[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;var contracts_1=require("./contracts");var file_element_1=require("./file-element");var METHOD_DELIMITER="@";var BRANCH_DELIMITER="|";var NULL_PARAM_MESSAGE="cannot be null or undefined";var UniqueIdConverter=function(){function UniqueIdConverter(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=[]}UniqueIdConverter.prototype.sortElements=function(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)};UniqueIdConverter.prototype.createElementsArray=function(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)};UniqueIdConverter.prototype.createFileElement=function(element,filename,type){var startPosition=this.createElementPosition(element.position);var endPosition=this.createElementPosition(element.endPosition);var 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){var index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}return fileElement};UniqueIdConverter.prototype.process=function(){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()};UniqueIdConverter.prototype.setAndInitFile=function(file){this.createElementsArray(file)};UniqueIdConverter.prototype.createElementPosition=function(position){var line;var 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}};UniqueIdConverter.prototype.fillFileElementsArray=function(elements,array,type){for(var _i=0,elements_1=elements;_i<elements_1.length;_i++){var element=elements_1[_i];array.push(this.createFileElement(element,this._filename,type))}};UniqueIdConverter.prototype.fillUniqueIdsMap=function(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)};UniqueIdConverter.prototype.createNewUniqueIds=function(array,delimiter){var aggregatedByLine=this.aggregateElementsByLine(array);var lines=Object.keys(aggregatedByLine);for(var _i=0,lines_1=lines;_i<lines_1.length;_i++){var line=lines_1[_i];var indexesArray=aggregatedByLine[line];for(var i=0;i<indexesArray.length;i++){var currentIndex=indexesArray[i];var currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug("[UniqueIdConverter] uniqueId "+currentElement.uniqueIdKey+" converted to \n "+currentElement.uniqueId);this._uniqueIdsMap[currentElement.uniqueIdKey]=currentElement.uniqueId;if(currentElement.uniqueIdKey_decl){this._uniqueIdsMap[currentElement.uniqueIdKey_decl]=currentElement.uniqueId}}}};UniqueIdConverter.prototype.comparePosition=function(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};Object.defineProperty(UniqueIdConverter.prototype,"uniqueIdsMap",{get:function(){return this._uniqueIdsMap},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"methodsArray",{get:function(){return this._methodsArray},set:function(value){this._methodsArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"branchesArray",{get:function(){return this._branchesArray},set:function(value){this._branchesArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"filename",{get:function(){return this._filename},enumerable:false,configurable:true});UniqueIdConverter.prototype.removeDuplicateElements=function(elementsArray){var _this=this;var existedKeys={};elementsArray=elementsArray.filter(function(element){return _this.filterDuplicates(element,existedKeys)})};UniqueIdConverter.prototype.filterDuplicates=function(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};UniqueIdConverter.prototype.removeBranchesOutOfMethods=function(){var validBranches=[];var methodsIndex=0;for(var _i=0,_a=this._branchesArray;_i<_a.length;_i++){var branch=_a[_i];for(var i=methodsIndex;i<this._methodsArray.length;i++){var currentMethod=this._methodsArray[i];var branchPosition=this.checkBranchPosition(branch,currentMethod);if(branchPosition===0){validBranches.push(branch);break}if(branchPosition===1){methodsIndex++}}}this._branchesArray=validBranches.sort(this.comparePosition)};UniqueIdConverter.prototype.checkBranchPosition=function(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};UniqueIdConverter.prototype.aggregateElementsByLine=function(elements){var aggregated={};for(var i=0;i<elements.length;i++){var element=elements[i];var lineNumber=element.startPosition.line;if(!aggregated[lineNumber]){aggregated[lineNumber]=[]}aggregated[lineNumber].push(i)}return aggregated};return UniqueIdConverter}();exports.UniqueIdConverter=UniqueIdConverter})},{"./contracts":306,"./file-element":307}],312:[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.TestSelectionStatus=exports.EventTypes=void 0;var EventTypes;(function(EventTypes){EventTypes["AgentStarted"]="agentStarted";EventTypes["ExecutionIdStarted"]="executionIdStarted";EventTypes["ExecutionIdEnded"]="executionIdEnded";EventTypes["TestStart"]="testStart";EventTypes["TestEnd"]="testEnd"})(EventTypes=exports.EventTypes||(exports.EventTypes={}));var TestSelectionStatus;(function(TestSelectionStatus){TestSelectionStatus["RECOMMENDED_TESTS"]="recommendedTests";TestSelectionStatus["DISABLED"]="disabled";TestSelectionStatus["DISABLED_BY_CONFIGURATION"]="disabledByConfiguration";TestSelectionStatus["RECOMMENDATIONS_TIMEOUT"]="recommendationsTimeout";TestSelectionStatus["ERROR"]="error"})(TestSelectionStatus=exports.TestSelectionStatus||(exports.TestSelectionStatus={}))})},{}],313:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};(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-contracts","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsCreator=void 0;var events_contracts_1=require("./events-contracts");var system_date_1=require("../system-date");var EventsCreator=function(){function EventsCreator(){}EventsCreator.createTestStartedEvent=function(executionId,framework,testName,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestStart,executionId,framework);var startTimeStamp=system_date_1.getSystemDateValueOf()-duration;eventBase.localTime=startTimeStamp;return __assign(__assign({},eventBase),{testName:testName})};EventsCreator.createTestEndEvent=function(executionId,framework,testName,result,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestEnd,executionId,framework);return __assign(__assign({},eventBase),{result:result,duration:duration,testName:testName})};EventsCreator.createEvent=function(type,executionId,framework){return{type:type,executionId:executionId,framework:framework,localTime:system_date_1.getSystemDateValueOf()}};return EventsCreator}();exports.EventsCreator=EventsCreator})},{"../system-date":333,"./events-contracts":312}],314:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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;var validation_utils_1=require("../utils/validation-utils");var system_date_1=require("../system-date");var EventsProcess=function(){function EventsProcess(configuration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentDataService,backendProxy,eventsQueue,logger){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()}EventsProcess.prototype.enqueueEvent=function(evt){evt.localTime=evt.localTime||system_date_1.getSystemDateValueOf();this._eventsQueue.enqueue(evt);if(this.isRunning&&this.configuration.sendEvents.value&&this.configuration.enabled.value){this.ensureKeepaliveThreadRunning()}};EventsProcess.prototype.start=function(){if(this._isRunning||!this._configuration.enabled.value){return}this._sendToServerWatchdog.start();if(this._eventsQueue.getQueueSize()>0){this.ensureKeepaliveThreadRunning()}this._isRunning=true};EventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:this._sendToServerWatchdog.stop();this.keepAliveWatchdog.stop();if(this._configuration.enabled.value===false||this._configuration.sendEvents.value===false){return[2]}_a.label=1;case 1:_a.trys.push([1,4,,5]);return[4,Promise.all(this._onGoingRequests)];case 2:_a.sent();return[4,this.submitEventsSync()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this._logger.warn("Error while stopping EventsProcess: ",e_1);return[3,5];case 5:this._isRunning=false;return[2]}})})};EventsProcess.prototype.getQueueSize=function(){return this._eventsQueue.getQueueSize()};EventsProcess.prototype.submitEvents=function(){var _this=this;if(!this._isRunning||!this._configuration.sendEvents.value||!this._configuration.enabled.value||this._eventsQueue.getQueueSize()==0){return}var items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);var packet=this.createEventsPacket(items);var promise=this._backendProxy.submitEventsPromise(packet);this._onGoingRequests.push(promise);promise.then(function(){if(_this._eventsQueue.getQueueSize()>0){_this.submitEvents()}_this.removeRequest(promise)}).catch(function(err){_this._logger.warn("Error while submitting events, "+err);_this._eventsQueue.requeue(items);_this.removeRequest(promise)})};EventsProcess.prototype.submitEventsSync=function(){return __awaiter(this,void 0,void 0,function(){var items,packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,4,,5]);_a.label=1;case 1:if(!(this._eventsQueue.getQueueSize()>0))return[3,3];items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);return[4,this._backendProxy.submitEventsPromise(packet)];case 2:_a.sent();return[3,1];case 3:return[3,5];case 4:e_2=_a.sent();this._logger.warn("Error while sending events synchronously. "+e_2);return[3,5];case 5:return[2]}})})};EventsProcess.prototype.createEventsPacket=function(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:system_date_1.getSystemDateValueOf(),agentId:this._agentInstanceData.agentId}}};EventsProcess.prototype.init=function(){var _this=this;this._sendToServerWatchdog.on("alarm",function(){return _this.submitEvents()});this._eventsQueue.on("full",function(){return _this.submitEvents()});this.keepAliveWatchdog.on("alarm",function(){if(_this.eventsQueue.getQueueSize()==0){_this.keepAliveWatchdog.stop()}})};EventsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepAliveWatchdog.start()};EventsProcess.prototype.removeRequest=function(request){var index=this._onGoingRequests.indexOf(request);this._onGoingRequests.splice(index,1)};Object.defineProperty(EventsProcess.prototype,"onGoingRequests",{get:function(){return this._onGoingRequests},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"configuration",{get:function(){return this._configuration},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"isRunning",{get:function(){return this._isRunning},set:function(value){this._isRunning=value},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"sendToServerWatchdog",{get:function(){return this._sendToServerWatchdog},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"backendProxy",{get:function(){return this._backendProxy},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"eventsQueue",{get:function(){return this._eventsQueue},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"testSelectionStatus",{get:function(){return this._testSelectionStatus},set:function(testSelectionStatus){this._testSelectionStatus=testSelectionStatus},enumerable:false,configurable:true});EventsProcess.ITEMS_TO_DEQUE=1e3;return EventsProcess}();exports.EventsProcess=EventsProcess})},{"../system-date":333,"../utils/validation-utils":337}],315:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var location_formatter_1=require("./location-formatter");var hits_converter_1=require("../../common/footprints-process-v6/hits-converter");var files_utils_1=require("../utils/files-utils");var BaseBrowserHitsConverter=function(_super){__extends(BaseBrowserHitsConverter,_super);function BaseBrowserHitsConverter(relativePathResolver,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,{},{},logger)||this;_this.buildSessionId=buildSessionId;return _this}BaseBrowserHitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var uniqueId=absolutePath+hits_converter_1.HitsConverter.METHOD_ID_DEL+this.formatLoc(startLoc);return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId=absolutePath+hits_converter_1.HitsConverter.BRANCH_ID_DEL+this.formatLoc(startLoc)+hits_converter_1.HitsConverter.BRANCH_ID_DEL+leaveIndex;return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getDeclStart=function(hit){var decl=this.getDecl(hit);return decl.start||decl.st};BaseBrowserHitsConverter.prototype.getDecl=function(hit){return hit.decl||hit.d};BaseBrowserHitsConverter.prototype.getStartLoc=function(hit){var loc=hit.loc||hit.lc;return loc.start||loc.st};BaseBrowserHitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx){var locations=hit.branchData.locations||hit.branchData.lcs;return locations[leaveIdx].start||locations[leaveIdx].st};BaseBrowserHitsConverter.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};BaseBrowserHitsConverter.prototype.tryGetUniqueIdFromSlMapping=function(rawUniqueId){rawUniqueId=files_utils_1.FilesUtils.adjustPathSlashes(rawUniqueId);var mapping=this.getSlMapping()||{};return mapping[rawUniqueId]||rawUniqueId};return BaseBrowserHitsConverter}(hits_converter_1.HitsConverter);exports.BaseBrowserHitsConverter=BaseBrowserHitsConverter})},{"../../common/footprints-process-v6/hits-converter":319,"../utils/files-utils":334,"./location-formatter":321}],316:[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;var BufferSizeHelper=function(){function BufferSizeHelper(){this.uniqueIdsLengthSum=0;this.testNamesCount=0;this.testNamesLengthSum=0;this.hitCount=0;this.indicesCount=0;this.uniqueIdsCount=0}BufferSizeHelper.prototype.calculateBufferSize=function(){var 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.MB};BufferSizeHelper.prototype.incrementSizeCounters=function(testName,methodIndicesSize,branchIndicesSize){this.hitCount++;this.indicesCount+=methodIndicesSize+branchIndicesSize;if(testName){this.testNamesCount++;this.testNamesLengthSum+=testName.length}};BufferSizeHelper.FOUR_BYTES=4;BufferSizeHelper.EIGHT_BYTES=8;BufferSizeHelper.APPROX_HIT_SIZE=128;BufferSizeHelper.MB=1024*1024;return BufferSizeHelper}();exports.BufferSizeHelper=BufferSizeHelper})},{}],317:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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-conracts","events","./buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsBuffer=void 0;var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var events=require("events");var buffer_size_helper_1=require("./buffer-size-helper");var FootprintsBuffer=function(_super){__extends(FootprintsBuffer,_super);function FootprintsBuffer(agentInstanceData,agentConfig){var _this=_super.call(this)||this;_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};return _this}FootprintsBuffer.prototype.addHit=function(footprints,collectionInterval,executionId,testName,isInitFootprints,isFinalFootprints){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_COLLECTED_FP);var methodIndices=this.addOrGetIndices(footprints.methods,true);var branchIndices=this.addOrGetIndices(footprints.branches,false);var 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()};FootprintsBuffer.prototype.createPacket=function(){var packet=this.toJson();this.resetState();return packet};FootprintsBuffer.prototype.resetState=function(){this.branches=[];this.methods=[];this.executions=[];this.methodIdToIndex=new Map;this.branchIdToIndex=new Map;this.bufferSizeHelper=new buffer_size_helper_1.BufferSizeHelper};FootprintsBuffer.prototype.hasHitsInBuffer=function(){return this.executions.length>0};Object.defineProperty(FootprintsBuffer.prototype,"agentConfig",{get:function(){return this._agentConfig},set:function(value){this._agentConfig=value},enumerable:false,configurable:true});FootprintsBuffer.prototype.toJson=function(){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}};FootprintsBuffer.prototype.addOrGetIndices=function(elementIds,isMethods){var _this=this;var map=isMethods?this.methodIdToIndex:this.branchIdToIndex;var arr=isMethods?this.methods:this.branches;var indices=[];elementIds.forEach(function(id){if(!map.get(id)){_this.bufferSizeHelper.uniqueIdsLengthSum+=id.length;_this.bufferSizeHelper.uniqueIdsCount++;var position=arr.push(id);map.set(id,position-1)}indices.push(map.get(id))});return indices};FootprintsBuffer.prototype.addOrGetExecutionIndex=function(executionId){var index=-1;this.executions.every(function(execution,idx){if(executionId==execution.executionId){index=idx;return false}return true});return index!=-1?index:this.executions.push({executionId:executionId,hits:[]})-1};FootprintsBuffer.prototype.verifyBufferSize=function(){if(this.bufferSizeHelper.calculateBufferSize()>=this._agentConfig.footprintsBufferThresholdMb.value){this.emit(FootprintsBuffer.BUFFER_FULL)}};FootprintsBuffer.BUFFER_FULL="bufferFull";return FootprintsBuffer}(events.EventEmitter);exports.FootprintsBuffer=FootprintsBuffer})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"./buffer-size-helper":316,events:110}],318:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsCollector=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var GLOBAL_ISTANBUL_CONTAINER_NAMES=["__coverage__"];var HitsCollector=function(){function HitsCollector(logger,globalCoverageObject){this.logger=logger;this._globalCoverageObject=globalCoverageObject;this.latestCoverageSnapshot={}}HitsCollector.prototype.getHitElements=function(){return __awaiter(this,void 0,void 0,function(){var hitFilesData,globalCoverage,filename,_a,fileCoverageSnapshot,currentFileCoverage,shouldResolveRelativePath,hitMethods,hitBranches;return __generator(this,function(_b){hitFilesData=[];globalCoverage=this.getGlobalCoverageObject();if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(globalCoverage,this.logger).load()}for(filename in globalCoverage){_a=this.getFileCoverageObjects(filename),fileCoverageSnapshot=_a.fileCoverageSnapshot,currentFileCoverage=_a.currentFileCoverage,shouldResolveRelativePath=_a.shouldResolveRelativePath;hitMethods=this.getHitMethods(currentFileCoverage,fileCoverageSnapshot);hitBranches=this.getHitBranches(currentFileCoverage,fileCoverageSnapshot);if(hitMethods.length||hitBranches.length){hitFilesData.push({filename:filename,hitMethods:hitMethods,hitBranches:hitBranches,shouldResolveRelativePath:shouldResolveRelativePath})}}this.updateCoverageSnapshot(globalCoverage);return[2,hitFilesData]})})};Object.defineProperty(HitsCollector.prototype,"latestCoverageSnapshot",{get:function(){return this._latestCoverageSnapshot},set:function(value){this._latestCoverageSnapshot=value},enumerable:false,configurable:true});Object.defineProperty(HitsCollector.prototype,"globalCoverageObject",{get:function(){return this._globalCoverageObject},set:function(value){this._globalCoverageObject=value},enumerable:false,configurable:true});HitsCollector.prototype.getHitMethods=function(currentHits,snapshotHits){var hitMethodsIndices=Object.keys(currentHits.f).filter(function(id){snapshotHits.f[id]=snapshotHits.f[id]||0
|
|
31
|
-
;return currentHits.f[id]>snapshotHits.f[id]});return hitMethodsIndices.map(function(id){return currentHits.fnMap[id]})};HitsCollector.prototype.dropHits=function(){this.updateCoverageSnapshot(this.getGlobalCoverageObject())};HitsCollector.prototype.getHitLeaves=function(currentLeaveHits,snapshotLeaveHits){var hitLeavesIndices=[];snapshotLeaveHits=snapshotLeaveHits||Array(currentLeaveHits.length).fill(0);currentLeaveHits.forEach(function(leaveHit,leaveIdx){if(currentLeaveHits[leaveIdx]>snapshotLeaveHits[leaveIdx]){hitLeavesIndices.push(leaveIdx)}});return hitLeavesIndices};HitsCollector.prototype.getHitBranches=function(currentHits,fileHitSnapshot){var hitBranches=[];for(var branchIdx in currentHits.b){var hitLeaves=this.getHitLeaves(currentHits.b[branchIdx],fileHitSnapshot.b[branchIdx]);if(hitLeaves.length>0){var branchData=currentHits.branchMap[branchIdx];hitBranches.push({branchData:branchData,hitLeaves:hitLeaves})}}return hitBranches};HitsCollector.prototype.createEmptyIstanbulModule=function(path,useDataKey){if(useDataKey===void 0){useDataKey=false}var emptyModule={f:{},fnMap:{},b:{},branchMap:{},path:path,s:{}};if(useDataKey){return{data:emptyModule}}return emptyModule};HitsCollector.prototype.getFileCoverageObjects=function(filename){var fileCoverageSnapshot=this._latestCoverageSnapshot[filename]||this.createEmptyIstanbulModule(filename);var currentFileCoverage=this._globalCoverageObject[filename];var shouldResolveRelativePath=true;if(!fileCoverageSnapshot.f&&fileCoverageSnapshot.data){fileCoverageSnapshot=fileCoverageSnapshot.data;shouldResolveRelativePath=false}if(!currentFileCoverage.f&¤tFileCoverage.data){currentFileCoverage=currentFileCoverage.data}return{fileCoverageSnapshot:fileCoverageSnapshot,currentFileCoverage:currentFileCoverage,shouldResolveRelativePath:shouldResolveRelativePath}};HitsCollector.prototype.getGlobalCoverageObject=function(){if(this._globalCoverageObject)return this._globalCoverageObject;this._globalCoverageObject=HitsCollector.resolveGlobalCoverageObject();if(!this._globalCoverageObject){this.logger.warn("Coverage object not found")}return this._globalCoverageObject};HitsCollector.resolveGlobalCoverageObject=function(){var re=/^\$\$cov_[0-9]+\$\$$/;var keys=Object.keys(global);for(var i=0;i<keys.length;i++){var k=keys[i];if(re.exec(k)!==null||GLOBAL_ISTANBUL_CONTAINER_NAMES.indexOf(k)>=0){return global[k]}}};HitsCollector.prototype.updateCoverageSnapshot=function(currentCounters){for(var istanbulModule in currentCounters){var useDataKey=currentCounters[istanbulModule].data!==undefined;this._latestCoverageSnapshot[istanbulModule]=this._latestCoverageSnapshot[istanbulModule]||this.createEmptyIstanbulModule(istanbulModule,useDataKey);var f=currentCounters[istanbulModule].f||currentCounters[istanbulModule].data.f;var b=currentCounters[istanbulModule].b||currentCounters[istanbulModule].data.b;for(var funcId in f){this.setFunctionHit(istanbulModule,funcId,f,useDataKey)}for(var branchId in b){this.setBranchHit(b,branchId,istanbulModule,useDataKey)}}};HitsCollector.prototype.setBranchHit=function(b,branchId,istanbulModule,useDataKey){var currentBranchesHits=b[branchId];this._latestCoverageSnapshot[istanbulModule].b[branchId]=this._latestCoverageSnapshot[istanbulModule].b[branchId]||[];for(var 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]}}};HitsCollector.prototype.setFunctionHit=function(istanbulModule,funcId,f,useDataKey){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.f[funcId]=f[funcId]}else{this._latestCoverageSnapshot[istanbulModule].f[funcId]=f[funcId]}};return HitsCollector}();exports.HitsCollector=HitsCollector})}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../constants/sl-env-vars":305,"../coverage-elements/original-module-loader":310}],319:[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;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var hits_collector_1=require("./hits-collector");var new_id_resolver_1=require("../coverage-elements/new-id-resolver");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var HitsConverter=function(){function HitsConverter(relativePathResolver,sourceMapData,projectRoot,logger){this.conversionErrors=[];this._slMapping={};this.relativePathResolver=relativePathResolver;this.sourceMapData=sourceMapData;this.projectRoot=projectRoot;this.logger=logger}HitsConverter.prototype.convertHits=function(hitFilesData){var _this=this;var methodUniqueIds=[];var branchUniqueIds=[];if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger).load()}hitFilesData.forEach(function(fileHit){var 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}};Object.defineProperty(HitsConverter.prototype,"slMapping",{get:function(){return this._slMapping},set:function(value){this._slMapping=value},enumerable:false,configurable:true});HitsConverter.prototype.createMethodIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var methodIds=[];hitFunctions.forEach(function(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};HitsConverter.prototype.getDeclStart=function(hit){return hit.decl.start};HitsConverter.prototype.getDecl=function(hit){return hit.decl};HitsConverter.prototype.getStartLoc=function(hit){return hit.loc.start};HitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx,absolutePath){var _a;var position=hit.branchData.locations[leaveIdx].start;var parentPosition=(_a=hit.branchData.loc)===null||_a===void 0?void 0:_a.start;if(!parentPosition){if(!sl_env_vars_1.SlEnvVars.isUseIstanbul()){var 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}var newInstrumentation=parentPosition.line!=position.line||parentPosition.column!=position.column;if(hit.branchData.type==="if"){var 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};HitsConverter.prototype.createBranchIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var branchIds=[];hitFunctions.forEach(function(hit){hit.hitLeaves.forEach(function(leaveIdx){branchIds.push(_this.getBranchUniqueId(_this.getLeaveStartLoc(hit,leaveIdx,absolutePath),relativePath,absolutePath,leaveIdx))})});return branchIds};HitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var idParts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=idParts.relativePath+"@"+this.formatLoc(idParts.start);var uniqueId=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)};HitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId;var parts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=parts.relativePath+"|"+this.formatLoc(parts.start)+"|"+leaveIndex;uniqueId=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};HitsConverter.prototype.resolveIdParts=function(startLoc,relativePath,absolutePath){var sourcePosition=this.sourceMapData.getSourcePosition(relativePath,absolutePath,startLoc,this.projectRoot,this.slMapping);return sourcePosition?sourcePosition:{relativePath:relativePath,start:startLoc,absolutePath:absolutePath}};HitsConverter.prototype.buildMethodUniqueId=function(parts){return parts.relativePath+HitsConverter.METHOD_ID_DEL+this.formatLoc(parts.start)};HitsConverter.prototype.sendConversionErrors=function(){if(this.conversionErrors.length>0){cockpit_notifier_1.CockpitNotifier.sendErrorsBatch(this.conversionErrors);this.conversionErrors=[]}};HitsConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};HitsConverter.METHOD_ID_DEL="@";HitsConverter.BRANCH_ID_DEL="|";return HitsConverter}();exports.HitsConverter=HitsConverter})},{"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../coverage-elements/new-id-resolver":309,"../coverage-elements/original-module-loader":310,"./hits-collector":318}],320:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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-conracts","../constants/sl-env-vars"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsProcess=void 0;var footprints_buffer_1=require("./footprints-buffer");var collection_interval_1=require("../footprints-process/collection-interval");var state_tracker_1=require("../state-tracker");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var sl_env_vars_1=require("../constants/sl-env-vars");var FootprintsProcess=function(){function FootprintsProcess(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()}FootprintsProcess.prototype.enqueueCurrentFootprints=function(execution,testName,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){var hitFilesData,convertedHits;return __generator(this,function(_a){switch(_a.label){case 0:this.currentExecutionBsid=execution.buildSessionId;this.collectionInterval.next();return[4,this.hitsCollector.getHitElements()];case 1:hitFilesData=_a.sent();if(hitFilesData.length){this.logger.info("Collecting hits for '"+hitFilesData.length+"' files");convertedHits=this.hitsConverter.convertHits(hitFilesData);this.footprintsBuffer.addHit(convertedHits,this.collectionInterval.toJson(),execution.executionId,testName,this.isInitFootprints(),isFinalFootprints)}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.start()}this.footprintsEnqueueOnce=true;return[2]}})})};FootprintsProcess.prototype.updateConfig=function(updatedCfg){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:this.cfg=updatedCfg;return[4,this.stopIfNeededAfterConfigChanged(updatedCfg)];case 1:_a.sent();this.sendToServerWatchdog.setInterval(this.cfg.footprintsSendIntervalSecs.value);this.footprintsBuffer.agentConfig=updatedCfg;return[2]}})})};FootprintsProcess.prototype.stopIfNeededAfterConfigChanged=function(updatedCfg){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:if(!(updatedCfg.sendFootprints.value===false||updatedCfg.enabled.value===false))return[3,4];cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.AGENT_MUTED);this.footprintsBuffer.resetState();_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.stop()];case 2:_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error("Error stopping footprints process "+e_1.message);this.logger.debug(e_1.stackTrace);return[3,4];case 4:return[2]}})})};FootprintsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepaliveWatchdog.start()};FootprintsProcess.prototype.submitQueuedFootprints=function(execution){return __awaiter(this,void 0,void 0,function(){var packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.shouldSubmitFootprints()){return[2]}packet=this.footprintsBuffer.createPacket();if(!packet)return[3,6];this.ongoingRequestsCounter++;_a.label=1;case 1:_a.trys.push([1,3,4,5]);return[4,this.backendProxy.submitFootprintsV6(packet,execution.buildSessionId,execution.testStage,this.cfg.buildSessionId.value)];case 2:_a.sent();this.logger.info("Footprints packet submitted successfully. packet contains "+packet.methods.length+" methods, "+packet.branches.length+" branches in "+packet.executions.length+" executions");return[3,5];case 3:e_2=_a.sent();this.logger.error("Error while submitting footprints '"+e_2+"'");cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.FOOTPRINTS_LOSS);return[3,5];case 4:this.ongoingRequestsCounter--;return[7];case 5:return[3,7];case 6:this.logger.info("No hits collected nothing to submit");_a.label=7;case 7:return[2]}})})};FootprintsProcess.prototype.shouldSubmitFootprints=function(){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};FootprintsProcess.prototype.start=function(){if(this.isRunning)return;if(this.cfg.enabled.value==false)return;this.isRunning=true;this.sendToServerWatchdog.start();if(this.footprintsBuffer.hasHitsInBuffer()){this.ensureKeepaliveThreadRunning()}};FootprintsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var packet,e_3;return __generator(this,function(_a){switch(_a.label){case 0:this.sendToServerWatchdog.stop();if(!this.shouldSubmitFootprints()){this.isRunning=false;return[2]}return[4,this.flushCurrentFootprints(true)];case 1:_a.sent();packet=this.footprintsBuffer.createPacket();this.isRunning=false;if(!packet){this.logger.info("No hits collected, nothing to submit");return[2]}this.logger.info("Start submitting footprints, triggered by stop event.");_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value)];case 3:_a.sent();this.logger.info("Final footprints submitted successfully");return[3,5];case 4:e_3=_a.sent();this.logger.error("Failed to submit final footprints, error: "+e_3.message);this.logger.debug(e_3);return[2];case 5:return[2]}})})};FootprintsProcess.prototype.handleTestIdChanged=function(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{if(!this.stateTracker.shouldCollectHits()){this.logger.info("Test identifier changed, couldn't find active execution for anonymous footprints. Skip enqueuing footprints process.");return}this.logger.debug("Test identifier changed, start enqueuing footprints process.");var prevTestIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(previousTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution,prevTestIdentifierParts.testName)}};FootprintsProcess.prototype.delegateEvents=function(){var _this=this;this.sendToServerWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){_this.logger.debug("Start submitting footprints, triggered by send to server watchdog.");_this.submitQueuedFootprints(_this.stateTracker.currentExecution)});this.keepaliveWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){if(!_this.hasOngoingRequests()&&!_this.footprintsBuffer.hasHitsInBuffer()){_this.keepaliveWatchdog.stop()}});this.footprintsBuffer.on(footprints_buffer_1.FootprintsBuffer.BUFFER_FULL,function(){_this.submitQueuedFootprints(_this.stateTracker.currentExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_BSID_CHANGED,function(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,function(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,function(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,function(execution){_this.enqueueAndSubmit(execution)})};FootprintsProcess.prototype.enqueueAndSubmit=function(executionData,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.enqueueCurrentFootprints(executionData,null,isFinalFootprints)];case 1:_a.sent();return[4,this.submitQueuedFootprints(executionData)];case 2:_a.sent();return[2]}})})};FootprintsProcess.prototype.flushCurrentFootprints=function(isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){var currentTestIdentifier,testIdentifierParts;return __generator(this,function(_a){switch(_a.label){case 0:currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();if(!currentTestIdentifier)return[3,2];testIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug("Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '%s'",currentTestIdentifier);return[4,this.enqueueCurrentFootprints(this.stateTracker.currentExecution,testIdentifierParts.testName,isFinalFootprints)];case 1:_a.sent();return[3,5];case 2:if(!this.stateTracker.shouldCollectHits())return[3,4];this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");return[4,this.enqueueCurrentFootprints(this.stateTracker.currentExecution,null,isFinalFootprints)];case 3:_a.sent();return[3,5];case 4:this.logger.info("Enqueue footprints interval - no active execution. skip enqueuing process.");this.handleNoExecutionFound();_a.label=5;case 5:return[2]}})})};FootprintsProcess.prototype.handleNoExecutionFound=function(){if(this.stateTracker.openExecutionFoundOnce){this.logger.debug("No active execution and not in initFootprints mode, updating coverage snapshot");this.hitsCollector.dropHits()}};FootprintsProcess.prototype.isInitFootprints=function(){return this.stateTracker.openExecutionFoundOnce&&!this.footprintsEnqueueOnce};FootprintsProcess.prototype.hasOngoingRequests=function(){return this.ongoingRequestsCounter>0};FootprintsProcess.prototype.loadSlMapping=function(){return __awaiter(this,void 0,void 0,function(){var mappingsArr,flatted;return __generator(this,function(_a){switch(_a.label){case 0:if(!sl_env_vars_1.SlEnvVars.useSlMapping()){return[2]}return[4,this.backendProxy.getBlobsAsJson(this.cfg.buildSessionId.value)];case 1:mappingsArr=_a.sent();flatted={};mappingsArr.forEach(function(mapping){flatted=__assign(__assign({},flatted),mapping)});this.hitsConverter.slMapping=flatted;return[2]}})})};FootprintsProcess.ALARM_FIRED="alarm";return FootprintsProcess}();exports.FootprintsProcess=FootprintsProcess})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../footprints-process/collection-interval":323,"../state-tracker":332,"./footprints-buffer":317}],321:[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+"'"}}})},{}],322:[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;var RelativePathResolver=function(){function RelativePathResolver(projectRoot){this.absoluteToRelativePath=new Map;this.projectRoot=projectRoot}RelativePathResolver.prototype.getRelativePath=function(absolutePath){if(!this.absoluteToRelativePath.get(absolutePath)){absolutePath=this.adjustPathSlashes(absolutePath);var relativePath=absolutePath.replace(this.resolveProjectRoot(),"");if(relativePath.indexOf("/")===0){relativePath=relativePath.substring(1)}this.absoluteToRelativePath.set(absolutePath,relativePath)}return this.absoluteToRelativePath.get(absolutePath)};RelativePathResolver.prototype.adjustPathSlashes=function(filePath){return(filePath||"").replace(/\\/g,"/")};RelativePathResolver.prototype.resolveProjectRoot=function(){return(this.projectRoot||process.cwd()).replace(/\\/g,"/")};return RelativePathResolver}();exports.RelativePathResolver=RelativePathResolver})}).call(this)}).call(this,require("_process"))},{_process:179}],323:[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;var system_date_1=require("../system-date");var CollectionInterval=function(){function CollectionInterval(intervalInMS){this.intervalInSeconds=this.toSeconds(intervalInMS);this.start=this.toSeconds(system_date_1.getSystemDateValueOf())}CollectionInterval.prototype.next=function(){if(this.end){this.start=this.end}this.end=this.toSeconds(system_date_1.getSystemDateValueOf());if(this.end-this.start>this.intervalInSeconds){this.start=this.end-this.intervalInSeconds}};CollectionInterval.prototype.toJson=function(){return{start:this.start,end:this.end}};CollectionInterval.prototype.toSeconds=function(time){return Math.floor(time/1e3)};return CollectionInterval}();exports.CollectionInterval=CollectionInterval})},{"../system-date":333}],324:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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","./http-client","./sl-routes","../utils/validation-utils","./entities-mapper","../constants/constants","../constants/sl-env-vars","../utils/timer-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BackendProxy=void 0;var contracts_1=require("./contracts");var http_client_1=require("./http-client");var sl_routes_1=require("./sl-routes");var validation_utils_1=require("../utils/validation-utils");var entities_mapper_1=require("./entities-mapper");var constants_1=require("../constants/constants");var sl_env_vars_1=require("../constants/sl-env-vars");var timer_utils_1=require("../utils/timer-utils");var BackendProxy=function(){function BackendProxy(agentInstanceData,config,logger,httpClient){this.agentInstanceData=agentInstanceData;this.config=config;this.logger=logger;this.client=httpClient||new http_client_1.HttpClient(this.config,this.logger)}BackendProxy.prototype.getBuildSession=function(buildSessionId,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);var url=sl_routes_1.SLRoutes.buildSessionV2(buildSessionId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.createBuildSessionId=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildSessionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body,entities_mapper_1.EntitiesMapper.toCreateBuildSessionIdResponse)})};BackendProxy.prototype.createBuildSessionIdPromise=function(request){return __awaiter(this,void 0,void 0,function(){var url;var _this=this;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);url=constants_1.Constants.PULL_REQUEST_PARAMS in request?sl_routes_1.SLRoutes.prBuildSession():sl_routes_1.SLRoutes.buildSessionV2();return[2,new Promise(function(resolve,reject){_this.client.post(request,url,function(err,body){if(err){return reject(err)}return resolve(body)})})]})})};BackendProxy.prototype.getRecommendedVersion=function(request){var _this=this
|
|
32
|
-
;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.recommendedAgentV2(request.componentName,request.customerId,request.appName,request.branchName,request.testStage);return new Promise(function(resolve,reject){_this.client.get(url,function(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."))}})})};BackendProxy.prototype.submitBuildMapping=function(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildMappingV4();return this.submitPostRequestWithRetries(request,url)};BackendProxy.prototype.submitLogs=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.logSubmissionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfig=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfigPromise=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.configV3(_this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)})})};BackendProxy.prototype.startExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.startColoredExecution=function(request){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecution();_this.client.post(request,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.testExecutionV4=function(labId,async,executionId){var _this=this;if(async===void 0){async=true}return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecutionV4(labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)},false,async)})};BackendProxy.prototype.uploadReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalData();this.client.postMultipart(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.externalReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalReport();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;this.client.delete(body,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecutionPromise=function(request){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;return new Promise(function(resolve,reject){_this.client.delete(body,url,function(err){err?reject(err):resolve()})})};BackendProxy.prototype.submitEvents=function(packetToSend,callback,async){if(async===void 0){async=true}var url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,callback)};BackendProxy.prototype.submitEventsPromise=function(packetToSend){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.eventsV2();_this.client.post(packetToSend,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.submitBlobAsync=function(body,buildSessionId,blobId){var _this=this;var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,statusCode){_this.logger.debug("Blob "+blobId+" uploaded with status code "+statusCode);if(error){_this.logger.error("Error while submitting sl-mapping, '"+error+"'");return reject(error)}else{_this.logger.info("sl-mapping submitted successfully");return resolve({})}},true,contracts_1.ContentType.OCTET_STREAM)})};BackendProxy.prototype.submitBlob=function(body,buildSessionId,blobId,callback){var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);this.client.post(body,url,callback,true,contracts_1.ContentType.OCTET_STREAM)};BackendProxy.prototype.getBlobsAsJson=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var slMapping,url,e_1;return __generator(this,function(_a){switch(_a.label){case 0:slMapping=[];_a.label=1;case 1:_a.trys.push([1,3,,4]);url=sl_routes_1.SLRoutes.blobsForBsidAsJson(buildSessionId);return[4,this.submitGetRequestWithRetries(url)];case 2:slMapping=_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error(e_1);return[3,4];case 4:return[2,slMapping]}})})};BackendProxy.prototype.submitAgentEvent=function(body){var _this=this;var url=sl_routes_1.SLRoutes.agentEvents();return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,response){if(error){return reject(error)}return resolve()})})};BackendProxy.prototype.getTestsRecommendation=function(buildSessionId,stage){var url=sl_routes_1.SLRoutes.testsRecommendations(buildSessionId,stage);return this.submitGetRequestWithRetries(url,null,null,[400,404],false)};BackendProxy.prototype.addOrUpdateIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitPutRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.deleteIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitDelRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.buildEnd=function(data){return this.submitPostRequestWithRetries(data,sl_routes_1.SLRoutes.buildEnd())};BackendProxy.prototype.submitFootprintsV6=function(footprintsPacket,executionBsid,testStage,buildSessionId){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){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);url=sl_routes_1.SLRoutes.footprintsV6(executionBsid,testStage,buildSessionId);return[2,this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.OCTET_STREAM)]})})};BackendProxy.prototype.getBuildSessionData=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){return[2,new Promise(function(resolve,reject){_this.getBuildSession(buildSessionId,function(err,response){err?reject(err):resolve(response)})})]})})};BackendProxy.prototype.getRecommendedAgent=function(configuration){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,{}]})})};BackendProxy.prototype.getBuildSessionDataFromLabId=function(labid){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){url=sl_routes_1.SLRoutes.activeBuildSessionId(labid);return[2,this.submitGetRequestWithRetries(url)]})})};BackendProxy.prototype.invokeCallback=function(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)}var apiResponse=map(body);return callback(null,apiResponse)};BackendProxy.prototype.submitPostRequestWithRetries=function(body,url,retries,delayBetweenRetires,async,contentType){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.post(body,url,callback,async,contentType)},retries,delayBetweenRetires)};BackendProxy.prototype.submitPutRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.put(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitDelRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.delete(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitGetRequestWithRetries=function(url,retries,delayBetweenRetires,statusesForRetry,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}return this.makeRequestWithRetries(function(callback){_this.client.get(url,callback,isNotFoundAcceptable)},retries,delayBetweenRetires,statusesForRetry)};BackendProxy.prototype.makeRequestWithRetries=function(doSingleRequest,retries,delayBetweenRetires,statusesForRetry){return __awaiter(this,void 0,void 0,function(){var retriesLeft,intervalBetweenRetries,lastError,bodyAndStatusCode,errAndStatusCode_1;return __generator(this,function(_a){switch(_a.label){case 0:retriesLeft=retries||sl_env_vars_1.SlEnvVars.getHttpMaxAttempts()||BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS;intervalBetweenRetries=delayBetweenRetires||sl_env_vars_1.SlEnvVars.getHttpAttemptInterval()||BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL;lastError=undefined;_a.label=1;case 1:_a.trys.push([1,3,,4]);retriesLeft--;return[4,new Promise(function(resolve,reject){doSingleRequest(function(err,body,statusCode){err?reject({err:err,statusCode:statusCode}):resolve({body:body,statusCode:statusCode})})})];case 2:bodyAndStatusCode=_a.sent();return[2,bodyAndStatusCode.body];case 3:errAndStatusCode_1=_a.sent();this.logger.info(errAndStatusCode_1);lastError=errAndStatusCode_1.err;if(!this.shouldRetryRequest(errAndStatusCode_1.statusCode,statusesForRetry)){return[3,7]}return[3,4];case 4:return[4,timer_utils_1.TimerUtils.sleep(intervalBetweenRetries)];case 5:_a.sent();_a.label=6;case 6:if(retriesLeft>0)return[3,1];_a.label=7;case 7:throw lastError}})})};BackendProxy.prototype.shouldRetryRequest=function(statusCode,statusesForRetry){if(statusesForRetry===void 0){statusesForRetry=[]}if(statusCode>=500||statusCode&&statusesForRetry.includes(statusCode))return true;return false};BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS=6;BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL=5*1e3;return BackendProxy}();exports.BackendProxy=BackendProxy})},{"../constants/constants":304,"../constants/sl-env-vars":305,"../utils/timer-utils":336,"../utils/validation-utils":337,"./contracts":325,"./entities-mapper":326,"./http-client":327,"./sl-routes":329}],325:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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.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.HttpClientConfigData=void 0;var system_date_1=require("../system-date");var HttpClientConfigData=function(){function HttpClientConfigData(){}return HttpClientConfigData}();exports.HttpClientConfigData=HttpClientConfigData;var CreateBuildSessionIdResponse=function(){function CreateBuildSessionIdResponse(){}return CreateBuildSessionIdResponse}();exports.CreateBuildSessionIdResponse=CreateBuildSessionIdResponse;var GetVersionRequest=function(){function GetVersionRequest(){}return GetVersionRequest}();exports.GetVersionRequest=GetVersionRequest;var GetVersionResponse=function(){function GetVersionResponse(){}return GetVersionResponse}();exports.GetVersionResponse=GetVersionResponse;var AgentInfo=function(){function AgentInfo(){}return AgentInfo}();exports.AgentInfo=AgentInfo;var VersionMeta=function(){function VersionMeta(){}return VersionMeta}();exports.VersionMeta=VersionMeta;var VersionMetaQuery=function(){function VersionMetaQuery(){}return VersionMetaQuery}();exports.VersionMetaQuery=VersionMetaQuery;var BuildMappingRequest=function(){function BuildMappingRequest(){}return BuildMappingRequest}();exports.BuildMappingRequest=BuildMappingRequest;var DependencyData=function(){function DependencyData(){}return DependencyData}();exports.DependencyData=DependencyData;var FileData=function(){function FileData(){}return FileData}();exports.FileData=FileData;var GetRemoteConfigRequest=function(){function GetRemoteConfigRequest(){}return GetRemoteConfigRequest}();exports.GetRemoteConfigRequest=GetRemoteConfigRequest;var SubmitLogsRequest=function(){function SubmitLogsRequest(){this.creationTime=system_date_1.getSystemDateValueOf()}return SubmitLogsRequest}();exports.SubmitLogsRequest=SubmitLogsRequest;var BaseRequest=function(){function BaseRequest(){}return BaseRequest}();exports.BaseRequest=BaseRequest;var StartExecutionRequest=function(_super){__extends(StartExecutionRequest,_super);function StartExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return StartExecutionRequest}(BaseRequest);exports.StartExecutionRequest=StartExecutionRequest;var EndExecutionRequest=function(_super){__extends(EndExecutionRequest,_super);function EndExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return EndExecutionRequest}(BaseRequest);exports.EndExecutionRequest=EndExecutionRequest;var UploadReportRequest=function(_super){__extends(UploadReportRequest,_super);function UploadReportRequest(){return _super!==null&&_super.apply(this,arguments)||this}return UploadReportRequest}(BaseRequest);exports.UploadReportRequest=UploadReportRequest;var AgentData=function(){function AgentData(){}return AgentData}();exports.AgentData=AgentData;var EnvironmentData=function(){function EnvironmentData(){}return EnvironmentData}();exports.EnvironmentData=EnvironmentData;var UploadReportsBody=function(){function UploadReportsBody(){}return 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=exports.RecommendationSetStatus||(exports.RecommendationSetStatus={}));var ContentType;(function(ContentType){ContentType["OCTET_STREAM"]="application/octet-stream";ContentType["JSON"]="application/json"})(ContentType=exports.ContentType||(exports.ContentType={}))})},{"../system-date":333}],326:[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;var contracts_1=require("./contracts");var EntitiesMapper=function(){function EntitiesMapper(){}EntitiesMapper.toCreateBuildSessionIdResponse=function(body){if(body==null)return null;var response=new contracts_1.CreateBuildSessionIdResponse;response.buildSessionId=body;return response};return EntitiesMapper}();exports.EntitiesMapper=EntitiesMapper})},{"./contracts":325}],327:[function(require,module,exports){(function(process,Buffer){(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","./contracts","request","zlib","uuid/v1","../constants/sl-env-vars","./http-verb","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var contracts_1=require("./contracts");var request=require("request");var zlib=require("zlib");var uuid=require("uuid/v1");var sl_env_vars_1=require("../constants/sl-env-vars");var http_verb_1=require("./http-verb");var validation_utils_1=require("../utils/validation-utils");var HttpClient=function(){function HttpClient(cfg,logger){this.cfg=cfg;this.logger=logger;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"cfg");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.defaultTimeout=this.getDefaultTimeout()}HttpClient.prototype.get=function(urlPath,callback,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}this.invokeHttpRequest(http_verb_1.HttpVerb.GET,urlPath,callback,null,null,null,isNotFoundAcceptable)};HttpClient.prototype.delete=function(body,urlPath,callback){this.invokeHttpRequest(http_verb_1.HttpVerb.DELETE,urlPath,callback,null,body)};HttpClient.prototype.put=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.PUT,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.post=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.POST,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.postMultipart=function(requestData,urlPath,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.agentData,"requestData.agentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.reportFile,"requestData.reportFile");var agentData=requestData.agentData;var reportFile=requestData.reportFile;try{var opts=this.createDefaultOptions(urlPath);var id=uuid();var onRequestCallback=this.createOnRequestCallback(http_verb_1.HttpVerb.POST,id,callback);this.logger.info("Sending "+http_verb_1.HttpVerb.POST+" request. Url: '"+opts.url+"', requestId: '"+id+"'");var req=request.post(opts,onRequestCallback);var form=req.form();form.append("file",JSON.stringify(agentData),{filename:"agentData",contentType:"multipart/form-data"});form.append("file",reportFile.buffer.toString(),{filename:"report",contentType:"multipart/form-data"})}catch(err){this.logger.error("Failed sending Http "+http_verb_1.HttpVerb.POST+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.submitRequestWithBody=function(verb,requestData,urlPath,callback,async,contentType){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");var bufferToSend=Buffer.from(JSON.stringify(requestData));var shouldZip=this.cfg.compressRequests!=null?this.cfg.compressRequests:true;this.logger.debug("Sending buffer:"+bufferToSend.toString());if(shouldZip){zlib.gzip(bufferToSend,function(err,compressedBuf){if(err){_this.logger.warn("Failed while trying to compress the request data. Sending uncompressed data instead. Error: ",err);_this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}else{_this.invokeHttpRequest(verb,urlPath,callback,{"Content-Encoding":"gzip"},compressedBuf,contentType)}})}else{this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}};HttpClient.prototype.invokeHttpRequest=function(httpVerb,urlPath,callback,additionalHeaders,buffer,contentType,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(httpVerb,"httpVerb");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(urlPath,"urlPath");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,"callback");try{var opts=this.createDefaultOptions(urlPath,contentType);if(additionalHeaders){for(var header in additionalHeaders){opts.headers[header]=additionalHeaders[header]}}var id=uuid();var onRequestCallback=this.createOnRequestCallback(httpVerb,id,callback,isNotFoundAcceptable);this.logger.info("Sending "+httpVerb+" request. Url: '"+opts.url+"', requestId: '"+id+"'");if(httpVerb===http_verb_1.HttpVerb.GET){opts.json=true;request.get(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.DELETE){if(buffer)opts.body=buffer;opts.json=true;request.delete(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.POST){opts.body=buffer;request.post(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.PUT){opts.body=buffer;request.put(opts,onRequestCallback)}else{new Error(httpVerb+" is not implemented yet.")}}catch(err){this.logger.error("Failed sending Http "+httpVerb+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.createOnRequestCallback=function(httpVerb,requestId,callback,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}var handler=function(err,requestResponse,body){var txId=requestResponse&&requestResponse.headers&&requestResponse.headers["x-sl-txid"];if(err||requestResponse!=null&&(requestResponse.statusCode<200||requestResponse.statusCode>=400)){var statusCode=-1;if(requestResponse!=null){statusCode=requestResponse.statusCode;_this.logger.warn("Got "+statusCode+" in '"+httpVerb+"' request. Request id:'"+requestId+"', Transaction ID:'"+txId+"'.")}if(err){err=new Error("HttpClient failed. Error: "+err.message+", StatusCode: "+statusCode+", Stack: "+err.stack)}else if(statusCode===404&&isNotFoundAcceptable){err=null}else{var errorMessage="Server returned: "+statusCode+" status code in '"+httpVerb+"' request. Transaction ID:'"+txId+"'.";try{if(body)errorMessage+=Object.entries(JSON.parse(body)).map(function(_a){var key=_a[0],val=_a[1];return"\n\t"+key+": "+val}).join("")}catch(e){errorMessage+=" Parsing of server response failed, body: "+body+", request id:'"+requestId+"',error: "+e}err=new Error(errorMessage)}return callback(err,body,statusCode)}_this.logger.debug("'"+httpVerb+"' request was completed successfully. Request id:'"+requestId+"'. statusCode: "+requestResponse.statusCode+" body: "+body+", Transaction ID: "+txId);if(body&&body.length>0&&typeof body=="string"){try{body=JSON.parse(body)}catch(e){_this.logger.error("An error occurred parsing the body: ["+body+"], error: "+e)}}return callback(null,body,requestResponse.statusCode)};return handler};HttpClient.prototype.allowUntrustedCertificates=function(){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"};HttpClient.prototype.createDefaultOptions=function(urlPath,contentType){if(contentType===void 0){contentType=contracts_1.ContentType.JSON}var opts={url:this.cfg.server+urlPath,headers:{"Content-Type":contentType,Authorization:"Bearer "+this.cfg.token},timeout:this.defaultTimeout};opts["compressed"]=true;if(this.cfg.proxy!=null){opts.proxy=this.cfg.proxy;this.allowUntrustedCertificates()}return opts};HttpClient.prototype.getDefaultTimeout=function(){var timeout=sl_env_vars_1.SlEnvVars.getHttpTimeout();if(timeout==null){timeout=60*1e3*2}timeout=Number(timeout);this.logger.debug("Http timeout value is '"+timeout+"'.");return timeout};return HttpClient}();exports.HttpClient=HttpClient})}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"../constants/sl-env-vars":305,"../utils/validation-utils":337,"./contracts":325,"./http-verb":328,_process:179,buffer:71,request:454,"uuid/v1":510,zlib:68}],328:[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.HttpVerb=void 0;var HttpVerb;(function(HttpVerb){HttpVerb["GET"]="GET";HttpVerb["POST"]="POST";HttpVerb["DELETE"]="DELETE";HttpVerb["PUT"]="PUT"})(HttpVerb=exports.HttpVerb||(exports.HttpVerb={}))})},{}],329:[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;var constants_1=require("../constants/constants");var validation_utils_1=require("../utils/validation-utils");var SLRoutes=function(){function SLRoutes(){}SLRoutes.agentsV1=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV2=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV3=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV4=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV5=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V5)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV6=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V6)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.testExecution=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)};SLRoutes.testExecutionV4=function(labId,executionId){var url=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)+SLRoutes.toUri(labId);if(executionId){url+=SLRoutes.buildQueryParams({executionId:executionId})}return url};SLRoutes.endExecution=function(customerId,appName,buildName,branchName,environment){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(appName,"appName");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(customerId,"customerId");var result=SLRoutes.testExecution();var query={customerId:customerId,appName:appName,buildName:buildName,branchName:branchName,environment:environment};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.externalData=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.EXTERNAL_DATA)};SLRoutes.externalReport=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.EXTERNAL_REPORT)};SLRoutes.configV3=function(agentInstanceData,appName,branchName,buildName,testStage,labId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.CONFIG;var 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};SLRoutes.buildSessionV2=function(buildSessionId){var result=SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.BUILD_SESSION_ID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.prBuildSession=function(){return SLRoutes.buildSessionV2()+SLRoutes.toUri(SLRoutes.PULL_REQUEST)};SLRoutes.logSubmissionV2=function(){var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.LOG_SUBMISSION;return result};SLRoutes.buildMappingV4=function(){var result=SLRoutes.agentsV4()+SLRoutes.toUri(SLRoutes.BUILD_MAPPING);return result};SLRoutes.footprintsV5=function(){var result=SLRoutes.agentsV5()+SLRoutes.toUri(SLRoutes.FOOTPRINTS);return result};SLRoutes.footprintsV6=function(executionBsid,testStage,buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(executionBsid)+SLRoutes.toUri(SLRoutes.FOOTPRINTS)+SLRoutes.toUri(testStage)+SLRoutes.toUri(buildSessionId)};SLRoutes.eventsV2=function(){return SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.EVENTS)};SLRoutes.productionV1=function(buildSessionId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,"buildSessionId");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)+SLRoutes.toUri(SLRoutes.PRODUCTION)+SLRoutes.toUri(SLRoutes.BSID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.recommendedAgentV2=function(component,customerId,appName,branchName,testStage){if(!component){throw new Error("'component' "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}var result=SLRoutes.agentsV2()+SLRoutes.toUri(component)+SLRoutes.toUri(SLRoutes.RECOMMENDED_VERSION);var query={customerId:customerId,appName:appName,branch:branchName,envName:testStage};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.blobs=function(buildSessionId,blobId){return SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(blobId)};SLRoutes.blobsForBsidAsJson=function(buildSessionId){var url=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId);url=url.slice(0,-1);return url+SLRoutes.buildQueryParams({view:"concatJson"})};SLRoutes.agentEvents=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.AGENT_EVENTS)};SLRoutes.testsRecommendations=function(buildSessionId,stage){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)};SLRoutes.integrationBuildComponents=function(buildSessionId){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.AGENTS+SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.INTEGRATION_BUILDS)+SLRoutes.toUri(buildSessionId)+SLRoutes.COMPONENTS};SLRoutes.buildEnd=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.BUILD_END)};SLRoutes.activeBuildSessionId=function(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)};SLRoutes.toUri=function(uri){
|
|
33
|
-
if(uri==null||uri.length==null||uri.length===0){return""}return encodeURIComponent(uri)+SLRoutes.SLASH};SLRoutes.buildQueryParams=function(paramsMap){if(!paramsMap){throw new Error("'paramsMap' cannot be null or undefined.")}var queryString="";for(var key in paramsMap){var value=paramsMap[key];queryString+=SLRoutes.addQueryStringValue(key,value)}queryString="?"+queryString;queryString=queryString.substring(0,queryString.length-1);return queryString};SLRoutes.addQueryStringValue=function(key,value){if(!key&&!value)return"";if(!value){value=""}var paramString="";paramString+=encodeURIComponent(key);paramString+="=";paramString+=encodeURIComponent(value);paramString+="&";return paramString};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";return SLRoutes}();exports.SLRoutes=SLRoutes})},{"../constants/constants":304,"../utils/validation-utils":337}],330:[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;var fs=require("fs");var sourceMap=require("source-map");var SourceMapsUtils=function(){function SourceMapsUtils(){}SourceMapsUtils.readSourceMaps=function(fullFilename){if(!fullFilename)return;var sourceMapsFilename=fullFilename+".map";var 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}};return SourceMapsUtils}();exports.SourceMapsUtils=SourceMapsUtils})},{fs:69,"source-map":228}],331:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var state_tracker_1=require("./state-tracker");var StateTrackerFpv6=function(_super){__extends(StateTrackerFpv6,_super);function StateTrackerFpv6(){return _super!==null&&_super.apply(this,arguments)||this}StateTrackerFpv6.prototype.switchToAnonFootprints=function(){};StateTrackerFpv6.prototype.isAnonymousColor=function(testIdentifier){return testIdentifier==null};StateTrackerFpv6.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this.currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})};return StateTrackerFpv6}(state_tracker_1.StateTracker);exports.StateTrackerFpv6=StateTrackerFpv6})},{"./state-tracker":332}],332:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var events=require("events");var sl_env_vars_1=require("./constants/sl-env-vars");var validation_utils_1=require("./utils/validation-utils");var cockpit_notifier_1=require("./agent-events/cockpit-notifier");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var INITIAL_COLOR="00000000-0000-0000-0000-000000000000/__init";var StateTracker=function(_super){__extends(StateTracker,_super);function StateTracker(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){var _this=_super.call(this)||this;_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");_this.cfg=cfg;_this.configProcess=configProcess;_this.checkTestStatusWatchdog=checkTestStatusWatchdog;_this.backendProxy=backendProxy;_this.logger=logger;if(_this.cfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}configProcess.on("configuration_changed",function(newCfg){if(newCfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}_this.cfg=newCfg;_this.checkTestStatusWatchdog.setInterval(newCfg.executionQueryIntervalSecs.value)});_this.startCheckingTestStatusAtServer();return _this}StateTracker.prototype.startCheckingTestStatusAtServer=function(){var _this=this;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",function(){_this.checkTestStatusAtServer()});if(this.cfg.shouldCheckForActiveExecutionOnStartUp.value){this.checkTestStatusAtServer(false)}};StateTracker.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}if(!this.currentTestIdentifier){this.logger.info("'currentTestIdentifier' is null. That means that footprints will not be sent.")}else{this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this._currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})}};StateTracker.prototype.getExecutionIdForQuery=function(){if(this.isAnonymousColor(this.currentTestIdentifier)||!this.currentExecution){return null}return this.currentExecution.executionId};StateTracker.prototype.hasMappingAtServer=function(){return this._currentExecution!=null};StateTracker.prototype.shouldCollectHits=function(){return this.hasMappingAtServer()&&this.currentExecution.executionId!==this.pendingDeleteExecId};Object.defineProperty(StateTracker.prototype,"currentExecution",{get:function(){return this._currentExecution},set:function(value){this._currentExecution=value},enumerable:false,configurable:true});Object.defineProperty(StateTracker.prototype,"openExecutionFoundOnce",{get:function(){return this._openExecutionFoundOnce},enumerable:false,configurable:true});StateTracker.prototype.isAnonymousColor=function(testIdentifier){return INITIAL_COLOR==testIdentifier};StateTracker.prototype.switchToAnonFootprints=function(){this.logger.info("Switching to anonymous footprints.");this.setTestIdentifier(INITIAL_COLOR,false)};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentTestIdentifier};StateTracker.prototype.setTestIdentifier=function(newTestIdentifier,silent){this.logger.info("setting test identifier: "+newTestIdentifier);if(this.currentTestIdentifier==null&&newTestIdentifier!=null||this.currentTestIdentifier!=null&&this.currentTestIdentifier!=newTestIdentifier&&newTestIdentifier!=INITIAL_COLOR){var 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+"'")}};StateTracker.prototype.setCurrentTestIdentifier=function(newTestIdentifier){this.setTestIdentifier(newTestIdentifier)};StateTracker.prototype.start=function(){if(!this.isRunning){this.checkTestStatusWatchdog.start();this.isRunning=true}};StateTracker.prototype.stop=function(){try{if(!this.isRunning){return}this.checkTestStatusWatchdog.stop();this.isRunning=false}catch(err){this.logger.error("Error while stopping StateTracker. '"+err+"'");return}};StateTracker.prototype.getTestStage=function(){var _a;return(_a=this.currentExecution)===null||_a===void 0?void 0:_a.testStage};StateTracker.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId){testName=""}return{executionId:executionId,testName:testName}};StateTracker.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId){return""}return executionId+"/"+testName};StateTracker.prototype.startColoredExecution=function(executionId){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);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};return[4,this.backendProxy.startColoredExecution(request)];case 1:_a.sent();this.currentExecution=__assign(__assign({},request),{buildSessionId:this.cfg.buildSessionId.value,status:StateTracker.EXECUTION_STATUS_CREATED});return[3,3];case 2:e_1=_a.sent();this.logger.error("Failed to create execution, error '"+e_1+"'. Footprints will not be sent");return[3,3];case 3:return[2]}})})};StateTracker.prototype.fireExecutionEvents=function(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}};StateTracker.prototype.notifyCockpit=function(execution){if(!execution){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_NO_EXECUTION)}else{cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_HAS_EXECUTION);this._openExecutionFoundOnce=true}};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";return StateTracker}(events.EventEmitter);exports.StateTracker=StateTracker})},{"./agent-events/agent-events-conracts":289,"./agent-events/cockpit-notifier":294,"./constants/sl-env-vars":305,"./utils/validation-utils":337,events:110}],333:[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;var SystemDate=Date;var SystemDateValueOf=Date.prototype.valueOf;function getSystemDate(){return new SystemDate}exports.getSystemDate=getSystemDate;function getSystemDateValueOf(){var date=getSystemDate();return SystemDateValueOf.call(date)}exports.getSystemDateValueOf=getSystemDateValueOf})},{}],334:[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;var path=require("path");var fs=require("fs");var FilesUtils=function(){function FilesUtils(){}FilesUtils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};FilesUtils.prototype.fixPathAndSpecialChar=function(path){if(path){if(path[0]==="/"||path[0]==="\\"){return path.substr(1).split("\\").join("/")}return path.split("\\").join("/")}return path};FilesUtils.adjustPathSlashes=function(filePath){filePath=(filePath||"").replace(/\\/g,"/");return filePath};FilesUtils.findFileUp=function(file,folder){var parsed=path.parse(folder);var filePath=path.join(folder,file);if(fs.existsSync(filePath)){return filePath}if(path.resolve(folder)===parsed.root||folder==="."){return null}var parentFolder=path.join(folder,"..");parentFolder=path.normalize(parentFolder);return FilesUtils.findFileUp(file,parentFolder)};return FilesUtils}();exports.FilesUtils=FilesUtils})},{fs:69,path:171}],335:[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.ParsingUtils=void 0;var ParsingUtils=function(){function ParsingUtils(){}ParsingUtils.parseNumber=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null){var valueAsNumber=Number.parseFloat(valueFromEnv);if(!isNaN(valueAsNumber)){valueFromEnv=valueAsNumber}else{valueFromEnv=null}}return valueFromEnv};ParsingUtils.parseBoolean=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null&&typeof valueFromEnv=="string"){valueFromEnv=valueFromEnv.toLowerCase()}return valueFromEnv=="true"};return ParsingUtils}();exports.ParsingUtils=ParsingUtils})}).call(this)}).call(this,require("_process"))},{_process:179}],336:[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;var TimerUtils=function(){function TimerUtils(){}TimerUtils.sleep=function(timeout){return new Promise(function(resolve){setTimeout(resolve,timeout)})};return TimerUtils}();exports.TimerUtils=TimerUtils})},{}],337:[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;var constants_1=require("../constants/constants");var ValidationUtils=function(){function ValidationUtils(){}ValidationUtils.verifyNotNullOrEmpty=function(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+".")}};return ValidationUtils}();exports.ValidationUtils=ValidationUtils})},{"../constants/constants":304}],338:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var events=require("events");var WatchdogOptions=function(){function WatchdogOptions(){}return WatchdogOptions}();exports.WatchdogOptions=WatchdogOptions;var Watchdog=function(_super){__extends(Watchdog,_super);function Watchdog(options,timers){var _this=_super.call(this)||this;_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")}return _this}Watchdog.prototype.abort=function(){if(this.handle){this.timers.clearTimeout(this.handle);this.handle=null;this.pendingAlarmDuringSuspended=false}};Watchdog.prototype.reset=function(){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()}}};Watchdog.prototype.stop=function(){this.stopped=true;this.abort()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{pendingAlarmDuringSuspended:this.pendingAlarmDuringSuspended,running:!this.stopped,suspended:this.suspended}};Watchdog.prototype.suspend=function(){this.suspended=true};Watchdog.prototype.resume=function(){this.suspended=false;if(this.pendingAlarmDuringSuspended){this.pendingAlarmDuringSuspended=false;this.fireAlarm()}};Watchdog.prototype.fireAlarm=function(){this.handle=null;if(this.suspended){this.pendingAlarmDuringSuspended=true}else{try{this.emit("alarm",this)}catch(err){}}if(this.options.autoReset){this.reset()}};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.options.interval=newInterval};Watchdog.prototype.getInterval=function(){return this.options.interval};return Watchdog}(events.EventEmitter);exports.Watchdog=Watchdog})},{events:110}],339:[function(require,module,exports){"use strict";var compileSchema=require("./compile"),resolve=require("./compile/resolve"),Cache=require("./cache"),SchemaObject=require("./compile/schema_obj"),stableStringify=require("fast-json-stable-stringify"),formats=require("./compile/formats"),rules=require("./compile/rules"),$dataMetaSchema=require("./data"),util=require("./compile/util");module.exports=Ajv;Ajv.prototype.validate=validate;Ajv.prototype.compile=compile;Ajv.prototype.addSchema=addSchema;Ajv.prototype.addMetaSchema=addMetaSchema;Ajv.prototype.validateSchema=validateSchema;Ajv.prototype.getSchema=getSchema;Ajv.prototype.removeSchema=removeSchema;Ajv.prototype.addFormat=addFormat;Ajv.prototype.errorsText=errorsText;Ajv.prototype._addSchema=_addSchema;Ajv.prototype._compile=_compile;Ajv.prototype.compileAsync=require("./compile/async");var customKeyword=require("./keyword");Ajv.prototype.addKeyword=customKeyword.add;Ajv.prototype.getKeyword=customKeyword.get;Ajv.prototype.removeKeyword=customKeyword.remove;Ajv.prototype.validateKeyword=customKeyword.validate;var errorClasses=require("./compile/error_classes");Ajv.ValidationError=errorClasses.Validation;Ajv.MissingRefError=errorClasses.MissingRef;Ajv.$dataMetaSchema=$dataMetaSchema;var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var META_SUPPORT_DATA=["/properties"];function Ajv(opts){if(!(this instanceof Ajv))return new Ajv(opts);opts=this._opts=util.copy(opts)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=formats(opts.format);this._cache=opts.cache||new Cache;this._loadingSchemas={};this._compilations=[];this.RULES=rules();this._getId=chooseGetId(opts);opts.loopRequired=opts.loopRequired||Infinity;if(opts.errorDataPath=="property")opts._errorDataPathProperty=true;if(opts.serialize===undefined)opts.serialize=stableStringify;this._metaOpts=getMetaSchemaOptions(this);if(opts.formats)addInitialFormats(this);if(opts.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof opts.meta=="object")this.addMetaSchema(opts.meta);if(opts.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(schemaKeyRef,data){var v;if(typeof schemaKeyRef=="string"){v=this.getSchema(schemaKeyRef);if(!v)throw new Error('no schema with key or ref "'+schemaKeyRef+'"')}else{var schemaObj=this._addSchema(schemaKeyRef);v=schemaObj.validate||this._compile(schemaObj)}var valid=v(data);if(v.$async!==true)this.errors=v.errors;return valid}function compile(schema,_meta){var schemaObj=this._addSchema(schema,undefined,_meta);return schemaObj.validate||this._compile(schemaObj)}function addSchema(schema,key,_skipValidation,_meta){if(Array.isArray(schema)){for(var i=0;i<schema.length;i++)this.addSchema(schema[i],undefined,_skipValidation,_meta);return this}var id=this._getId(schema);if(id!==undefined&&typeof id!="string")throw new Error("schema id must be string");key=resolve.normalizeId(key||id);checkUnique(this,key);this._schemas[key]=this._addSchema(schema,_skipValidation,_meta,true);return this}function addMetaSchema(schema,key,skipValidation){this.addSchema(schema,key,skipValidation,true);return this}function validateSchema(schema,throwOrLogError){var $schema=schema.$schema;if($schema!==undefined&&typeof $schema!="string")throw new Error("$schema must be a string");$schema=$schema||this._opts.defaultMeta||defaultMeta(this);if(!$schema){this.logger.warn("meta-schema not available");this.errors=null;return true}var valid=this.validate($schema,schema);if(!valid&&throwOrLogError){var message="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(message);else throw new Error(message)}return valid}function defaultMeta(self){var meta=self._opts.meta;self._opts.defaultMeta=typeof meta=="object"?self._getId(meta)||meta:self.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:undefined;return self._opts.defaultMeta}function getSchema(keyRef){var schemaObj=_getSchemaObj(this,keyRef);switch(typeof schemaObj){case"object":return schemaObj.validate||this._compile(schemaObj);case"string":return this.getSchema(schemaObj);case"undefined":return _getSchemaFragment(this,keyRef)}}function _getSchemaFragment(self,ref){var res=resolve.schema.call(self,{schema:{}},ref);if(res){var schema=res.schema,root=res.root,baseId=res.baseId;var v=compileSchema.call(self,schema,root,undefined,baseId);self._fragments[ref]=new SchemaObject({ref:ref,fragment:true,schema:schema,root:root,baseId:baseId,validate:v});return v}}function _getSchemaObj(self,keyRef){keyRef=resolve.normalizeId(keyRef);return self._schemas[keyRef]||self._refs[keyRef]||self._fragments[keyRef]}function removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp){_removeAllSchemas(this,this._schemas,schemaKeyRef);_removeAllSchemas(this,this._refs,schemaKeyRef);return this}switch(typeof schemaKeyRef){case"undefined":_removeAllSchemas(this,this._schemas);_removeAllSchemas(this,this._refs);this._cache.clear();return this;case"string":var schemaObj=_getSchemaObj(this,schemaKeyRef);if(schemaObj)this._cache.del(schemaObj.cacheKey);delete this._schemas[schemaKeyRef];delete this._refs[schemaKeyRef];return this;case"object":var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schemaKeyRef):schemaKeyRef;this._cache.del(cacheKey);var id=this._getId(schemaKeyRef);if(id){id=resolve.normalizeId(id);delete this._schemas[id];delete this._refs[id]}}return this}function _removeAllSchemas(self,schemas,regex){for(var keyRef in schemas){var schemaObj=schemas[keyRef];if(!schemaObj.meta&&(!regex||regex.test(keyRef))){self._cache.del(schemaObj.cacheKey);delete schemas[keyRef]}}}function _addSchema(schema,skipValidation,meta,shouldAddSchema){if(typeof schema!="object"&&typeof schema!="boolean")throw new Error("schema should be object or boolean");var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schema):schema;var cached=this._cache.get(cacheKey);if(cached)return cached;shouldAddSchema=shouldAddSchema||this._opts.addUsedSchema!==false;var id=resolve.normalizeId(this._getId(schema));if(id&&shouldAddSchema)checkUnique(this,id);var willValidate=this._opts.validateSchema!==false&&!skipValidation;var recursiveMeta;if(willValidate&&!(recursiveMeta=id&&id==resolve.normalizeId(schema.$schema)))this.validateSchema(schema,true);var localRefs=resolve.ids.call(this,schema);var schemaObj=new SchemaObject({id:id,schema:schema,localRefs:localRefs,cacheKey:cacheKey,meta:meta});if(id[0]!="#"&&shouldAddSchema)this._refs[id]=schemaObj;this._cache.put(cacheKey,schemaObj);if(willValidate&&recursiveMeta)this.validateSchema(schema,true);return schemaObj}function _compile(schemaObj,root){if(schemaObj.compiling){schemaObj.validate=callValidate;callValidate.schema=schemaObj.schema;callValidate.errors=null;callValidate.root=root?root:callValidate;if(schemaObj.schema.$async===true)callValidate.$async=true;return callValidate}schemaObj.compiling=true;var currentOpts;if(schemaObj.meta){currentOpts=this._opts;this._opts=this._metaOpts}var v;try{v=compileSchema.call(this,schemaObj.schema,root,schemaObj.localRefs)}catch(e){delete schemaObj.validate;throw e}finally{schemaObj.compiling=false;if(schemaObj.meta)this._opts=currentOpts}schemaObj.validate=v;schemaObj.refs=v.refs;schemaObj.refVal=v.refVal;schemaObj.root=v.root;return v;function callValidate(){var _validate=schemaObj.validate;var result=_validate.apply(this,arguments);callValidate.errors=_validate.errors;return result}}function chooseGetId(opts){switch(opts.schemaId){case"auto":return _get$IdOrId;case"id":return _getId;default:return _get$Id}}function _getId(schema){if(schema.$id)this.logger.warn("schema $id ignored",schema.$id);return schema.id}function _get$Id(schema){if(schema.id)this.logger.warn("schema id ignored",schema.id);return schema.$id}function _get$IdOrId(schema){if(schema.$id&&schema.id&&schema.$id!=schema.id)throw new Error("schema $id is different from id");return schema.$id||schema.id}function errorsText(errors,options){errors=errors||this.errors;if(!errors)return"No errors";options=options||{};var separator=options.separator===undefined?", ":options.separator;var dataVar=options.dataVar===undefined?"data":options.dataVar;var text="";for(var i=0;i<errors.length;i++){var e=errors[i];if(e)text+=dataVar+e.dataPath+" "+e.message+separator}return text.slice(0,-separator.length)}function addFormat(name,format){
|
|
28
|
+
;this._tags=__spreadArrays(this._tags||[],tags||[])};AgentEventsController.prototype.addTool=function(tollInfo){if(!tollInfo)return;this._tools=this._tools||[];this._tools.push(tollInfo)};AgentEventsController.prototype.createBackendProxy=function(){var httpConfig={token:this._agentConfig.token.value,proxy:this._agentConfig.proxy.value,server:this._agentConfig.server.value,compressRequests:this._agentConfig.gzip.value};return new backend_proxy_1.BackendProxy(this._agentInstanceData,httpConfig,this._logger)};AgentEventsController.prototype.initWatchdog=function(){var watchdogOptions={interval:AgentEventsController.PING_INTERVAL,name:"AgentEventsWatchdog",autoReset:true,unref:true};var timers=this.getTimers();this._pingWatchdog=new watchdog_1.Watchdog(watchdogOptions,timers);this._pingWatchdog.on("alarm",this.submitPingEvent.bind(this))};AgentEventsController.prototype.getTimers=function(){if(this._agentInstanceData.technology===agent_events_conracts_1.Technology.BROWSER){return{setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window)}}else{return{setTimeout:setTimeout,clearTimeout:clearTimeout}}};AgentEventsController.prototype.buildEvent=function(type,data){return{type:type,utcTimestamp_ms:system_date_1.getSystemDateValueOf(),data:data}};Object.defineProperty(AgentEventsController.prototype,"agentInstanceData",{get:function(){return this._agentInstanceData},enumerable:false,configurable:true});AgentEventsController.PING_INTERVAL=2*60*1e3;AgentEventsController.MAX_SHUTDOWN_RETRIES=60;return AgentEventsController}();exports.AgentEventsController=AgentEventsController;var StartRequestStatus;(function(StartRequestStatus){StartRequestStatus["FAILED"]="failed";StartRequestStatus["SUCCEED"]="succeed";StartRequestStatus["PENDING"]="pending"})(StartRequestStatus||(StartRequestStatus={}))})},{"../http/backend-proxy":324,"../system-date":333,"../utils/validation-utils":337,"../watchdog":338,"./agent-events-conracts":289,"./agent-instance-info-builder":291,"./agent-start-info-builder":292,"./ci-info-builder":293,"./machine-info-builder":296,"./nodejs-env-info-builder":297}],291:[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;var sensitive_data_filter_1=require("./sensitive-data-filter");var SEALIGHTS_ENV_VAR_PREFIX="SL_";var AgentInstanceInfoBuilder=function(){function AgentInstanceInfoBuilder(agentEventsController){this.sendsPing=true;this.agentConfig=agentEventsController.agentConfig;this.agentId=agentEventsController.agentInstanceData.agentId;this.agentType=agentEventsController.agentInstanceData.agentType;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}}AgentInstanceInfoBuilder.prototype.fillData=function(){this.info.tags=this.tags;this.info.tools=this.tools;this.info.technology=this.technology;this.info.sendsPing=this.sendsPing;this.fillFromAgentConfig();this.fillFromProcessObject()};AgentInstanceInfoBuilder.prototype.build=function(){this.fillData();return this.info};AgentInstanceInfoBuilder.prototype.fillFromAgentConfig=function(){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()};AgentInstanceInfoBuilder.prototype.fillFromProcessObject=function(){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()};AgentInstanceInfoBuilder.prototype.extractSealightsEnvVars=function(){var _this=this;var slEnvVars={};Object.keys(process.env).forEach(function(key){if(key.indexOf(SEALIGHTS_ENV_VAR_PREFIX)===0||key==="NODE_OPTIONS"){slEnvVars[key]=sensitive_data_filter_1.isSensitive(key,process.env[key],_this.logger)?AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER:process.env[key]}});return slEnvVars};AgentInstanceInfoBuilder.DEFAULT_BROWSER_AGENT_VERSION="1.0.0";AgentInstanceInfoBuilder.SEALIGHTS_WINDOW_OBJECT="$Sealights";AgentInstanceInfoBuilder.SECRET_VALUE_PLACEHOLDER="********";return AgentInstanceInfoBuilder}();exports.AgentInstanceInfoBuilder=AgentInstanceInfoBuilder})}).call(this)}).call(this,require("_process"))},{"./sensitive-data-filter":298,_process:179}],292:[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.AgentStartInfoBuilder=void 0;var AgentStartInfoBuilder=function(){function AgentStartInfoBuilder(agentInstanceInfoBuilder,machineInfoBuilder,techSpecificInfoBuilder,ciInfoBuilder){this.agentInstanceInfoBuilder=agentInstanceInfoBuilder;this.machineInfoBuilder=machineInfoBuilder;this.techSpecificInfoBuilder=techSpecificInfoBuilder;this.ciInfoBuilder=ciInfoBuilder}AgentStartInfoBuilder.prototype.fillData=function(){};AgentStartInfoBuilder.prototype.build=function(){return{agentInfo:this.agentInstanceInfoBuilder.build(),machineInfo:this.machineInfoBuilder.build(),techSpecificInfo:this.techSpecificInfoBuilder.build(),ciInfo:this.ciInfoBuilder.build()}};return AgentStartInfoBuilder}();exports.AgentStartInfoBuilder=AgentStartInfoBuilder})},{}],293:[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;var JENKINS_JOB_NAME_ENV="JOB_NAME";var JENKINS_JOB_ID_ENV="BUILD_ID";var JENKINS_JOB_URL_ENV="BUILD_URL";var CiInfoBuilder=function(){function CiInfoBuilder(){this.info={}}CiInfoBuilder.prototype.fillData=function(){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]}};CiInfoBuilder.prototype.isJenkins=function(){return process.env[JENKINS_JOB_ID_ENV]&&process.env[JENKINS_JOB_NAME_ENV]&&process.env[JENKINS_JOB_URL_ENV]};CiInfoBuilder.prototype.build=function(){this.fillData();return this.info};return CiInfoBuilder}();exports.CiInfoBuilder=CiInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],294:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.CockpitNotifier=void 0;var agent_events_controller_1=require("./agent-events-controller");var dry_run_agent_events_controller_1=require("./dry-run-agent-events-controller");var CockpitNotifier=function(){function CockpitNotifier(){}CockpitNotifier.notifyStart=function(agentConfig,agentInstanceData,logger,packageJsonFile,backendProxy,tool,tags){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.controller=new agent_events_controller_1.AgentEventsController(agentConfig,agentInstanceData,logger,backendProxy,tool,tags);return[4,CockpitNotifier.controller.submitAgentStartedEvent(packageJsonFile)];case 1:_a.sent();return[2]}})})};CockpitNotifier.notifyShutdown=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:CockpitNotifier.verifyControllerInitialized();return[4,CockpitNotifier.controller.submitAgentShutdownEvent()];case 1:_a.sent();return[2]}})})};CockpitNotifier.sendGenericMessage=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitGenericMessage(message)};CockpitNotifier.sendWarning=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitWarning(message)};CockpitNotifier.sendError=function(message){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitError(message)};CockpitNotifier.sendErrorsBatch=function(messages){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitErrorsBatch(messages)};CockpitNotifier.sendEvent=function(code,data){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEvent(code,data)};CockpitNotifier.sendEventOnce=function(code){CockpitNotifier.verifyControllerInitialized();CockpitNotifier.controller.submitEventOnce(code)};CockpitNotifier.verifyControllerInitialized=function(){if(!CockpitNotifier.controller&&!CockpitNotifier.isDryRunMode){throw new Error("'Agent started' event was not sent. Disabling!")}};CockpitNotifier.reset=function(){CockpitNotifier.controller=undefined;CockpitNotifier.controllerNullLogged=false;CockpitNotifier.isDryRunMode=false};CockpitNotifier.setDryRunMode=function(logger,proxy){CockpitNotifier.isDryRunMode=true;CockpitNotifier.controller=new dry_run_agent_events_controller_1.DryRunAgentEventsController(logger,proxy)};CockpitNotifier.controllerNullLogged=false;return CockpitNotifier}();exports.CockpitNotifier=CockpitNotifier})},{"./agent-events-controller":290,"./dry-run-agent-events-controller":295}],295:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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-conracts","./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;var agent_events_conracts_1=require("./agent-events-conracts");var agent_events_controller_1=require("./agent-events-controller");var config_1=require("../config-process/config");var agent_instance_data_1=require("../agent-instance-data");var DryRunAgentEventsController=function(_super){__extends(DryRunAgentEventsController,_super);function DryRunAgentEventsController(logger,proxy){return _super.call(this,new config_1.AgentConfig,new agent_instance_data_1.AgentInstanceData(agent_events_conracts_1.AgentType.SLNODEJS,agent_events_conracts_1.Technology.NODEJS),logger,proxy,null)||this}DryRunAgentEventsController.prototype.submitAgentStartedEvent=function(packageJsonFile){return Promise.resolve(undefined)};return DryRunAgentEventsController}(agent_events_controller_1.AgentEventsController);exports.DryRunAgentEventsController=DryRunAgentEventsController})},{"../agent-instance-data":299,"../config-process/config":302,"./agent-events-conracts":289,"./agent-events-controller":290}],296:[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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MachineInfoBuilder=void 0;var os=require("os");var system_date_1=require("../system-date");var MachineInfoBuilder=function(){function MachineInfoBuilder(){this.info={}}MachineInfoBuilder.prototype.fillData=function(){var currentDate=system_date_1.getSystemDate();this.info.machineName=os.hostname();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()};MachineInfoBuilder.prototype.build=function(){this.fillData();return this.info};MachineInfoBuilder.prototype.extractIpAddresses=function(){var ipAddresses=[];var interfaces=os.networkInterfaces();Object.keys(interfaces).forEach(function(key){var addressesArr=interfaces[key];ipAddresses=ipAddresses.concat(addressesArr.map(function(addressObject){return addressObject.address}))});return ipAddresses};return MachineInfoBuilder}();exports.MachineInfoBuilder=MachineInfoBuilder})}).call(this)}).call(this,require("_process"))},{"../system-date":333,_process:179,os:154}],297:[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;var NodejsEnvInfoBuilder=function(){function NodejsEnvInfoBuilder(dependencies){this.info={};this.dependencies=dependencies||{}}NodejsEnvInfoBuilder.prototype.fillData=function(){this.info.indexJsonDeps=this.dependencies;this.info.nodeVersion=process.versions.node};NodejsEnvInfoBuilder.prototype.build=function(){this.fillData();return this.info};return NodejsEnvInfoBuilder}();exports.NodejsEnvInfoBuilder=NodejsEnvInfoBuilder})}).call(this)}).call(this,require("_process"))},{_process:179}],298:[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;var 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(var _i=0,_a=Object.entries(secretKeysRegexes);_i<_a.length;_i++){var _b=_a[_i],key=_b[0],regex=_b[1];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})},{}],299:[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-conracts","./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;var uuid=require("uuid");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var files_utils_1=require("./utils/files-utils");var fs_1=require("fs");var agent_instance_info_builder_1=require("./agent-events/agent-instance-info-builder");var AgentInstanceData=function(){function AgentInstanceData(agentType,technology){this.agentType=agentType;this.technology=technology;this.agentId=uuid();this.agentVersion=this.resolveAgentVersion()}AgentInstanceData.prototype.resolveAgentVersion=function(){if(this.technology===agent_events_conracts_1.Technology.BROWSER){return this.resolveAgentVersionForBrowserAgent()}var packageJsonFilePath=files_utils_1.FilesUtils.findFileUp("package.json",__dirname);if(packageJsonFilePath){try{var packageJson=fs_1.readFileSync(packageJsonFilePath).toString();var parsed=JSON.parse(packageJson);return parsed.version}catch(e){console.warn("Failed to resolve agent version, Error: '"+e);return null}}return null};AgentInstanceData.prototype.resolveAgentVersionForBrowserAgent=function(){var 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};return AgentInstanceData}();exports.AgentInstanceData=AgentInstanceData})}).call(this)}).call(this,"/tsOutputs/common")},{"./agent-events/agent-events-conracts":289,"./agent-events/agent-instance-info-builder":291,"./utils/files-utils":335,fs:69,uuid:507}],300:[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","fs","jwt-decode","./config"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ConfigLoader=void 0;var config_system_1=require("./config-system");var fs=require("fs");var jwtDecode=require("jwt-decode");var config_1=require("./config");var ConfigLoader=function(){function ConfigLoader(logger){this.logger=logger}ConfigLoader.prototype.loadAgentConfiguration=function(initialJsonConfig){var agentCfg=new config_1.AgentConfig;if(process.env.SL_CONFIGURATION){try{var jsonCfg=JSON.parse(process.env.SL_CONFIGURATION);agentCfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(jsonCfg))}catch(e){console.error("Error parsing agent configuration %s",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.printConfiguration(agentCfg);return agentCfg};ConfigLoader.prototype.printConfiguration=function(agentCfg){if(!this.logger)return;this.logger.info("****************************************************");this.logger.info("Current config");this.logger.info("****************************************************");this.logger.info(agentCfg.toJsonObject())};ConfigLoader.prototype.loadConfigFromToken=function(agentCfg,token){if(!token)return null;try{var 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")}var customerId=tokenData["subject"];var 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){}};return ConfigLoader}();exports.ConfigLoader=ConfigLoader})}).call(this)}).call(this,require("_process"))},{"./config":302,"./config-system":301,_process:179,fs:69,"jwt-decode":441}],301:[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;var fs=require("fs");var JsonObjectConfigurationProvider=function(){function JsonObjectConfigurationProvider(configObject){this.configObject=configObject;this.configObject=configObject||{}}JsonObjectConfigurationProvider.prototype.getAllKeyValues=function(callback){return callback(null,this.configObject)};JsonObjectConfigurationProvider.prototype.getName=function(){return"JSON Object"};return JsonObjectConfigurationProvider}();exports.JsonObjectConfigurationProvider=JsonObjectConfigurationProvider;var EnvVariableConfigurationProvider=function(){function EnvVariableConfigurationProvider(prefix){this.prefix=prefix}EnvVariableConfigurationProvider.prototype.getAllKeyValues=function(callback){if(this.prefix){var ret={};for(var key in process.env){if(key.indexOf(this.prefix)==0){ret[key.substr(this.prefix.length)]=process.env[key]}}callback(null,ret)}else{return callback(null,process.env)}};EnvVariableConfigurationProvider.prototype.getName=function(){return"Environment Variables"};return EnvVariableConfigurationProvider}();exports.EnvVariableConfigurationProvider=EnvVariableConfigurationProvider;var ConfigProviderAggregator=function(){function ConfigProviderAggregator(providers){this.providers=providers;if(!providers)throw new Error("no provider was specified")}ConfigProviderAggregator.prototype.getAllKeyValues=function(callback){var flattenedConfiguration={};var remainingProviders=[].concat(this.providers);var attemptNext=function(){if(remainingProviders.length==0){return callback(null,flattenedConfiguration)}var nextProvider=remainingProviders.shift();nextProvider.getAllKeyValues(function(err,keysAndValues){if(err)return attemptNext();Object.keys(keysAndValues).forEach(function(k){if(!flattenedConfiguration.hasOwnProperty(k))flattenedConfiguration[k]=keysAndValues[k]});return attemptNext()})};attemptNext()};ConfigProviderAggregator.prototype.getName=function(){return"Aggregated config from multiple providers: "+this.providers.map(function(t){return t.getName()})};return ConfigProviderAggregator}();exports.ConfigProviderAggregator=ConfigProviderAggregator;var JsonConfigFileConfigurationProvider=function(){function JsonConfigFileConfigurationProvider(filename){this.filename=filename;if(!filename)throw new Error("filename is required")}JsonConfigFileConfigurationProvider.prototype.getAllKeyValues=function(callback){try{var cfg=JSON.parse(fs.readFileSync(this.filename).toString().trim());return callback(null,cfg)}catch(e){return callback(e,null)}};JsonConfigFileConfigurationProvider.prototype.getName=function(){return"Config filename: "+this.filename};return JsonConfigFileConfigurationProvider}();exports.JsonConfigFileConfigurationProvider=JsonConfigFileConfigurationProvider;var AgentConfigKey=function(){function AgentConfigKey(){}return AgentConfigKey}();exports.AgentConfigKey=AgentConfigKey;var StringConfigKey=function(){function StringConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"string"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(StringConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});StringConfigKey.prototype.loadFromRawData=function(s){this.value=s;this.hasValue=true};return StringConfigKey}();exports.StringConfigKey=StringConfigKey;var NumberConfigKey=function(){function NumberConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"number"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(NumberConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});NumberConfigKey.prototype.loadFromRawData=function(s){var parsed=parseInt(s);if(isNaN(parsed))throw new Error(s+" is not a valid number");this.value=parsed;this.hasValue=true};return NumberConfigKey}();exports.NumberConfigKey=NumberConfigKey;var BooleanConfigKey=function(){function BooleanConfigKey(required,defaultValue){this.required=required;this.isConfigKey=true;this.metadata={required:required,type:"boolean"};if(defaultValue!==undefined){this.value=defaultValue}}Object.defineProperty(BooleanConfigKey.prototype,"value",{get:function(){return this._value},set:function(value){this._value=value;this.hasValue=true},enumerable:false,configurable:true});BooleanConfigKey.prototype.loadFromRawData=function(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)}};return BooleanConfigKey}();exports.BooleanConfigKey=BooleanConfigKey;var BaseConfiguration=function(){function BaseConfiguration(){}BaseConfiguration.prototype.loadConfigurationFromMultipleProviders=function(configProviders,callback){var provider=new ConfigProviderAggregator(configProviders);this.loadConfiguration(provider,callback)};BaseConfiguration.prototype.loadConfiguration=function(configProvider,callback,dbg){var _this=this;try{configProvider.getAllKeyValues(function(err,keysAndValues){if(err){if(callback){callback(err)}return}keysAndValues=keysAndValues||{};var knownKeys=Object.keys(_this);var hadError=false;var keyWithError="";knownKeys.forEach(function(keyName){if(hadError){console.log("[Sealights Test Listener] - Failed to load configuration due to invalid value in '"+keyWithError+"' field'.");return}var cfgKey=_this[keyName];if(!cfgKey.isConfigKey)return;var rawValue=keysAndValues[keyName];if(cfgKey.metadata.required&&rawValue==undefined){var 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){var 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}};BaseConfiguration.prototype.toJsonObject=function(){var _this=this;var ret={};var knownKeys=Object.keys(this);knownKeys.forEach(function(keyName){var cfgKey=_this[keyName];if(cfgKey.isConfigKey&&cfgKey.hasValue){ret[keyName]=cfgKey.value}});return ret};BaseConfiguration.prototype.getLowerCaseToKeyMap=function(){var lowerCaseMap={}
|
|
29
|
+
;Object.keys(this).forEach(function(key){lowerCaseMap[key.toLowerCase()]=key});return lowerCaseMap};return BaseConfiguration}();exports.BaseConfiguration=BaseConfiguration})}).call(this)}).call(this,require("_process"))},{_process:179,fs:69}],302:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var config_system_1=require("./config-system");var AgentConfig=function(_super){__extends(AgentConfig,_super);function AgentConfig(){var _this=_super!==null&&_super.apply(this,arguments)||this;_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.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.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);return _this}return AgentConfig}(config_system_1.BaseConfiguration);exports.AgentConfig=AgentConfig;var AgentConfigWithRuntimeArgs=function(_super){__extends(AgentConfigWithRuntimeArgs,_super);function AgentConfigWithRuntimeArgs(){var _this=_super!==null&&_super.apply(this,arguments)||this;_this.cfg=new config_system_1.StringConfigKey(false);return _this}return AgentConfigWithRuntimeArgs}(AgentConfig);exports.AgentConfigWithRuntimeArgs=AgentConfigWithRuntimeArgs})},{"./config-system":301}],303:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var events=require("events");var config_system_1=require("./config-system");var assign=require("object-assign");var jwtDecode=require("jwt-decode");var ConfigProcess=function(_super){__extends(ConfigProcess,_super);function ConfigProcess(cfg,watchdog,backendProxy,logger){var _this=_super.call(this)||this;_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",function(){watchdog.stop();_this.reloadConfigFromServer()});_this.initCfg();return _this}ConfigProcess.prototype.reloadConfigFromServer=function(callback){var _this=this;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},function(err,updatedCfg){if(!err&&updatedCfg){_this.mergeConfigFromServerAndFireEvent(updatedCfg)}_this.watchdog.start();if(callback){callback(err)}})};ConfigProcess.prototype.mergeConfigFromServerAndFireEvent=function(updatedCfgObject){var configChanged=false;this.cfg.loadConfiguration(new config_system_1.JsonObjectConfigurationProvider(this.initialCfg));for(var 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)}};ConfigProcess.prototype.getConfiguration=function(){return this.cfg};ConfigProcess.prototype.initCfg=function(){if(this.cfg.token.hasValue){try{var 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")}var customerId=tokenData["subject"];var 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. %s",err)}}};ConfigProcess.prototype.start=function(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};ConfigProcess.prototype.stop=function(callback){this.watchdog.stop();this.isRunning=false;return callback()};return ConfigProcess}(events.EventEmitter);exports.ConfigProcess=ConfigProcess})},{"./config-system":301,events:110,"jwt-decode":441,"object-assign":153}],304:[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.Constants=void 0;var Constants=function(){function Constants(){}var _a;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=function(){function class_1(){}return class_1}(),_a.CANNOT_BE_NULL_OR_UNDEFINED="cannot be null or undefined.",_a.CANNOT_BE_EMPTY_STRING="cannot be empty string",_a);return Constants}();exports.Constants=Constants})},{}],305:[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","../utils/env-var-parsing"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SlEnvVars=void 0;var env_var_parsing_1=require("../utils/env-var-parsing");var SlEnvVars=function(){function SlEnvVars(){}SlEnvVars.getHttpTimeout=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.HTTP_TIMEOUT)};SlEnvVars.getHttpMaxAttempts=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.HTTP_MAX_ATTEMPTS)};SlEnvVars.getHttpAttemptInterval=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.HTTP_ATTEMPT_INTERVAL)};SlEnvVars.inProductionListenerMode=function(){return!!process.env[SlEnvVars.PRODUCTION_LISTENER]};SlEnvVars.getProductionListenerModes=function(){return(process.env[SlEnvVars.PRODUCTION_LISTENER]||"").split(",")};SlEnvVars.getFileStorage=function(){return process.env[SlEnvVars.FILE_STORAGE]};SlEnvVars.getBasePath=function(){return process.env[SlEnvVars.BASE_PATH]};SlEnvVars.isUseNewUniqueId=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.NEW_UNIQUE_ID)};SlEnvVars.isUseIstanbul=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_ISTANBUL)};SlEnvVars.enableFootprintsV6=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.ENABLE_FOOTPRINTS_V6)};SlEnvVars.getFootprintsCollectIntervalSecs=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_COLLECTION_INTERVAL_SECS)};SlEnvVars.getFootprintsSendMaxIntervalSecs=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_SEND_MAX_INTERVAL_SECS)};SlEnvVars.getFootprintsQueueSize=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_QUEUE_SIZE)};SlEnvVars.getExecutionQueryIntervalSecs=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.EXECUTION_QUERY_INTERVAL_SEC)};SlEnvVars.getFootprintsBufferThresholdMb=function(){return env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.FOOTPRINTS_BUFFER_THRESHOLD_MB)};SlEnvVars.blockBrowserHttpTraffic=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.BLOCK_BROWSER_HTTP_TRAFFIC)};SlEnvVars.getDisableHookDependencyGuard=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.DISABLE_HOOK_DEPENDENCY_GUARD)};SlEnvVars.useSlMapping=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.USE_SL_MAPPING)};var _a;SlEnvVars.HTTP_TIMEOUT="SL_httpTimeout";SlEnvVars.HTTP_MAX_ATTEMPTS="SL_HttpMaxAttempts";SlEnvVars.HTTP_ATTEMPT_INTERVAL="SL_HttpAttemptInterval";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_SL_MAPPING="SL_useSlMapping";SlEnvVars.CIA=(_a=function(){function class_1(){}class_1.getFileExtensions=function(){return process.env[SlEnvVars.CIA.FILE_EXTENSIONS]};class_1.getScmPrefix=function(){return process.env[SlEnvVars.CIA.SCM_PREFIX]};class_1.getSourceRoot=function(){return process.env[SlEnvVars.CIA.SL_SOURCE_ROOT]};class_1.getSlMappingPath=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_PATH]};class_1.getSlMappingUrl=function(){return process.env[SlEnvVars.CIA.SL_MAPPING_URL]};class_1.reduceInstrumentedFileSize=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.REDUCE_INSTRUMENTED_FILE_SIZE)};class_1.minifyInstrumentedOutput=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.MINIFY_INSTRUMENTED_OUTPUT)};class_1.inProcessInstrumentation=function(){return env_var_parsing_1.EnvVarParsing.parseBoolean(SlEnvVars.CIA.IN_PROCESS_INSTRUMENTATION)};class_1.getMaxBuffer=function(){var oneMB=1024*1024;var bufferInBytes=env_var_parsing_1.EnvVarParsing.parseNumber(SlEnvVars.CIA.MAX_BUFFER);if(bufferInBytes!==null){return bufferInBytes*oneMB}return bufferInBytes};return class_1}(),_a.FILE_EXTENSIONS="SL_fileExtensions",_a.SCM_PREFIX="SL_scmPrefix",_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.MINIFY_INSTRUMENTED_OUTPUT="SL_minifyInstrumentedOutput",_a.IN_PROCESS_INSTRUMENTATION="SL_inProcessInstrumentation",_a.MAX_BUFFER="SL_maxBuffer",_a);return SlEnvVars}();exports.SlEnvVars=SlEnvVars})}).call(this)}).call(this,require("_process"))},{"../utils/env-var-parsing":334,_process:179}],306:[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={}))})},{}],307:[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;var validation_utils_1=require("../utils/validation-utils");var FileElement=function(){function FileElement(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}Object.defineProperty(FileElement.prototype,"type",{get:function(){return this._type},set:function(value){this._type=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"startPosition",{get:function(){return this._startPosition},set:function(value){this._startPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"endPosition",{get:function(){return this._endPosition},set:function(value){this._endPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey",{get:function(){return this._uniqueIdKey},set:function(value){this._uniqueIdKey=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueIdKey_decl",{get:function(){return this._uniqueIdKey_decl},set:function(value){this._uniqueIdKey_decl=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"filename",{get:function(){return this._filename},set:function(value){this._filename=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"uniqueId",{get:function(){return this._uniqueId},set:function(value){this._uniqueId=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"parentPosition",{get:function(){return this._parentPosition},set:function(value){this._parentPosition=value},enumerable:false,configurable:true});Object.defineProperty(FileElement.prototype,"index",{get:function(){return this._index},set:function(value){this._index=value},enumerable:false,configurable:true});FileElement.prototype.isStartsAfter=function(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};FileElement.prototype.isStartsBefore=function(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};FileElement.prototype.isEndsAfter=function(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};FileElement.prototype.isEndsBefore=function(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};return FileElement}();exports.FileElement=FileElement})},{"../utils/validation-utils":337}],308:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var contracts_1=require("./contracts");var unique_id_converter_1=require("./unique-id-converter");var IstanbulUniqueIdConverter=function(_super){__extends(IstanbulUniqueIdConverter,_super);function IstanbulUniqueIdConverter(filename,logger){return _super.call(this,filename,logger)||this}IstanbulUniqueIdConverter.prototype.createElementsArray=function(file){var _this=this;file.fnMap=file.fnMap||{};file.branchMap=file.branchMap||{};var methodsArr=Object.keys(file.fnMap).map(function(key){return _this.formatMethod(file.fnMap[key])});var branchesArr=this.createBranchElements(file.branchMap);this.fillFileElementsArray(methodsArr,this.methodsArray,contracts_1.ElementType.METHOD);this.fillFileElementsArray(branchesArr,this.branchesArray,contracts_1.ElementType.BRANCH)};IstanbulUniqueIdConverter.prototype.createElementPosition=function(position){return position};IstanbulUniqueIdConverter.prototype.createBranchElements=function(branchesMap){var branchesMapArr=Object.keys(branchesMap).map(function(key){return branchesMap[key]});var branchesArr=[];for(var _i=0,branchesMapArr_1=branchesMapArr;_i<branchesMapArr_1.length;_i++){var branch=branchesMapArr_1[_i];branchesArr=branchesArr.concat(this.extractBranchParts(branch))}return branchesArr};IstanbulUniqueIdConverter.prototype.extractBranchParts=function(branch){var formattedBranches=[];var locations=branch.locations;for(var i=0;i<locations.length;i++){var 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};IstanbulUniqueIdConverter.prototype.formatMethod=function(method){var 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};IstanbulUniqueIdConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};return IstanbulUniqueIdConverter}(unique_id_converter_1.UniqueIdConverter);exports.IstanbulUniqueIdConverter=IstanbulUniqueIdConverter})},{"./contracts":306,"./unique-id-converter":311}],309:[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;var path_1=require("path");var system_date_1=require("../system-date");var files_utils_1=require("../utils/files-utils");var istanbul_unique_id_converter_1=require("./istanbul-unique-id-converter");function resolveNewId(uniqueIdKey,moduleName,relativePath,coverageObject,logger){moduleName=path_1.normalize(moduleName);var moduleData=resolveModule(coverageObject,moduleName,logger);if(!moduleData){return}if(!moduleData.uniqueIdsMap){logger.debug("building uniqueids map for "+moduleData.path);var before_1=system_date_1.getSystemDateValueOf();logger.debug("file "+moduleData.path+" not contains uniqueIdMaps, trying to reload");createSLMapping(moduleData.path,relativePath,coverageObject,logger);var after_1=system_date_1.getSystemDateValueOf();logger.debug("*******************************create unique id map ******************************************");logger.debug(after_1-before_1);logger.debug("*******************************create unique id map ******************************************")}var 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){var withLeftSlashes=files_utils_1.FilesUtils.adjustPathSlashes(moduleName);var 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){var module=coverageObject[fullPath];var converter=new istanbul_unique_id_converter_1.IstanbulUniqueIdConverter(relativePath,logger);converter.createElementsArray(module);converter.process();coverageObject[fullPath].uniqueIdsMap=converter.uniqueIdsMap}})},{"../system-date":333,"../utils/files-utils":335,"./istanbul-unique-id-converter":308,path:171}],310:[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;var validation_utils_1=require("../utils/validation-utils");var files_utils_1=require("../utils/files-utils");var source_maps_utils_1=require("../source-maps-utils");var BRANCHES_MAP_KEY="branchMap";var METHODS_MAP_KEY="fnMap";var OriginalModuleLoader=function(){function OriginalModuleLoader(coverageObject,logger){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(coverageObject,"coverageObject");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.coverageObject=coverageObject;this.logger=logger;this._fileToSourceMapConsumer={}}OriginalModuleLoader.prototype.load=function(){var _this=this;var modules=Object.keys(this.coverageObject);modules.map(function(moduleName){return _this.tryLoadOriginalModule(moduleName)})};OriginalModuleLoader.prototype.tryLoadOriginalModule=function(istanbulModule){if(!this.getSourceMapForFile(istanbulModule)){return}this.readOriginalModule(istanbulModule)};OriginalModuleLoader.prototype.readOriginalModule=function(moduleName){var _this=this;var sourceMapsReader=this.getSourceMapForFile(moduleName);var module=this.coverageObject[moduleName];Object.keys(module.branchMap).forEach(function(key){return _this.resolveAndAddBranch(module.branchMap[key],sourceMapsReader,moduleName)});Object.keys(module.fnMap).map(function(key){return _this.resolveAndAddMethod(module.fnMap[key],sourceMapsReader,moduleName)})};OriginalModuleLoader.prototype.resolveAndAddMethod=function(method,sourceMapsReader,moduleName){var originalMethod=this.createEmptyMethodObject();originalMethod.name=method.name;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,method,moduleName,originalMethod);if(originalModuleName){this.addElementToModule(originalModuleName,originalMethod,METHODS_MAP_KEY)}};OriginalModuleLoader.prototype.resolveAndAddBranch=function(branch,sourceMapsReader,moduleName){var _this=this;var originalBranch=this.createEmptyBranchObject();originalBranch.type=branch.type;var originalModuleName=this.loadOriginalDataForElement(sourceMapsReader,branch,moduleName,originalBranch);if(originalModuleName){var originalLocations=branch.locations.map(function(locationElement){return _this.createElementSourceData(locationElement,sourceMapsReader,moduleName)});originalBranch.locations=originalLocations;this.addElementToModule(originalModuleName,originalBranch,BRANCHES_MAP_KEY)}};OriginalModuleLoader.prototype.loadOriginalDataForElement=function(sourceMapsReader,element,moduleName,originalElement){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,element.loc.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,element.loc.end,moduleName);if(!sourceMapDataForStart){return}originalElement.loc.start=sourceMapDataForStart.originalPosition;originalElement.line=sourceMapDataForStart.originalPosition.line;var originalModuleName=sourceMapDataForStart.originalFilename;if(sourceMapDataForEnd){originalElement.loc.end=sourceMapDataForEnd.originalPosition}if(element.decl){originalElement.decl={};var sourceMapDataForDeclStart=this.readSourceMapData(sourceMapsReader,element.decl.start,moduleName);var sourceMapDataForDeclEnd=this.readSourceMapData(sourceMapsReader,element.decl.end,moduleName);if(sourceMapDataForDeclStart){originalElement.decl.start=sourceMapDataForDeclStart.originalPosition}if(sourceMapDataForDeclEnd){originalElement.decl.end=sourceMapDataForDeclEnd.originalPosition}}return originalModuleName};OriginalModuleLoader.prototype.addElementToModule=function(moduleName,element,mapObjectKey){var module=this.getOrCreateIstanbulModule(moduleName);var key=this.createElementKey(element);if(!module[mapObjectKey][key]){module[mapObjectKey][key]=element}};OriginalModuleLoader.prototype.createElementSourceData=function(locationElement,sourceMapsReader,moduleName){var sourceMapDataForStart=this.readSourceMapData(sourceMapsReader,locationElement.start,moduleName);var sourceMapDataForEnd=this.readSourceMapData(sourceMapsReader,locationElement.end,moduleName);if(!sourceMapDataForStart&&!sourceMapDataForEnd){return{}}var sourceLocationElement={start:sourceMapDataForStart.originalPosition,end:sourceMapDataForEnd.originalPosition};return sourceLocationElement};OriginalModuleLoader.prototype.getOrCreateIstanbulModule=function(moduleName){var module=this.coverageObject[moduleName];if(!module){module=this.createIstanbulModule(moduleName);this.coverageObject[moduleName]=module}return module};OriginalModuleLoader.prototype.getSourceMapForFile=function(fullPath){if(!this._fileToSourceMapConsumer[fullPath]){this._fileToSourceMapConsumer[fullPath]=source_maps_utils_1.SourceMapsUtils.readSourceMaps(fullPath);this.logger.debug("Read source maps for file':"+fullPath+"'")}var sourceMap=this._fileToSourceMapConsumer[fullPath];return sourceMap};OriginalModuleLoader.prototype.readSourceMapData=function(sourceMaps,start,fullPath){if(!sourceMaps)return null;try{var originalPosition=sourceMaps.originalPositionFor(start);if(originalPosition&&originalPosition.source&&originalPosition.line!==null&&originalPosition.column!==null){var 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);var originalPositionObj={line:originalPosition.line,column:originalPosition.column};var result={originalFilename:originalFilename,originalPosition:originalPositionObj};return result}}}catch(e){console.log(e)}return null};OriginalModuleLoader.prototype.createElementKey=function(element){return element.loc.start.line+":"+element.loc.start.column};OriginalModuleLoader.prototype.createEmptyBranchObject=function(){return{loc:{},locations:[],type:"",line:null}};OriginalModuleLoader.prototype.createEmptyMethodObject=function(){return{loc:{},name:"",line:null}};OriginalModuleLoader.prototype.createIstanbulModule=function(path){return{s:{},f:{},b:{},fnMap:{},statementMap:{},branchMap:{},path:path,
|
|
30
|
+
uniqueIdsMap:null}};Object.defineProperty(OriginalModuleLoader.prototype,"fileToSourceMapConsumer",{get:function(){return this._fileToSourceMapConsumer},set:function(value){this._fileToSourceMapConsumer=value},enumerable:false,configurable:true});return OriginalModuleLoader}();exports.OriginalModuleLoader=OriginalModuleLoader})},{"../source-maps-utils":330,"../utils/files-utils":335,"../utils/validation-utils":337}],311:[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;var contracts_1=require("./contracts");var file_element_1=require("./file-element");var METHOD_DELIMITER="@";var BRANCH_DELIMITER="|";var NULL_PARAM_MESSAGE="cannot be null or undefined";var UniqueIdConverter=function(){function UniqueIdConverter(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=[]}UniqueIdConverter.prototype.sortElements=function(){this._methodsArray=this._methodsArray.sort(this.comparePosition);this._branchesArray=this._branchesArray.sort(this.comparePosition)};UniqueIdConverter.prototype.createElementsArray=function(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)};UniqueIdConverter.prototype.createFileElement=function(element,filename,type){var startPosition=this.createElementPosition(element.position);var endPosition=this.createElementPosition(element.endPosition);var 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){var index=element.index||0;fileElement.startPosition=this.createElementPosition(element.parentPosition);fileElement.index=index}return fileElement};UniqueIdConverter.prototype.process=function(){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()};UniqueIdConverter.prototype.setAndInitFile=function(file){this.createElementsArray(file)};UniqueIdConverter.prototype.createElementPosition=function(position){var line;var 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}};UniqueIdConverter.prototype.fillFileElementsArray=function(elements,array,type){for(var _i=0,elements_1=elements;_i<elements_1.length;_i++){var element=elements_1[_i];array.push(this.createFileElement(element,this._filename,type))}};UniqueIdConverter.prototype.fillUniqueIdsMap=function(){this.createNewUniqueIds(this._methodsArray,METHOD_DELIMITER);this.createNewUniqueIds(this._branchesArray,BRANCH_DELIMITER)};UniqueIdConverter.prototype.createNewUniqueIds=function(array,delimiter){var aggregatedByLine=this.aggregateElementsByLine(array);var lines=Object.keys(aggregatedByLine);for(var _i=0,lines_1=lines;_i<lines_1.length;_i++){var line=lines_1[_i];var indexesArray=aggregatedByLine[line];for(var i=0;i<indexesArray.length;i++){var currentIndex=indexesArray[i];var currentElement=array[currentIndex];currentElement.uniqueId=currentElement.filename+delimiter+line+","+i;this.logger.debug("[UniqueIdConverter] uniqueId "+currentElement.uniqueIdKey+" converted to \n "+currentElement.uniqueId);this._uniqueIdsMap[currentElement.uniqueIdKey]=currentElement.uniqueId;if(currentElement.uniqueIdKey_decl){this._uniqueIdsMap[currentElement.uniqueIdKey_decl]=currentElement.uniqueId}}}};UniqueIdConverter.prototype.comparePosition=function(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};Object.defineProperty(UniqueIdConverter.prototype,"uniqueIdsMap",{get:function(){return this._uniqueIdsMap},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"methodsArray",{get:function(){return this._methodsArray},set:function(value){this._methodsArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"branchesArray",{get:function(){return this._branchesArray},set:function(value){this._branchesArray=value},enumerable:false,configurable:true});Object.defineProperty(UniqueIdConverter.prototype,"filename",{get:function(){return this._filename},enumerable:false,configurable:true});UniqueIdConverter.prototype.removeDuplicateElements=function(elementsArray){var _this=this;var existedKeys={};elementsArray=elementsArray.filter(function(element){return _this.filterDuplicates(element,existedKeys)})};UniqueIdConverter.prototype.filterDuplicates=function(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};UniqueIdConverter.prototype.removeBranchesOutOfMethods=function(){var validBranches=[];var methodsIndex=0;for(var _i=0,_a=this._branchesArray;_i<_a.length;_i++){var branch=_a[_i];for(var i=methodsIndex;i<this._methodsArray.length;i++){var currentMethod=this._methodsArray[i];var branchPosition=this.checkBranchPosition(branch,currentMethod);if(branchPosition===0){validBranches.push(branch);break}if(branchPosition===1){methodsIndex++}}}this._branchesArray=validBranches.sort(this.comparePosition)};UniqueIdConverter.prototype.checkBranchPosition=function(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};UniqueIdConverter.prototype.aggregateElementsByLine=function(elements){var aggregated={};for(var i=0;i<elements.length;i++){var element=elements[i];var lineNumber=element.startPosition.line;if(!aggregated[lineNumber]){aggregated[lineNumber]=[]}aggregated[lineNumber].push(i)}return aggregated};return UniqueIdConverter}();exports.UniqueIdConverter=UniqueIdConverter})},{"./contracts":306,"./file-element":307}],312:[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.TestSelectionStatus=exports.EventTypes=void 0;var EventTypes;(function(EventTypes){EventTypes["AgentStarted"]="agentStarted";EventTypes["ExecutionIdStarted"]="executionIdStarted";EventTypes["ExecutionIdEnded"]="executionIdEnded";EventTypes["TestStart"]="testStart";EventTypes["TestEnd"]="testEnd"})(EventTypes=exports.EventTypes||(exports.EventTypes={}));var TestSelectionStatus;(function(TestSelectionStatus){TestSelectionStatus["RECOMMENDED_TESTS"]="recommendedTests";TestSelectionStatus["DISABLED"]="disabled";TestSelectionStatus["DISABLED_BY_CONFIGURATION"]="disabledByConfiguration";TestSelectionStatus["RECOMMENDATIONS_TIMEOUT"]="recommendationsTimeout";TestSelectionStatus["ERROR"]="error"})(TestSelectionStatus=exports.TestSelectionStatus||(exports.TestSelectionStatus={}))})},{}],313:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};(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-contracts","../system-date"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.EventsCreator=void 0;var events_contracts_1=require("./events-contracts");var system_date_1=require("../system-date");var EventsCreator=function(){function EventsCreator(){}EventsCreator.createTestStartedEvent=function(executionId,framework,testName,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestStart,executionId,framework);var startTimeStamp=system_date_1.getSystemDateValueOf()-duration;eventBase.localTime=startTimeStamp;return __assign(__assign({},eventBase),{testName:testName})};EventsCreator.createTestEndEvent=function(executionId,framework,testName,result,duration){var eventBase=this.createEvent(events_contracts_1.EventTypes.TestEnd,executionId,framework);return __assign(__assign({},eventBase),{result:result,duration:duration,testName:testName})};EventsCreator.createEvent=function(type,executionId,framework){return{type:type,executionId:executionId,framework:framework,localTime:system_date_1.getSystemDateValueOf()}};return EventsCreator}();exports.EventsCreator=EventsCreator})},{"../system-date":333,"./events-contracts":312}],314:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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;var validation_utils_1=require("../utils/validation-utils");var system_date_1=require("../system-date");var EventsProcess=function(){function EventsProcess(configuration,agentInstanceData,sendToServerWatchdog,keepAliveWatchdog,environmentDataService,backendProxy,eventsQueue,logger){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()}EventsProcess.prototype.enqueueEvent=function(evt){evt.localTime=evt.localTime||system_date_1.getSystemDateValueOf();this._eventsQueue.enqueue(evt);if(this.isRunning&&this.configuration.sendEvents.value&&this.configuration.enabled.value){this.ensureKeepaliveThreadRunning()}};EventsProcess.prototype.start=function(){if(this._isRunning||!this._configuration.enabled.value){return}this._sendToServerWatchdog.start();if(this._eventsQueue.getQueueSize()>0){this.ensureKeepaliveThreadRunning()}this._isRunning=true};EventsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:this._sendToServerWatchdog.stop();this.keepAliveWatchdog.stop();if(this._configuration.enabled.value===false||this._configuration.sendEvents.value===false){return[2]}_a.label=1;case 1:_a.trys.push([1,4,,5]);return[4,Promise.all(this._onGoingRequests)];case 2:_a.sent();return[4,this.submitEventsSync()];case 3:_a.sent();return[3,5];case 4:e_1=_a.sent();this._logger.warn("Error while stopping EventsProcess: ",e_1);return[3,5];case 5:this._isRunning=false;return[2]}})})};EventsProcess.prototype.getQueueSize=function(){return this._eventsQueue.getQueueSize()};EventsProcess.prototype.submitEvents=function(){var _this=this;if(!this._isRunning||!this._configuration.sendEvents.value||!this._configuration.enabled.value||this._eventsQueue.getQueueSize()==0){return}var items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);var packet=this.createEventsPacket(items);var promise=this._backendProxy.submitEventsPromise(packet);this._onGoingRequests.push(promise);promise.then(function(){if(_this._eventsQueue.getQueueSize()>0){_this.submitEvents()}_this.removeRequest(promise)}).catch(function(err){_this._logger.warn("Error while submitting events, "+err);_this._eventsQueue.requeue(items);_this.removeRequest(promise)})};EventsProcess.prototype.submitEventsSync=function(){return __awaiter(this,void 0,void 0,function(){var items,packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,4,,5]);_a.label=1;case 1:if(!(this._eventsQueue.getQueueSize()>0))return[3,3];items=this._eventsQueue.dequeue(EventsProcess.ITEMS_TO_DEQUE);packet=this.createEventsPacket(items);return[4,this._backendProxy.submitEventsPromise(packet)];case 2:_a.sent();return[3,1];case 3:return[3,5];case 4:e_2=_a.sent();this._logger.warn("Error while sending events synchronously. "+e_2);return[3,5];case 5:return[2]}})})};EventsProcess.prototype.createEventsPacket=function(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:system_date_1.getSystemDateValueOf(),agentId:this._agentInstanceData.agentId}}};EventsProcess.prototype.init=function(){var _this=this;this._sendToServerWatchdog.on("alarm",function(){return _this.submitEvents()});this._eventsQueue.on("full",function(){return _this.submitEvents()});this.keepAliveWatchdog.on("alarm",function(){if(_this.eventsQueue.getQueueSize()==0){_this.keepAliveWatchdog.stop()}})};EventsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepAliveWatchdog.start()};EventsProcess.prototype.removeRequest=function(request){var index=this._onGoingRequests.indexOf(request);this._onGoingRequests.splice(index,1)};Object.defineProperty(EventsProcess.prototype,"onGoingRequests",{get:function(){return this._onGoingRequests},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"configuration",{get:function(){return this._configuration},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"logger",{get:function(){return this._logger},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"isRunning",{get:function(){return this._isRunning},set:function(value){this._isRunning=value},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"sendToServerWatchdog",{get:function(){return this._sendToServerWatchdog},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"backendProxy",{get:function(){return this._backendProxy},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"eventsQueue",{get:function(){return this._eventsQueue},enumerable:false,configurable:true});Object.defineProperty(EventsProcess.prototype,"testSelectionStatus",{get:function(){return this._testSelectionStatus},set:function(testSelectionStatus){this._testSelectionStatus=testSelectionStatus},enumerable:false,configurable:true});EventsProcess.ITEMS_TO_DEQUE=1e3;return EventsProcess}();exports.EventsProcess=EventsProcess})},{"../system-date":333,"../utils/validation-utils":337}],315:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var location_formatter_1=require("./location-formatter");var hits_converter_1=require("../../common/footprints-process-v6/hits-converter");var files_utils_1=require("../utils/files-utils");var BaseBrowserHitsConverter=function(_super){__extends(BaseBrowserHitsConverter,_super);function BaseBrowserHitsConverter(relativePathResolver,buildSessionId,logger){var _this=_super.call(this,relativePathResolver,{},{},logger)||this;_this.buildSessionId=buildSessionId;return _this}BaseBrowserHitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var uniqueId=absolutePath+hits_converter_1.HitsConverter.METHOD_ID_DEL+this.formatLoc(startLoc);return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId=absolutePath+hits_converter_1.HitsConverter.BRANCH_ID_DEL+this.formatLoc(startLoc)+hits_converter_1.HitsConverter.BRANCH_ID_DEL+leaveIndex;return this.tryGetUniqueIdFromSlMapping(uniqueId)};BaseBrowserHitsConverter.prototype.getDeclStart=function(hit){var decl=this.getDecl(hit);return decl.start||decl.st};BaseBrowserHitsConverter.prototype.getDecl=function(hit){return hit.decl||hit.d};BaseBrowserHitsConverter.prototype.getStartLoc=function(hit){var loc=hit.loc||hit.lc;return loc.start||loc.st};BaseBrowserHitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx){var locations=hit.branchData.locations||hit.branchData.lcs;return locations[leaveIdx].start||locations[leaveIdx].st};BaseBrowserHitsConverter.prototype.formatLoc=function(loc){return location_formatter_1.formatLocation(loc,this.logger)};BaseBrowserHitsConverter.prototype.tryGetUniqueIdFromSlMapping=function(rawUniqueId){rawUniqueId=files_utils_1.FilesUtils.adjustPathSlashes(rawUniqueId);var mapping=this.getSlMapping()||{};return mapping[rawUniqueId]||rawUniqueId};return BaseBrowserHitsConverter}(hits_converter_1.HitsConverter);exports.BaseBrowserHitsConverter=BaseBrowserHitsConverter})},{"../../common/footprints-process-v6/hits-converter":319,"../utils/files-utils":335,"./location-formatter":321}],316:[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;var BufferSizeHelper=function(){function BufferSizeHelper(){this.uniqueIdsLengthSum=0;this.testNamesCount=0;this.testNamesLengthSum=0;this.hitCount=0;this.indicesCount=0;this.uniqueIdsCount=0}BufferSizeHelper.prototype.calculateBufferSize=function(){var 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.MB};BufferSizeHelper.prototype.incrementSizeCounters=function(testName,methodIndicesSize,branchIndicesSize){this.hitCount++;this.indicesCount+=methodIndicesSize+branchIndicesSize;if(testName){this.testNamesCount++;this.testNamesLengthSum+=testName.length}};BufferSizeHelper.FOUR_BYTES=4;BufferSizeHelper.EIGHT_BYTES=8;BufferSizeHelper.APPROX_HIT_SIZE=128;BufferSizeHelper.MB=1024*1024;return BufferSizeHelper}();exports.BufferSizeHelper=BufferSizeHelper})},{}],317:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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-conracts","events","./buffer-size-helper"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsBuffer=void 0;var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var events=require("events");var buffer_size_helper_1=require("./buffer-size-helper");var FootprintsBuffer=function(_super){__extends(FootprintsBuffer,_super);function FootprintsBuffer(agentInstanceData,agentConfig){var _this=_super.call(this)||this;_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};return _this}FootprintsBuffer.prototype.addHit=function(footprints,collectionInterval,executionId,testName,isInitFootprints,isFinalFootprints){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_COLLECTED_FP);var methodIndices=this.addOrGetIndices(footprints.methods,true);var branchIndices=this.addOrGetIndices(footprints.branches,false);var 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()};FootprintsBuffer.prototype.createPacket=function(){var packet=this.toJson();this.resetState();return packet};FootprintsBuffer.prototype.resetState=function(){this.branches=[];this.methods=[];this.executions=[];this.methodIdToIndex=new Map;this.branchIdToIndex=new Map;this.bufferSizeHelper=new buffer_size_helper_1.BufferSizeHelper};FootprintsBuffer.prototype.hasHitsInBuffer=function(){return this.executions.length>0};Object.defineProperty(FootprintsBuffer.prototype,"agentConfig",{get:function(){return this._agentConfig},set:function(value){this._agentConfig=value},enumerable:false,configurable:true});FootprintsBuffer.prototype.toJson=function(){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}};FootprintsBuffer.prototype.addOrGetIndices=function(elementIds,isMethods){var _this=this;var map=isMethods?this.methodIdToIndex:this.branchIdToIndex;var arr=isMethods?this.methods:this.branches;var indices=[];elementIds.forEach(function(id){if(!map.get(id)){_this.bufferSizeHelper.uniqueIdsLengthSum+=id.length;_this.bufferSizeHelper.uniqueIdsCount++;var position=arr.push(id);map.set(id,position-1)}indices.push(map.get(id))});return indices};FootprintsBuffer.prototype.addOrGetExecutionIndex=function(executionId){var index=-1;this.executions.every(function(execution,idx){if(executionId==execution.executionId){index=idx;return false}return true});return index!=-1?index:this.executions.push({executionId:executionId,hits:[]})-1};FootprintsBuffer.prototype.verifyBufferSize=function(){if(this.bufferSizeHelper.calculateBufferSize()>=this._agentConfig.footprintsBufferThresholdMb.value){this.emit(FootprintsBuffer.BUFFER_FULL)}};FootprintsBuffer.BUFFER_FULL="bufferFull";return FootprintsBuffer}(events.EventEmitter);exports.FootprintsBuffer=FootprintsBuffer})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"./buffer-size-helper":316,events:110}],318:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HitsCollector=void 0;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var GLOBAL_ISTANBUL_CONTAINER_NAMES=["__coverage__"];var HitsCollector=function(){function HitsCollector(logger,globalCoverageObject){this.logger=logger;this._globalCoverageObject=globalCoverageObject;this.latestCoverageSnapshot={}}HitsCollector.prototype.getHitElements=function(){return __awaiter(this,void 0,void 0,function(){var hitFilesData,globalCoverage,filename,_a,fileCoverageSnapshot,currentFileCoverage,shouldResolveRelativePath,hitMethods,hitBranches;return __generator(this,function(_b){hitFilesData=[];globalCoverage=this.getGlobalCoverageObject();if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(globalCoverage,this.logger).load()}for(filename in globalCoverage){_a=this.getFileCoverageObjects(filename),fileCoverageSnapshot=_a.fileCoverageSnapshot,currentFileCoverage=_a.currentFileCoverage,shouldResolveRelativePath=_a.shouldResolveRelativePath;hitMethods=this.getHitMethods(currentFileCoverage,fileCoverageSnapshot);hitBranches=this.getHitBranches(currentFileCoverage,fileCoverageSnapshot);if(hitMethods.length||hitBranches.length){hitFilesData.push({filename:filename,hitMethods:hitMethods,hitBranches:hitBranches,shouldResolveRelativePath:shouldResolveRelativePath})}}this.updateCoverageSnapshot(globalCoverage);return[2,hitFilesData]})})};Object.defineProperty(HitsCollector.prototype,"latestCoverageSnapshot",{get:function(){return this._latestCoverageSnapshot},set:function(value){this._latestCoverageSnapshot=value},enumerable:false,configurable:true});Object.defineProperty(HitsCollector.prototype,"globalCoverageObject",{get:function(){return this._globalCoverageObject},set:function(value){this._globalCoverageObject=value},enumerable:false,configurable:true});HitsCollector.prototype.getHitMethods=function(currentHits,snapshotHits){
|
|
31
|
+
var hitMethodsIndices=Object.keys(currentHits.f).filter(function(id){snapshotHits.f[id]=snapshotHits.f[id]||0;return currentHits.f[id]>snapshotHits.f[id]});return hitMethodsIndices.map(function(id){return currentHits.fnMap[id]})};HitsCollector.prototype.dropHits=function(){this.updateCoverageSnapshot(this.getGlobalCoverageObject())};HitsCollector.prototype.getHitLeaves=function(currentLeaveHits,snapshotLeaveHits){var hitLeavesIndices=[];snapshotLeaveHits=snapshotLeaveHits||Array(currentLeaveHits.length).fill(0);currentLeaveHits.forEach(function(leaveHit,leaveIdx){if(currentLeaveHits[leaveIdx]>snapshotLeaveHits[leaveIdx]){hitLeavesIndices.push(leaveIdx)}});return hitLeavesIndices};HitsCollector.prototype.getHitBranches=function(currentHits,fileHitSnapshot){var hitBranches=[];for(var branchIdx in currentHits.b){var hitLeaves=this.getHitLeaves(currentHits.b[branchIdx],fileHitSnapshot.b[branchIdx]);if(hitLeaves.length>0){var branchData=currentHits.branchMap[branchIdx];hitBranches.push({branchData:branchData,hitLeaves:hitLeaves})}}return hitBranches};HitsCollector.prototype.createEmptyIstanbulModule=function(path,useDataKey){if(useDataKey===void 0){useDataKey=false}var emptyModule={f:{},fnMap:{},b:{},branchMap:{},path:path,s:{}};if(useDataKey){return{data:emptyModule}}return emptyModule};HitsCollector.prototype.getFileCoverageObjects=function(filename){var fileCoverageSnapshot=this._latestCoverageSnapshot[filename]||this.createEmptyIstanbulModule(filename);var currentFileCoverage=this._globalCoverageObject[filename];var shouldResolveRelativePath=true;if(!fileCoverageSnapshot.f&&fileCoverageSnapshot.data){fileCoverageSnapshot=fileCoverageSnapshot.data;shouldResolveRelativePath=false}if(!currentFileCoverage.f&¤tFileCoverage.data){currentFileCoverage=currentFileCoverage.data}return{fileCoverageSnapshot:fileCoverageSnapshot,currentFileCoverage:currentFileCoverage,shouldResolveRelativePath:shouldResolveRelativePath}};HitsCollector.prototype.getGlobalCoverageObject=function(){if(this._globalCoverageObject)return this._globalCoverageObject;this._globalCoverageObject=HitsCollector.resolveGlobalCoverageObject();if(!this._globalCoverageObject){this.logger.warn("Coverage object not found")}return this._globalCoverageObject};HitsCollector.resolveGlobalCoverageObject=function(){var re=/^\$\$cov_[0-9]+\$\$$/;var keys=Object.keys(global);for(var i=0;i<keys.length;i++){var k=keys[i];if(re.exec(k)!==null||GLOBAL_ISTANBUL_CONTAINER_NAMES.indexOf(k)>=0){return global[k]}}};HitsCollector.prototype.updateCoverageSnapshot=function(currentCounters){for(var istanbulModule in currentCounters){var useDataKey=currentCounters[istanbulModule].data!==undefined;this._latestCoverageSnapshot[istanbulModule]=this._latestCoverageSnapshot[istanbulModule]||this.createEmptyIstanbulModule(istanbulModule,useDataKey);var f=currentCounters[istanbulModule].f||currentCounters[istanbulModule].data.f;var b=currentCounters[istanbulModule].b||currentCounters[istanbulModule].data.b;for(var funcId in f){this.setFunctionHit(istanbulModule,funcId,f,useDataKey)}for(var branchId in b){this.setBranchHit(b,branchId,istanbulModule,useDataKey)}}};HitsCollector.prototype.setBranchHit=function(b,branchId,istanbulModule,useDataKey){var currentBranchesHits=b[branchId];this._latestCoverageSnapshot[istanbulModule].b[branchId]=this._latestCoverageSnapshot[istanbulModule].b[branchId]||[];for(var 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]}}};HitsCollector.prototype.setFunctionHit=function(istanbulModule,funcId,f,useDataKey){if(useDataKey){this._latestCoverageSnapshot[istanbulModule].data.f[funcId]=f[funcId]}else{this._latestCoverageSnapshot[istanbulModule].f[funcId]=f[funcId]}};return HitsCollector}();exports.HitsCollector=HitsCollector})}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../constants/sl-env-vars":305,"../coverage-elements/original-module-loader":310}],319:[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;var sl_env_vars_1=require("../constants/sl-env-vars");var original_module_loader_1=require("../coverage-elements/original-module-loader");var hits_collector_1=require("./hits-collector");var new_id_resolver_1=require("../coverage-elements/new-id-resolver");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var HitsConverter=function(){function HitsConverter(relativePathResolver,sourceMapData,projectRoot,logger){this.conversionErrors=[];this._slMapping={};this.relativePathResolver=relativePathResolver;this.sourceMapData=sourceMapData;this.projectRoot=projectRoot;this.logger=logger}HitsConverter.prototype.convertHits=function(hitFilesData){var _this=this;var methodUniqueIds=[];var branchUniqueIds=[];if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){new original_module_loader_1.OriginalModuleLoader(hits_collector_1.HitsCollector.resolveGlobalCoverageObject(),this.logger).load()}hitFilesData.forEach(function(fileHit){var 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}};Object.defineProperty(HitsConverter.prototype,"slMapping",{get:function(){return this._slMapping},set:function(value){this._slMapping=value},enumerable:false,configurable:true});HitsConverter.prototype.createMethodIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var methodIds=[];hitFunctions.forEach(function(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};HitsConverter.prototype.getDeclStart=function(hit){return hit.decl.start};HitsConverter.prototype.getDecl=function(hit){return hit.decl};HitsConverter.prototype.getStartLoc=function(hit){return hit.loc.start};HitsConverter.prototype.getLeaveStartLoc=function(hit,leaveIdx,absolutePath){var _a;var position=hit.branchData.locations[leaveIdx].start;var parentPosition=(_a=hit.branchData.loc)===null||_a===void 0?void 0:_a.start;if(!parentPosition){if(!sl_env_vars_1.SlEnvVars.isUseIstanbul()){var 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}var newInstrumentation=parentPosition.line!=position.line||parentPosition.column!=position.column;if(hit.branchData.type==="if"){var 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};HitsConverter.prototype.createBranchIds=function(hitFunctions,relativePath,absolutePath){var _this=this;var branchIds=[];hitFunctions.forEach(function(hit){hit.hitLeaves.forEach(function(leaveIdx){branchIds.push(_this.getBranchUniqueId(_this.getLeaveStartLoc(hit,leaveIdx,absolutePath),relativePath,absolutePath,leaveIdx))})});return branchIds};HitsConverter.prototype.getMethodUniqueId=function(startLoc,relativePath,absolutePath){var idParts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=idParts.relativePath+"@"+this.formatLoc(idParts.start);var uniqueId=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)};HitsConverter.prototype.getBranchUniqueId=function(startLoc,relativePath,absolutePath,leaveIndex){var uniqueId;var parts=this.resolveIdParts(startLoc,relativePath,absolutePath);if(sl_env_vars_1.SlEnvVars.isUseNewUniqueId()){var uniqueIdKey=parts.relativePath+"|"+this.formatLoc(parts.start)+"|"+leaveIndex;uniqueId=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};HitsConverter.prototype.resolveIdParts=function(startLoc,relativePath,absolutePath){var sourcePosition=this.sourceMapData.getSourcePosition(relativePath,absolutePath,startLoc,this.projectRoot,this.slMapping);return sourcePosition?sourcePosition:{relativePath:relativePath,start:startLoc,absolutePath:absolutePath}};HitsConverter.prototype.buildMethodUniqueId=function(parts){return parts.relativePath+HitsConverter.METHOD_ID_DEL+this.formatLoc(parts.start)};HitsConverter.prototype.sendConversionErrors=function(){if(this.conversionErrors.length>0){cockpit_notifier_1.CockpitNotifier.sendErrorsBatch(this.conversionErrors);this.conversionErrors=[]}};HitsConverter.prototype.formatLoc=function(loc){return loc.line+","+loc.column};HitsConverter.METHOD_ID_DEL="@";HitsConverter.BRANCH_ID_DEL="|";return HitsConverter}();exports.HitsConverter=HitsConverter})},{"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../coverage-elements/new-id-resolver":309,"../coverage-elements/original-module-loader":310,"./hits-collector":318}],320:[function(require,module,exports){var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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-conracts","../constants/sl-env-vars"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.FootprintsProcess=void 0;var footprints_buffer_1=require("./footprints-buffer");var collection_interval_1=require("../footprints-process/collection-interval");var state_tracker_1=require("../state-tracker");var cockpit_notifier_1=require("../agent-events/cockpit-notifier");var agent_events_conracts_1=require("../agent-events/agent-events-conracts");var sl_env_vars_1=require("../constants/sl-env-vars");var FootprintsProcess=function(){function FootprintsProcess(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()}FootprintsProcess.prototype.enqueueCurrentFootprints=function(execution,testName,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){var hitFilesData,convertedHits;return __generator(this,function(_a){switch(_a.label){case 0:this.currentExecutionBsid=execution.buildSessionId;this.collectionInterval.next();return[4,this.hitsCollector.getHitElements()];case 1:hitFilesData=_a.sent();if(hitFilesData.length){this.logger.info("Collecting hits for '"+hitFilesData.length+"' files");convertedHits=this.hitsConverter.convertHits(hitFilesData);this.footprintsBuffer.addHit(convertedHits,this.collectionInterval.toJson(),execution.executionId,testName,this.isInitFootprints(),isFinalFootprints)}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.start()}this.footprintsEnqueueOnce=true;return[2]}})})};FootprintsProcess.prototype.updateConfig=function(updatedCfg){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:this.cfg=updatedCfg;return[4,this.stopIfNeededAfterConfigChanged(updatedCfg)];case 1:_a.sent();this.sendToServerWatchdog.setInterval(this.cfg.footprintsSendIntervalSecs.value);this.footprintsBuffer.agentConfig=updatedCfg;return[2]}})})};FootprintsProcess.prototype.stopIfNeededAfterConfigChanged=function(updatedCfg){return __awaiter(this,void 0,void 0,function(){var e_1;return __generator(this,function(_a){switch(_a.label){case 0:if(!(updatedCfg.sendFootprints.value===false||updatedCfg.enabled.value===false))return[3,4];cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.AGENT_MUTED);this.footprintsBuffer.resetState();_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.stop()];case 2:_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error("Error stopping footprints process "+e_1.message);this.logger.debug(e_1.stackTrace);return[3,4];case 4:return[2]}})})};FootprintsProcess.prototype.ensureKeepaliveThreadRunning=function(){this.keepaliveWatchdog.start()};FootprintsProcess.prototype.submitQueuedFootprints=function(execution){return __awaiter(this,void 0,void 0,function(){var packet,e_2;return __generator(this,function(_a){switch(_a.label){case 0:if(!this.shouldSubmitFootprints()){return[2]}packet=this.footprintsBuffer.createPacket();if(!packet)return[3,6];this.ongoingRequestsCounter++;_a.label=1;case 1:_a.trys.push([1,3,4,5]);return[4,this.backendProxy.submitFootprintsV6(packet,execution.buildSessionId,execution.testStage,this.cfg.buildSessionId.value)];case 2:_a.sent();this.logger.info("Footprints packet submitted successfully. packet contains "+packet.methods.length+" methods, "+packet.branches.length+" branches in "+packet.executions.length+" executions");return[3,5];case 3:e_2=_a.sent();this.logger.error("Error while submitting footprints '"+e_2+"'");cockpit_notifier_1.CockpitNotifier.sendEvent(agent_events_conracts_1.AgentEventCode.FOOTPRINTS_LOSS);return[3,5];case 4:this.ongoingRequestsCounter--;return[7];case 5:return[3,7];case 6:this.logger.info("No hits collected nothing to submit");_a.label=7;case 7:return[2]}})})};FootprintsProcess.prototype.shouldSubmitFootprints=function(){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};FootprintsProcess.prototype.start=function(){if(this.isRunning)return;if(this.cfg.enabled.value==false)return;this.isRunning=true;this.sendToServerWatchdog.start();if(this.footprintsBuffer.hasHitsInBuffer()){this.ensureKeepaliveThreadRunning()}};FootprintsProcess.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var packet,e_3;return __generator(this,function(_a){switch(_a.label){case 0:this.sendToServerWatchdog.stop();if(!this.shouldSubmitFootprints()){this.isRunning=false;return[2]}return[4,this.flushCurrentFootprints(true)];case 1:_a.sent();packet=this.footprintsBuffer.createPacket();this.isRunning=false;if(!packet){this.logger.info("No hits collected, nothing to submit");return[2]}this.logger.info("Start submitting footprints, triggered by stop event.");_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.backendProxy.submitFootprintsV6(packet,this.currentExecutionBsid,this.stateTracker.getTestStage(),this.cfg.buildSessionId.value)];case 3:_a.sent();this.logger.info("Final footprints submitted successfully");return[3,5];case 4:e_3=_a.sent();this.logger.error("Failed to submit final footprints, error: "+e_3.message);this.logger.debug(e_3);return[2];case 5:return[2]}})})};FootprintsProcess.prototype.handleTestIdChanged=function(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{if(!this.stateTracker.shouldCollectHits()){this.logger.info("Test identifier changed, couldn't find active execution for anonymous footprints. Skip enqueuing footprints process.");return}this.logger.debug("Test identifier changed, start enqueuing footprints process.");var prevTestIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(previousTestIdentifier);this.enqueueCurrentFootprints(this.stateTracker.currentExecution,prevTestIdentifierParts.testName)}};FootprintsProcess.prototype.delegateEvents=function(){var _this=this;this.sendToServerWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){_this.logger.debug("Start submitting footprints, triggered by send to server watchdog.");_this.submitQueuedFootprints(_this.stateTracker.currentExecution)});this.keepaliveWatchdog.on(FootprintsProcess.ALARM_FIRED,function(){if(!_this.hasOngoingRequests()&&!_this.footprintsBuffer.hasHitsInBuffer()){_this.keepaliveWatchdog.stop()}});this.footprintsBuffer.on(footprints_buffer_1.FootprintsBuffer.BUFFER_FULL,function(){_this.submitQueuedFootprints(_this.stateTracker.currentExecution)});this.stateTracker.on(state_tracker_1.StateTracker.EXECUTION_BSID_CHANGED,function(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,function(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,function(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,function(execution){_this.enqueueAndSubmit(execution)})};FootprintsProcess.prototype.enqueueAndSubmit=function(executionData,isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.enqueueCurrentFootprints(executionData,null,isFinalFootprints)];case 1:_a.sent();return[4,this.submitQueuedFootprints(executionData)];case 2:_a.sent();return[2]}})})};FootprintsProcess.prototype.flushCurrentFootprints=function(isFinalFootprints){if(isFinalFootprints===void 0){isFinalFootprints=false}return __awaiter(this,void 0,void 0,function(){var currentTestIdentifier,testIdentifierParts;return __generator(this,function(_a){switch(_a.label){case 0:currentTestIdentifier=this.stateTracker.getCurrentTestIdentifier();if(!currentTestIdentifier)return[3,2];testIdentifierParts=state_tracker_1.StateTracker.splitTestIdToExecutionAndTestName(currentTestIdentifier);this.logger.debug("Enqueue footprints interval - start enqueuing process. currentTestIdentifier: '%s'",currentTestIdentifier);return[4,this.enqueueCurrentFootprints(this.stateTracker.currentExecution,testIdentifierParts.testName,isFinalFootprints)];case 1:_a.sent();return[3,5];case 2:if(!this.stateTracker.shouldCollectHits())return[3,4];this.logger.debug("Enqueue footprints interval - start enqueuing process. anonymous footprints");return[4,this.enqueueCurrentFootprints(this.stateTracker.currentExecution,null,isFinalFootprints)];case 3:_a.sent();return[3,5];case 4:this.logger.info("Enqueue footprints interval - no active execution. skip enqueuing process.");this.handleNoExecutionFound();_a.label=5;case 5:return[2]}})})};FootprintsProcess.prototype.handleNoExecutionFound=function(){if(this.stateTracker.openExecutionFoundOnce){this.logger.debug("No active execution and not in initFootprints mode, updating coverage snapshot");this.hitsCollector.dropHits()}};FootprintsProcess.prototype.isInitFootprints=function(){return this.stateTracker.openExecutionFoundOnce&&!this.footprintsEnqueueOnce};FootprintsProcess.prototype.hasOngoingRequests=function(){return this.ongoingRequestsCounter>0};FootprintsProcess.prototype.loadSlMapping=function(){return __awaiter(this,void 0,void 0,function(){var mappingsArr,flatted;return __generator(this,function(_a){switch(_a.label){case 0:if(!sl_env_vars_1.SlEnvVars.useSlMapping()){return[2]}return[4,this.backendProxy.getBlobsAsJson(this.cfg.buildSessionId.value)];case 1:mappingsArr=_a.sent();flatted={};mappingsArr.forEach(function(mapping){flatted=__assign(__assign({},flatted),mapping)});this.hitsConverter.slMapping=flatted;return[2]}})})};FootprintsProcess.ALARM_FIRED="alarm";return FootprintsProcess}();exports.FootprintsProcess=FootprintsProcess})},{"../agent-events/agent-events-conracts":289,"../agent-events/cockpit-notifier":294,"../constants/sl-env-vars":305,"../footprints-process/collection-interval":323,"../state-tracker":332,"./footprints-buffer":317}],321:[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+"'"}}})},{}],322:[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;var RelativePathResolver=function(){function RelativePathResolver(projectRoot){this.absoluteToRelativePath=new Map;this.projectRoot=projectRoot}RelativePathResolver.prototype.getRelativePath=function(absolutePath){if(!this.absoluteToRelativePath.get(absolutePath)){absolutePath=this.adjustPathSlashes(absolutePath);var relativePath=absolutePath.replace(this.resolveProjectRoot(),"");if(relativePath.indexOf("/")===0){relativePath=relativePath.substring(1)}this.absoluteToRelativePath.set(absolutePath,relativePath)}return this.absoluteToRelativePath.get(absolutePath)};RelativePathResolver.prototype.adjustPathSlashes=function(filePath){return(filePath||"").replace(/\\/g,"/")};RelativePathResolver.prototype.resolveProjectRoot=function(){return(this.projectRoot||process.cwd()).replace(/\\/g,"/")};return RelativePathResolver}();exports.RelativePathResolver=RelativePathResolver})}).call(this)}).call(this,require("_process"))},{_process:179}],323:[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;var system_date_1=require("../system-date");var CollectionInterval=function(){function CollectionInterval(intervalInMS){this.intervalInSeconds=this.toSeconds(intervalInMS);this.start=this.toSeconds(system_date_1.getSystemDateValueOf())}CollectionInterval.prototype.next=function(){if(this.end){this.start=this.end}this.end=this.toSeconds(system_date_1.getSystemDateValueOf());if(this.end-this.start>this.intervalInSeconds){this.start=this.end-this.intervalInSeconds}};CollectionInterval.prototype.toJson=function(){return{start:this.start,end:this.end}};CollectionInterval.prototype.toSeconds=function(time){return Math.floor(time/1e3)};return CollectionInterval}();exports.CollectionInterval=CollectionInterval})},{"../system-date":333}],324:[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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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","./http-client","./sl-routes","../utils/validation-utils","./entities-mapper","../constants/constants","../constants/sl-env-vars","../utils/timer-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BackendProxy=void 0;var contracts_1=require("./contracts");var http_client_1=require("./http-client");var sl_routes_1=require("./sl-routes");var validation_utils_1=require("../utils/validation-utils");var entities_mapper_1=require("./entities-mapper");var constants_1=require("../constants/constants");var sl_env_vars_1=require("../constants/sl-env-vars");var timer_utils_1=require("../utils/timer-utils");var BackendProxy=function(){function BackendProxy(agentInstanceData,config,logger,httpClient){this.agentInstanceData=agentInstanceData;this.config=config;this.logger=logger;this.client=httpClient||new http_client_1.HttpClient(this.config,this.logger)}BackendProxy.prototype.getBuildSession=function(buildSessionId,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,constants_1.Constants.BUILD_SESSION_ID);var url=sl_routes_1.SLRoutes.buildSessionV2(buildSessionId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.createBuildSessionId=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildSessionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body,entities_mapper_1.EntitiesMapper.toCreateBuildSessionIdResponse)})};BackendProxy.prototype.createBuildSessionIdPromise=function(request){return __awaiter(this,void 0,void 0,function(){var url;var _this=this;return __generator(this,function(_a){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);url=constants_1.Constants.PULL_REQUEST_PARAMS in request?sl_routes_1.SLRoutes.prBuildSession():sl_routes_1.SLRoutes.buildSessionV2();return[2,new Promise(function(resolve,reject){_this.client.post(request,url,function(err,body){if(err){return reject(err)}return resolve(body)})})]})})}
|
|
32
|
+
;BackendProxy.prototype.getRecommendedVersion=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.recommendedAgentV2(request.componentName,request.customerId,request.appName,request.branchName,request.testStage);return new Promise(function(resolve,reject){_this.client.get(url,function(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."))}})})};BackendProxy.prototype.submitBuildMapping=function(request){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.buildMappingV4();return this.submitPostRequestWithRetries(request,url)};BackendProxy.prototype.submitLogs=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.logSubmissionV2();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfig=function(request,callback){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);var url=sl_routes_1.SLRoutes.configV3(this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);this.client.get(url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.getRemoteConfigPromise=function(request){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(request,constants_1.Constants.REQUEST);return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.configV3(_this.agentInstanceData,request.appName,request.branch,request.build,request.testStage,request.labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)})})};BackendProxy.prototype.startExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.testExecution();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.startColoredExecution=function(request){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecution();_this.client.post(request,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.testExecutionV4=function(labId,async,executionId){var _this=this;if(async===void 0){async=true}return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.testExecutionV4(labId);_this.client.get(url,function(err,body){if(err){reject(err)}resolve(body)},false,async)})};BackendProxy.prototype.uploadReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalData();this.client.postMultipart(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.externalReport=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.externalReport();this.client.post(request,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecution=function(request,callback){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;this.client.delete(body,url,function(err,body){_this.invokeCallback(callback,err,body)})};BackendProxy.prototype.endExecutionPromise=function(request){var _this=this;var url=sl_routes_1.SLRoutes.endExecution(request.customerId,request.appName,request.buildName,request.branchName,request.environment);var body=request.executionIds?{executionIds:request.executionIds}:null;return new Promise(function(resolve,reject){_this.client.delete(body,url,function(err){err?reject(err):resolve()})})};BackendProxy.prototype.submitEvents=function(packetToSend,callback,async){if(async===void 0){async=true}var url=sl_routes_1.SLRoutes.eventsV2();this.client.post(packetToSend,url,callback)};BackendProxy.prototype.submitEventsPromise=function(packetToSend){var _this=this;return new Promise(function(resolve,reject){var url=sl_routes_1.SLRoutes.eventsV2();_this.client.post(packetToSend,url,function(err){if(err){reject(err)}resolve()})})};BackendProxy.prototype.submitBlobAsync=function(body,buildSessionId,blobId){var _this=this;var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,statusCode){_this.logger.debug("Blob "+blobId+" uploaded with status code "+statusCode);if(error){_this.logger.error("Error while submitting sl-mapping, '"+error+"'");return reject(error)}else{_this.logger.info("sl-mapping submitted successfully");return resolve({})}},true,contracts_1.ContentType.OCTET_STREAM)})};BackendProxy.prototype.submitBlob=function(body,buildSessionId,blobId,callback){var url=sl_routes_1.SLRoutes.blobs(buildSessionId,blobId);this.client.post(body,url,callback,true,contracts_1.ContentType.OCTET_STREAM)};BackendProxy.prototype.getBlobsAsJson=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var slMapping,url,e_1;return __generator(this,function(_a){switch(_a.label){case 0:slMapping=[];_a.label=1;case 1:_a.trys.push([1,3,,4]);url=sl_routes_1.SLRoutes.blobsForBsidAsJson(buildSessionId);return[4,this.submitGetRequestWithRetries(url)];case 2:slMapping=_a.sent();return[3,4];case 3:e_1=_a.sent();this.logger.error(e_1);return[3,4];case 4:return[2,slMapping]}})})};BackendProxy.prototype.submitAgentEvent=function(body){var _this=this;var url=sl_routes_1.SLRoutes.agentEvents();return new Promise(function(resolve,reject){_this.client.post(body,url,function(error,response){if(error){return reject(error)}return resolve()})})};BackendProxy.prototype.getTestsRecommendation=function(buildSessionId,stage){var url=sl_routes_1.SLRoutes.testsRecommendations(buildSessionId,stage);return this.submitGetRequestWithRetries(url,null,null,[400,404],false)};BackendProxy.prototype.addOrUpdateIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitPutRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.deleteIntegrationBuildComponents=function(buildSessionId,components,agentId){var url=sl_routes_1.SLRoutes.integrationBuildComponents(buildSessionId);return this.submitDelRequestWithRetries({components:components,agentId:agentId},url)};BackendProxy.prototype.buildEnd=function(data){return this.submitPostRequestWithRetries(data,sl_routes_1.SLRoutes.buildEnd())};BackendProxy.prototype.submitFootprintsV6=function(footprintsPacket,executionBsid,testStage,buildSessionId){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){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);url=sl_routes_1.SLRoutes.footprintsV6(executionBsid,testStage,buildSessionId);return[2,this.submitPostRequestWithRetries(footprintsPacket,url,null,null,true,contracts_1.ContentType.OCTET_STREAM)]})})};BackendProxy.prototype.getBuildSessionData=function(buildSessionId){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a){return[2,new Promise(function(resolve,reject){_this.getBuildSession(buildSessionId,function(err,response){err?reject(err):resolve(response)})})]})})};BackendProxy.prototype.getRecommendedAgent=function(configuration){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){return[2,{}]})})};BackendProxy.prototype.getBuildSessionDataFromLabId=function(labid){return __awaiter(this,void 0,void 0,function(){var url;return __generator(this,function(_a){url=sl_routes_1.SLRoutes.activeBuildSessionId(labid);return[2,this.submitGetRequestWithRetries(url)]})})};BackendProxy.prototype.invokeCallback=function(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)}var apiResponse=map(body);return callback(null,apiResponse)};BackendProxy.prototype.submitPostRequestWithRetries=function(body,url,retries,delayBetweenRetires,async,contentType){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.post(body,url,callback,async,contentType)},retries,delayBetweenRetires)};BackendProxy.prototype.submitPutRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.put(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitDelRequestWithRetries=function(body,url,retries,delayBetweenRetires){var _this=this;return this.makeRequestWithRetries(function(callback){_this.client.delete(body,url,callback)},retries,delayBetweenRetires)};BackendProxy.prototype.submitGetRequestWithRetries=function(url,retries,delayBetweenRetires,statusesForRetry,isNotFoundAcceptable){var _this=this;if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}return this.makeRequestWithRetries(function(callback){_this.client.get(url,callback,isNotFoundAcceptable)},retries,delayBetweenRetires,statusesForRetry)};BackendProxy.prototype.makeRequestWithRetries=function(doSingleRequest,retries,delayBetweenRetires,statusesForRetry){return __awaiter(this,void 0,void 0,function(){var retriesLeft,intervalBetweenRetries,lastError,bodyAndStatusCode,errAndStatusCode_1;return __generator(this,function(_a){switch(_a.label){case 0:retriesLeft=retries||sl_env_vars_1.SlEnvVars.getHttpMaxAttempts()||BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS;intervalBetweenRetries=delayBetweenRetires||sl_env_vars_1.SlEnvVars.getHttpAttemptInterval()||BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL;lastError=undefined;_a.label=1;case 1:_a.trys.push([1,3,,4]);retriesLeft--;return[4,new Promise(function(resolve,reject){doSingleRequest(function(err,body,statusCode){err?reject({err:err,statusCode:statusCode}):resolve({body:body,statusCode:statusCode})})})];case 2:bodyAndStatusCode=_a.sent();return[2,bodyAndStatusCode.body];case 3:errAndStatusCode_1=_a.sent();this.logger.info(errAndStatusCode_1);lastError=errAndStatusCode_1.err;if(!this.shouldRetryRequest(errAndStatusCode_1.statusCode,statusesForRetry)){return[3,7]}return[3,4];case 4:return[4,timer_utils_1.TimerUtils.sleep(intervalBetweenRetries)];case 5:_a.sent();_a.label=6;case 6:if(retriesLeft>0)return[3,1];_a.label=7;case 7:throw lastError}})})};BackendProxy.prototype.shouldRetryRequest=function(statusCode,statusesForRetry){if(statusesForRetry===void 0){statusesForRetry=[]}if(statusCode>=500||statusCode&&statusesForRetry.includes(statusCode))return true;return false};BackendProxy.DEFAULT_HTTP_MAX_ATTEMPTS=6;BackendProxy.DEFAULT_HTTP_ATTEMPT_INTERVAL=5*1e3;return BackendProxy}();exports.BackendProxy=BackendProxy})},{"../constants/constants":304,"../constants/sl-env-vars":305,"../utils/timer-utils":336,"../utils/validation-utils":337,"./contracts":325,"./entities-mapper":326,"./http-client":327,"./sl-routes":329}],325:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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.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.HttpClientConfigData=void 0;var system_date_1=require("../system-date");var HttpClientConfigData=function(){function HttpClientConfigData(){}return HttpClientConfigData}();exports.HttpClientConfigData=HttpClientConfigData;var CreateBuildSessionIdResponse=function(){function CreateBuildSessionIdResponse(){}return CreateBuildSessionIdResponse}();exports.CreateBuildSessionIdResponse=CreateBuildSessionIdResponse;var GetVersionRequest=function(){function GetVersionRequest(){}return GetVersionRequest}();exports.GetVersionRequest=GetVersionRequest;var GetVersionResponse=function(){function GetVersionResponse(){}return GetVersionResponse}();exports.GetVersionResponse=GetVersionResponse;var AgentInfo=function(){function AgentInfo(){}return AgentInfo}();exports.AgentInfo=AgentInfo;var VersionMeta=function(){function VersionMeta(){}return VersionMeta}();exports.VersionMeta=VersionMeta;var VersionMetaQuery=function(){function VersionMetaQuery(){}return VersionMetaQuery}();exports.VersionMetaQuery=VersionMetaQuery;var BuildMappingRequest=function(){function BuildMappingRequest(){}return BuildMappingRequest}();exports.BuildMappingRequest=BuildMappingRequest;var DependencyData=function(){function DependencyData(){}return DependencyData}();exports.DependencyData=DependencyData;var FileData=function(){function FileData(){}return FileData}();exports.FileData=FileData;var GetRemoteConfigRequest=function(){function GetRemoteConfigRequest(){}return GetRemoteConfigRequest}();exports.GetRemoteConfigRequest=GetRemoteConfigRequest;var SubmitLogsRequest=function(){function SubmitLogsRequest(){this.creationTime=system_date_1.getSystemDateValueOf()}return SubmitLogsRequest}();exports.SubmitLogsRequest=SubmitLogsRequest;var BaseRequest=function(){function BaseRequest(){}return BaseRequest}();exports.BaseRequest=BaseRequest;var StartExecutionRequest=function(_super){__extends(StartExecutionRequest,_super);function StartExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return StartExecutionRequest}(BaseRequest);exports.StartExecutionRequest=StartExecutionRequest;var EndExecutionRequest=function(_super){__extends(EndExecutionRequest,_super);function EndExecutionRequest(){return _super!==null&&_super.apply(this,arguments)||this}return EndExecutionRequest}(BaseRequest);exports.EndExecutionRequest=EndExecutionRequest;var UploadReportRequest=function(_super){__extends(UploadReportRequest,_super);function UploadReportRequest(){return _super!==null&&_super.apply(this,arguments)||this}return UploadReportRequest}(BaseRequest);exports.UploadReportRequest=UploadReportRequest;var AgentData=function(){function AgentData(){}return AgentData}();exports.AgentData=AgentData;var EnvironmentData=function(){function EnvironmentData(){}return EnvironmentData}();exports.EnvironmentData=EnvironmentData;var UploadReportsBody=function(){function UploadReportsBody(){}return 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=exports.RecommendationSetStatus||(exports.RecommendationSetStatus={}));var ContentType;(function(ContentType){ContentType["OCTET_STREAM"]="application/octet-stream";ContentType["JSON"]="application/json"})(ContentType=exports.ContentType||(exports.ContentType={}))})},{"../system-date":333}],326:[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;var contracts_1=require("./contracts");var EntitiesMapper=function(){function EntitiesMapper(){}EntitiesMapper.toCreateBuildSessionIdResponse=function(body){if(body==null)return null;var response=new contracts_1.CreateBuildSessionIdResponse;response.buildSessionId=body;return response};return EntitiesMapper}();exports.EntitiesMapper=EntitiesMapper})},{"./contracts":325}],327:[function(require,module,exports){(function(process,Buffer){(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","./contracts","request","zlib","../constants/sl-env-vars","./http-verb","../utils/validation-utils"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HttpClient=void 0;var contracts_1=require("./contracts");var request=require("request");var zlib=require("zlib");var sl_env_vars_1=require("../constants/sl-env-vars");var http_verb_1=require("./http-verb");var validation_utils_1=require("../utils/validation-utils");var HttpClient=function(){function HttpClient(cfg,logger){this.cfg=cfg;this.logger=logger;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(cfg,"cfg");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(logger,"logger");this.defaultTimeout=this.getDefaultTimeout()}HttpClient.prototype.get=function(urlPath,callback,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}this.invokeHttpRequest(http_verb_1.HttpVerb.GET,urlPath,callback,null,null,null,isNotFoundAcceptable)};HttpClient.prototype.delete=function(body,urlPath,callback){this.invokeHttpRequest(http_verb_1.HttpVerb.DELETE,urlPath,callback,null,body)};HttpClient.prototype.put=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.PUT,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.post=function(requestData,urlPath,callback,async,contentType){return this.submitRequestWithBody(http_verb_1.HttpVerb.POST,requestData,urlPath,callback,async,contentType)};HttpClient.prototype.postMultipart=function(requestData,urlPath,callback){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.agentData,"requestData.agentData");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData.reportFile,"requestData.reportFile");var agentData=requestData.agentData;var reportFile=requestData.reportFile;try{var opts=this.createDefaultOptions(urlPath);var onRequestCallback=this.createOnRequestCallback({httpVerb:http_verb_1.HttpVerb.POST,callback:callback});this.logger.info("Sending "+http_verb_1.HttpVerb.POST+" request. Url: '"+opts.url+"'");var req=request.post(opts,onRequestCallback);var form=req.form();form.append("file",JSON.stringify(agentData),{filename:"agentData",contentType:"multipart/form-data"});form.append("file",reportFile.buffer.toString(),{filename:"report",contentType:"multipart/form-data"})}catch(err){this.logger.error("Failed sending Http "+http_verb_1.HttpVerb.POST+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.submitRequestWithBody=function(verb,requestData,urlPath,callback,async,contentType){var _this=this;validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(requestData,"requestData");var bufferToSend=Buffer.from(JSON.stringify(requestData));var shouldZip=this.cfg.compressRequests!=null?this.cfg.compressRequests:true;this.logger.debug("Sending buffer:"+bufferToSend.toString());if(shouldZip){zlib.gzip(bufferToSend,function(err,compressedBuf){if(err){_this.logger.warn("Failed while trying to compress the request data. Sending uncompressed data instead. Error: ",err);_this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}else{_this.invokeHttpRequest(verb,urlPath,callback,{"Content-Encoding":"gzip"},compressedBuf,contentType)}})}else{this.invokeHttpRequest(verb,urlPath,callback,null,bufferToSend,contentType)}};HttpClient.prototype.invokeHttpRequest=function(httpVerb,urlPath,callback,additionalHeaders,buffer,contentType,isNotFoundAcceptable){if(isNotFoundAcceptable===void 0){isNotFoundAcceptable=true}validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(httpVerb,"httpVerb");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(urlPath,"urlPath");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(callback,"callback");try{var opts=this.createDefaultOptions(urlPath,contentType);if(additionalHeaders){for(var header in additionalHeaders){opts.headers[header]=additionalHeaders[header]}}var onRequestCallback=this.createOnRequestCallback({httpVerb:httpVerb,callback:callback,isNotFoundAcceptable:isNotFoundAcceptable});this.logger.info("Sending "+httpVerb+" request. Url: '"+opts.url+"'");if(httpVerb===http_verb_1.HttpVerb.GET){opts.json=true;request.get(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.DELETE){if(buffer)opts.body=buffer;opts.json=true;request.delete(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.POST){opts.body=buffer;request.post(opts,onRequestCallback)}else if(httpVerb===http_verb_1.HttpVerb.PUT){opts.body=buffer;request.put(opts,onRequestCallback)}else{new Error(httpVerb+" is not implemented yet.")}}catch(err){this.logger.error("Failed sending Http "+httpVerb+" request to:'"+urlPath+"'. Error: '"+err+"'");return callback(err,null,null)}};HttpClient.prototype.createOnRequestCallback=function(_a){var _this=this;var httpVerb=_a.httpVerb,callback=_a.callback,isNotFoundAcceptable=_a.isNotFoundAcceptable;var handler=function(err,requestResponse,body){var txId=requestResponse&&requestResponse.headers&&requestResponse.headers["x-sl-txid"];if(err||requestResponse!=null&&(requestResponse.statusCode<200||requestResponse.statusCode>=400)){var statusCode=-1;if(requestResponse!=null){statusCode=requestResponse.statusCode;_this.logger.warn("Got "+statusCode+" in '"+httpVerb+"' request. Transaction ID:'"+txId+"'.")}if(err){err=new Error("HttpClient failed. Error: "+err.message+", StatusCode: "+statusCode+", Stack: "+err.stack)}else if(statusCode===404&&isNotFoundAcceptable){err=null}else{var errorMessage="Server returned: "+statusCode+" status code in '"+httpVerb+"' request. Transaction ID:'"+txId+"'.";try{if(body)errorMessage+=Object.entries(JSON.parse(body)).map(function(_a){var key=_a[0],val=_a[1];return"\n\t"+key+": "+val}).join("")}catch(e){errorMessage+="Parsing of server response failed, body: "+body+", transaction ID:'"+txId+"', error: "+e}err=new Error(errorMessage)}return callback(err,body,statusCode)}_this.logger.debug("'"+httpVerb+"' request was completed successfully. statusCode: "+requestResponse.statusCode+" body: "+body+", Transaction ID: "+txId);if(body&&body.length>0&&typeof body=="string"){try{body=JSON.parse(body)}catch(e){_this.logger.error("An error occurred parsing the body: ["+body+"], error: "+e)}}return callback(null,body,requestResponse.statusCode)};return handler};HttpClient.prototype.allowUntrustedCertificates=function(){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0"};HttpClient.prototype.createDefaultOptions=function(urlPath,contentType){if(contentType===void 0){contentType=contracts_1.ContentType.JSON}var opts={url:this.cfg.server+urlPath,headers:{"Content-Type":contentType,Authorization:"Bearer "+this.cfg.token},timeout:this.defaultTimeout};opts["compressed"]=true;if(this.cfg.proxy!=null){opts.proxy=this.cfg.proxy;this.allowUntrustedCertificates()}return opts};HttpClient.prototype.getDefaultTimeout=function(){var timeout=sl_env_vars_1.SlEnvVars.getHttpTimeout();if(timeout==null){timeout=60*1e3*2}timeout=Number(timeout);this.logger.debug("Http timeout value is '"+timeout+"'.");return timeout};return HttpClient}();exports.HttpClient=HttpClient})}).call(this)}).call(this,require("_process"),require("buffer").Buffer)},{"../constants/sl-env-vars":305,"../utils/validation-utils":337,"./contracts":325,"./http-verb":328,_process:179,buffer:71,request:454,zlib:68}],328:[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.HttpVerb=void 0;var HttpVerb;(function(HttpVerb){HttpVerb["GET"]="GET";HttpVerb["POST"]="POST";HttpVerb["DELETE"]="DELETE";HttpVerb["PUT"]="PUT"})(HttpVerb=exports.HttpVerb||(exports.HttpVerb={}))})},{}],329:[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;var constants_1=require("../constants/constants");var validation_utils_1=require("../utils/validation-utils");var SLRoutes=function(){function SLRoutes(){}SLRoutes.agentsV1=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV2=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV3=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV4=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV5=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V5)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.agentsV6=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V6)+SLRoutes.toUri(SLRoutes.AGENTS)};SLRoutes.testExecution=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)};SLRoutes.testExecutionV4=function(labId,executionId){var url=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V4)+SLRoutes.toUri(SLRoutes.TEST_EXECUTION)+SLRoutes.toUri(labId);if(executionId){url+=SLRoutes.buildQueryParams({executionId:executionId})}return url};SLRoutes.endExecution=function(customerId,appName,buildName,branchName,environment){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(appName,"appName");validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(customerId,"customerId");var result=SLRoutes.testExecution();var query={customerId:customerId,appName:appName,buildName:buildName,branchName:branchName,environment:environment};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.externalData=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.toUri(SLRoutes.EXTERNAL_DATA)};SLRoutes.externalReport=function(){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.EXTERNAL_REPORT)};SLRoutes.configV3=function(agentInstanceData,appName,branchName,buildName,testStage,labId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(agentInstanceData,"agentInstanceData");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V3)+SLRoutes.CONFIG;var 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};SLRoutes.buildSessionV2=function(buildSessionId){var result=SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.BUILD_SESSION_ID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.prBuildSession=function(){return SLRoutes.buildSessionV2()+SLRoutes.toUri(SLRoutes.PULL_REQUEST)};SLRoutes.logSubmissionV2=function(){var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.LOG_SUBMISSION;return result};SLRoutes.buildMappingV4=function(){var result=SLRoutes.agentsV4()+SLRoutes.toUri(SLRoutes.BUILD_MAPPING);return result};SLRoutes.footprintsV5=function(){var result=SLRoutes.agentsV5()+SLRoutes.toUri(SLRoutes.FOOTPRINTS);return result};SLRoutes.footprintsV6=function(executionBsid,testStage,buildSessionId){return SLRoutes.agentsV6()+SLRoutes.toUri(executionBsid)+SLRoutes.toUri(SLRoutes.FOOTPRINTS)+SLRoutes.toUri(testStage)+SLRoutes.toUri(buildSessionId)};SLRoutes.eventsV2=function(){return SLRoutes.agentsV2()+SLRoutes.toUri(SLRoutes.EVENTS)};SLRoutes.productionV1=function(buildSessionId){validation_utils_1.ValidationUtils.verifyNotNullOrEmpty(buildSessionId,"buildSessionId");var result=SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.toUri(SLRoutes.AGENTS)+SLRoutes.toUri(SLRoutes.PRODUCTION)+SLRoutes.toUri(SLRoutes.BSID)+SLRoutes.toUri(buildSessionId);return result};SLRoutes.recommendedAgentV2=function(component,customerId,appName,branchName,testStage){if(!component){throw new Error("'component' "+constants_1.Constants.Messages.CANNOT_BE_NULL_OR_UNDEFINED+".")}var result=SLRoutes.agentsV2()+SLRoutes.toUri(component)+SLRoutes.toUri(SLRoutes.RECOMMENDED_VERSION);var query={customerId:customerId,appName:appName,branch:branchName,envName:testStage};result+=SLRoutes.buildQueryParams(query);return result};SLRoutes.blobs=function(buildSessionId,blobId){return SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(blobId)};SLRoutes.blobsForBsidAsJson=function(buildSessionId){var url=SLRoutes.agentsV1()+SLRoutes.toUri(SLRoutes.BLOBS)+SLRoutes.toUri(buildSessionId);url=url.slice(0,-1);return url+SLRoutes.buildQueryParams({view:"concatJson"})};SLRoutes.agentEvents=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.AGENT_EVENTS)};SLRoutes.testsRecommendations=function(buildSessionId,stage){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V2)+SLRoutes.toUri(SLRoutes.TEST_EXCLUSIONS)+SLRoutes.toUri(buildSessionId)+SLRoutes.toUri(stage)};SLRoutes.integrationBuildComponents=function(buildSessionId){return SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.V1)+SLRoutes.AGENTS+SLRoutes.SLASH+SLRoutes.toUri(SLRoutes.INTEGRATION_BUILDS)+SLRoutes.toUri(buildSessionId)+SLRoutes.COMPONENTS};SLRoutes.buildEnd=function(){return SLRoutes.agentsV3()+SLRoutes.toUri(SLRoutes.BUILD_END)};SLRoutes.activeBuildSessionId=function(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)};SLRoutes.toUri=function(uri){if(uri==null||uri.length==null||uri.length===0){return""}
|
|
33
|
+
return encodeURIComponent(uri)+SLRoutes.SLASH};SLRoutes.buildQueryParams=function(paramsMap){if(!paramsMap){throw new Error("'paramsMap' cannot be null or undefined.")}var queryString="";for(var key in paramsMap){var value=paramsMap[key];queryString+=SLRoutes.addQueryStringValue(key,value)}queryString="?"+queryString;queryString=queryString.substring(0,queryString.length-1);return queryString};SLRoutes.addQueryStringValue=function(key,value){if(!key&&!value)return"";if(!value){value=""}var paramString="";paramString+=encodeURIComponent(key);paramString+="=";paramString+=encodeURIComponent(value);paramString+="&";return paramString};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";return SLRoutes}();exports.SLRoutes=SLRoutes})},{"../constants/constants":304,"../utils/validation-utils":337}],330:[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;var fs=require("fs");var sourceMap=require("source-map");var SourceMapsUtils=function(){function SourceMapsUtils(){}SourceMapsUtils.readSourceMaps=function(fullFilename){if(!fullFilename)return;var sourceMapsFilename=fullFilename+".map";var 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}};return SourceMapsUtils}();exports.SourceMapsUtils=SourceMapsUtils})},{fs:69,"source-map":228}],331:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var state_tracker_1=require("./state-tracker");var StateTrackerFpv6=function(_super){__extends(StateTrackerFpv6,_super);function StateTrackerFpv6(){return _super!==null&&_super.apply(this,arguments)||this}StateTrackerFpv6.prototype.switchToAnonFootprints=function(){};StateTrackerFpv6.prototype.isAnonymousColor=function(testIdentifier){return testIdentifier==null};StateTrackerFpv6.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this.currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})};return StateTrackerFpv6}(state_tracker_1.StateTracker);exports.StateTrackerFpv6=StateTrackerFpv6})},{"./state-tracker":332}],332:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};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())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};(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-conracts"],factory)}})(function(require,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.StateTracker=void 0;var events=require("events");var sl_env_vars_1=require("./constants/sl-env-vars");var validation_utils_1=require("./utils/validation-utils");var cockpit_notifier_1=require("./agent-events/cockpit-notifier");var agent_events_conracts_1=require("./agent-events/agent-events-conracts");var INITIAL_COLOR="00000000-0000-0000-0000-000000000000/__init";var StateTracker=function(_super){__extends(StateTracker,_super);function StateTracker(cfg,configProcess,checkTestStatusWatchdog,backendProxy,logger){var _this=_super.call(this)||this;_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");_this.cfg=cfg;_this.configProcess=configProcess;_this.checkTestStatusWatchdog=checkTestStatusWatchdog;_this.backendProxy=backendProxy;_this.logger=logger;if(_this.cfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}configProcess.on("configuration_changed",function(newCfg){if(newCfg.useInitialColor.value&&_this.currentTestIdentifier==null){_this.switchToAnonFootprints()}_this.cfg=newCfg;_this.checkTestStatusWatchdog.setInterval(newCfg.executionQueryIntervalSecs.value)});_this.startCheckingTestStatusAtServer();return _this}StateTracker.prototype.startCheckingTestStatusAtServer=function(){var _this=this;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",function(){_this.checkTestStatusAtServer()});if(this.cfg.shouldCheckForActiveExecutionOnStartUp.value){this.checkTestStatusAtServer(false)}};StateTracker.prototype.checkTestStatusAtServer=function(async){var _this=this;if(async===void 0){async=true}if(!this.currentTestIdentifier){this.logger.info("'currentTestIdentifier' is null. That means that footprints will not be sent.")}else{this.backendProxy.testExecutionV4(this.cfg.labId.value,async,this.getExecutionIdForQuery()).then(function(response){_this.fireExecutionEvents(response.execution);_this.notifyCockpit(response.execution);_this._currentExecution=response.execution}).catch(function(err){_this.logger.warn("Error while checking test execution status "+err)})}};StateTracker.prototype.getExecutionIdForQuery=function(){if(this.isAnonymousColor(this.currentTestIdentifier)||!this.currentExecution){return null}return this.currentExecution.executionId};StateTracker.prototype.hasMappingAtServer=function(){return this._currentExecution!=null};StateTracker.prototype.shouldCollectHits=function(){return this.hasMappingAtServer()&&this.currentExecution.executionId!==this.pendingDeleteExecId};Object.defineProperty(StateTracker.prototype,"currentExecution",{get:function(){return this._currentExecution},set:function(value){this._currentExecution=value},enumerable:false,configurable:true});Object.defineProperty(StateTracker.prototype,"openExecutionFoundOnce",{get:function(){return this._openExecutionFoundOnce},enumerable:false,configurable:true});StateTracker.prototype.isAnonymousColor=function(testIdentifier){return INITIAL_COLOR==testIdentifier};StateTracker.prototype.switchToAnonFootprints=function(){this.logger.info("Switching to anonymous footprints.");this.setTestIdentifier(INITIAL_COLOR,false)};StateTracker.prototype.getCurrentTestIdentifier=function(){return this.currentTestIdentifier};StateTracker.prototype.setTestIdentifier=function(newTestIdentifier,silent){this.logger.info("setting test identifier: "+newTestIdentifier);if(this.currentTestIdentifier==null&&newTestIdentifier!=null||this.currentTestIdentifier!=null&&this.currentTestIdentifier!=newTestIdentifier&&newTestIdentifier!=INITIAL_COLOR){var 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+"'")}};StateTracker.prototype.setCurrentTestIdentifier=function(newTestIdentifier){this.setTestIdentifier(newTestIdentifier)};StateTracker.prototype.start=function(){if(!this.isRunning){this.checkTestStatusWatchdog.start();this.isRunning=true}};StateTracker.prototype.stop=function(){try{if(!this.isRunning){return}this.checkTestStatusWatchdog.stop();this.isRunning=false}catch(err){this.logger.error("Error while stopping StateTracker. '"+err+"'");return}};StateTracker.prototype.getTestStage=function(){var _a;return(_a=this.currentExecution)===null||_a===void 0?void 0:_a.testStage};StateTracker.splitTestIdToExecutionAndTestName=function(testId){testId=testId||"";var executionId=testId.split("/")[0];var testName=testId.indexOf("/")==-1?"":testId.substring(executionId.length+1);if(!executionId){testName=""}return{executionId:executionId,testName:testName}};StateTracker.combineExecutionIdAndTestName=function(executionId,testName){testName=testName||"";if(!executionId){return""}return executionId+"/"+testName};StateTracker.prototype.startColoredExecution=function(executionId){return __awaiter(this,void 0,void 0,function(){var request,e_1;return __generator(this,function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);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};return[4,this.backendProxy.startColoredExecution(request)];case 1:_a.sent();this.currentExecution=__assign(__assign({},request),{buildSessionId:this.cfg.buildSessionId.value,status:StateTracker.EXECUTION_STATUS_CREATED});return[3,3];case 2:e_1=_a.sent();this.logger.error("Failed to create execution, error '"+e_1+"'. Footprints will not be sent");return[3,3];case 3:return[2]}})})};StateTracker.prototype.fireExecutionEvents=function(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}};StateTracker.prototype.notifyCockpit=function(execution){if(!execution){cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_NO_EXECUTION)}else{cockpit_notifier_1.CockpitNotifier.sendEventOnce(agent_events_conracts_1.AgentEventCode.FIRST_TIME_HAS_EXECUTION);this._openExecutionFoundOnce=true}};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";return StateTracker}(events.EventEmitter);exports.StateTracker=StateTracker})},{"./agent-events/agent-events-conracts":289,"./agent-events/cockpit-notifier":294,"./constants/sl-env-vars":305,"./utils/validation-utils":337,events:110}],333:[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;var SystemDate=Date;var SystemDateValueOf=Date.prototype.valueOf;function getSystemDate(){return new SystemDate}exports.getSystemDate=getSystemDate;function getSystemDateValueOf(){var date=getSystemDate();return SystemDateValueOf.call(date)}exports.getSystemDateValueOf=getSystemDateValueOf})},{}],334:[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;var EnvVarParsing=function(){function EnvVarParsing(){}EnvVarParsing.parseNumber=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null){var valueAsNumber=Number.parseFloat(valueFromEnv);if(!isNaN(valueAsNumber)){valueFromEnv=valueAsNumber}else{valueFromEnv=null}}return valueFromEnv};EnvVarParsing.parseBoolean=function(key){var valueFromEnv=process.env[key];if(valueFromEnv!=null&&typeof valueFromEnv=="string"){valueFromEnv=valueFromEnv.toLowerCase()}return valueFromEnv=="true"};return EnvVarParsing}();exports.EnvVarParsing=EnvVarParsing})}).call(this)}).call(this,require("_process"))},{_process:179}],335:[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;var path=require("path");var fs=require("fs");var FilesUtils=function(){function FilesUtils(){}FilesUtils.resolveOriginalFullFileName=function(fullPath,originalFilename){if(path.isAbsolute(originalFilename)){return originalFilename}var generatedDir=path.dirname(fullPath);originalFilename=path.resolve(generatedDir,originalFilename);return originalFilename};FilesUtils.prototype.fixPathAndSpecialChar=function(path){if(path){if(path[0]==="/"||path[0]==="\\"){return path.substr(1).split("\\").join("/")}return path.split("\\").join("/")}return path};FilesUtils.adjustPathSlashes=function(filePath){filePath=(filePath||"").replace(/\\/g,"/");return filePath};FilesUtils.findFileUp=function(file,folder){var parsed=path.parse(folder);var filePath=path.join(folder,file);if(fs.existsSync(filePath)){return filePath}if(path.resolve(folder)===parsed.root||folder==="."){return null}var parentFolder=path.join(folder,"..");parentFolder=path.normalize(parentFolder);return FilesUtils.findFileUp(file,parentFolder)};return FilesUtils}();exports.FilesUtils=FilesUtils})},{fs:69,path:171}],336:[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;var TimerUtils=function(){function TimerUtils(){}TimerUtils.sleep=function(timeout){return new Promise(function(resolve){setTimeout(resolve,timeout)})};return TimerUtils}();exports.TimerUtils=TimerUtils})},{}],337:[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;var constants_1=require("../constants/constants");var ValidationUtils=function(){function ValidationUtils(){}ValidationUtils.verifyNotNullOrEmpty=function(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+".")}};return ValidationUtils}();exports.ValidationUtils=ValidationUtils})},{"../constants/constants":304}],338:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();(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;var events=require("events");var WatchdogOptions=function(){function WatchdogOptions(){}return WatchdogOptions}();exports.WatchdogOptions=WatchdogOptions;var Watchdog=function(_super){__extends(Watchdog,_super);function Watchdog(options,timers){var _this=_super.call(this)||this;_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")}return _this}Watchdog.prototype.abort=function(){if(this.handle){this.timers.clearTimeout(this.handle);this.handle=null;this.pendingAlarmDuringSuspended=false}};Watchdog.prototype.reset=function(){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()}}};Watchdog.prototype.stop=function(){this.stopped=true;this.abort()};Watchdog.prototype.start=function(){this.stopped=false;this.reset()};Watchdog.prototype.getStatus=function(){return{pendingAlarmDuringSuspended:this.pendingAlarmDuringSuspended,running:!this.stopped,suspended:this.suspended}};Watchdog.prototype.suspend=function(){this.suspended=true};Watchdog.prototype.resume=function(){this.suspended=false;if(this.pendingAlarmDuringSuspended){this.pendingAlarmDuringSuspended=false;this.fireAlarm()}};Watchdog.prototype.fireAlarm=function(){this.handle=null;if(this.suspended){this.pendingAlarmDuringSuspended=true}else{try{this.emit("alarm",this)}catch(err){}}if(this.options.autoReset){this.reset()}};Watchdog.prototype.setInterval=function(newInterval){if(newInterval<=0)throw new Error("Invalid value for interval: "+newInterval);this.options.interval=newInterval};Watchdog.prototype.getInterval=function(){return this.options.interval};return Watchdog}(events.EventEmitter);exports.Watchdog=Watchdog})},{events:110}],339:[function(require,module,exports){"use strict";var compileSchema=require("./compile"),resolve=require("./compile/resolve"),Cache=require("./cache"),SchemaObject=require("./compile/schema_obj"),stableStringify=require("fast-json-stable-stringify"),formats=require("./compile/formats"),rules=require("./compile/rules"),$dataMetaSchema=require("./data"),util=require("./compile/util");module.exports=Ajv;Ajv.prototype.validate=validate;Ajv.prototype.compile=compile;Ajv.prototype.addSchema=addSchema;Ajv.prototype.addMetaSchema=addMetaSchema;Ajv.prototype.validateSchema=validateSchema;Ajv.prototype.getSchema=getSchema;Ajv.prototype.removeSchema=removeSchema;Ajv.prototype.addFormat=addFormat;Ajv.prototype.errorsText=errorsText;Ajv.prototype._addSchema=_addSchema;Ajv.prototype._compile=_compile;Ajv.prototype.compileAsync=require("./compile/async");var customKeyword=require("./keyword");Ajv.prototype.addKeyword=customKeyword.add;Ajv.prototype.getKeyword=customKeyword.get;Ajv.prototype.removeKeyword=customKeyword.remove;Ajv.prototype.validateKeyword=customKeyword.validate;var errorClasses=require("./compile/error_classes");Ajv.ValidationError=errorClasses.Validation;Ajv.MissingRefError=errorClasses.MissingRef;Ajv.$dataMetaSchema=$dataMetaSchema;var META_SCHEMA_ID="http://json-schema.org/draft-07/schema";var META_IGNORE_OPTIONS=["removeAdditional","useDefaults","coerceTypes","strictDefaults"];var META_SUPPORT_DATA=["/properties"];function Ajv(opts){if(!(this instanceof Ajv))return new Ajv(opts);opts=this._opts=util.copy(opts)||{};setLogger(this);this._schemas={};this._refs={};this._fragments={};this._formats=formats(opts.format);this._cache=opts.cache||new Cache;this._loadingSchemas={};this._compilations=[];this.RULES=rules();this._getId=chooseGetId(opts);opts.loopRequired=opts.loopRequired||Infinity;if(opts.errorDataPath=="property")opts._errorDataPathProperty=true;if(opts.serialize===undefined)opts.serialize=stableStringify;this._metaOpts=getMetaSchemaOptions(this);if(opts.formats)addInitialFormats(this);if(opts.keywords)addInitialKeywords(this);addDefaultMetaSchema(this);if(typeof opts.meta=="object")this.addMetaSchema(opts.meta);if(opts.nullable)this.addKeyword("nullable",{metaSchema:{type:"boolean"}});addInitialSchemas(this)}function validate(schemaKeyRef,data){var v;if(typeof schemaKeyRef=="string"){v=this.getSchema(schemaKeyRef);if(!v)throw new Error('no schema with key or ref "'+schemaKeyRef+'"')}else{var schemaObj=this._addSchema(schemaKeyRef);v=schemaObj.validate||this._compile(schemaObj)}var valid=v(data);if(v.$async!==true)this.errors=v.errors;return valid}function compile(schema,_meta){var schemaObj=this._addSchema(schema,undefined,_meta);return schemaObj.validate||this._compile(schemaObj)}function addSchema(schema,key,_skipValidation,_meta){if(Array.isArray(schema)){for(var i=0;i<schema.length;i++)this.addSchema(schema[i],undefined,_skipValidation,_meta);return this}var id=this._getId(schema);if(id!==undefined&&typeof id!="string")throw new Error("schema id must be string");key=resolve.normalizeId(key||id);checkUnique(this,key);this._schemas[key]=this._addSchema(schema,_skipValidation,_meta,true);return this}function addMetaSchema(schema,key,skipValidation){this.addSchema(schema,key,skipValidation,true);return this}function validateSchema(schema,throwOrLogError){var $schema=schema.$schema;if($schema!==undefined&&typeof $schema!="string")throw new Error("$schema must be a string");$schema=$schema||this._opts.defaultMeta||defaultMeta(this);if(!$schema){this.logger.warn("meta-schema not available");this.errors=null;return true}var valid=this.validate($schema,schema);if(!valid&&throwOrLogError){var message="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(message);else throw new Error(message)}return valid}function defaultMeta(self){var meta=self._opts.meta;self._opts.defaultMeta=typeof meta=="object"?self._getId(meta)||meta:self.getSchema(META_SCHEMA_ID)?META_SCHEMA_ID:undefined;return self._opts.defaultMeta}function getSchema(keyRef){var schemaObj=_getSchemaObj(this,keyRef);switch(typeof schemaObj){case"object":return schemaObj.validate||this._compile(schemaObj);case"string":return this.getSchema(schemaObj);case"undefined":return _getSchemaFragment(this,keyRef)}}function _getSchemaFragment(self,ref){var res=resolve.schema.call(self,{schema:{}},ref);if(res){var schema=res.schema,root=res.root,baseId=res.baseId;var v=compileSchema.call(self,schema,root,undefined,baseId);self._fragments[ref]=new SchemaObject({ref:ref,fragment:true,schema:schema,root:root,baseId:baseId,validate:v});return v}}function _getSchemaObj(self,keyRef){keyRef=resolve.normalizeId(keyRef);return self._schemas[keyRef]||self._refs[keyRef]||self._fragments[keyRef]}function removeSchema(schemaKeyRef){if(schemaKeyRef instanceof RegExp){_removeAllSchemas(this,this._schemas,schemaKeyRef);_removeAllSchemas(this,this._refs,schemaKeyRef);return this}switch(typeof schemaKeyRef){case"undefined":_removeAllSchemas(this,this._schemas);_removeAllSchemas(this,this._refs);this._cache.clear();return this;case"string":var schemaObj=_getSchemaObj(this,schemaKeyRef);if(schemaObj)this._cache.del(schemaObj.cacheKey);delete this._schemas[schemaKeyRef];delete this._refs[schemaKeyRef];return this;case"object":var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schemaKeyRef):schemaKeyRef;this._cache.del(cacheKey);var id=this._getId(schemaKeyRef);if(id){id=resolve.normalizeId(id);delete this._schemas[id];delete this._refs[id]}}return this}function _removeAllSchemas(self,schemas,regex){for(var keyRef in schemas){var schemaObj=schemas[keyRef];if(!schemaObj.meta&&(!regex||regex.test(keyRef))){self._cache.del(schemaObj.cacheKey);delete schemas[keyRef]}}}function _addSchema(schema,skipValidation,meta,shouldAddSchema){if(typeof schema!="object"&&typeof schema!="boolean")throw new Error("schema should be object or boolean");var serialize=this._opts.serialize;var cacheKey=serialize?serialize(schema):schema;var cached=this._cache.get(cacheKey);if(cached)return cached;shouldAddSchema=shouldAddSchema||this._opts.addUsedSchema!==false;var id=resolve.normalizeId(this._getId(schema));if(id&&shouldAddSchema)checkUnique(this,id);var willValidate=this._opts.validateSchema!==false&&!skipValidation;var recursiveMeta;if(willValidate&&!(recursiveMeta=id&&id==resolve.normalizeId(schema.$schema)))this.validateSchema(schema,true);var localRefs=resolve.ids.call(this,schema);var schemaObj=new SchemaObject({id:id,schema:schema,localRefs:localRefs,cacheKey:cacheKey,meta:meta});if(id[0]!="#"&&shouldAddSchema)this._refs[id]=schemaObj;this._cache.put(cacheKey,schemaObj);if(willValidate&&recursiveMeta)this.validateSchema(schema,true);return schemaObj}function _compile(schemaObj,root){if(schemaObj.compiling){schemaObj.validate=callValidate;callValidate.schema=schemaObj.schema;callValidate.errors=null;callValidate.root=root?root:callValidate;if(schemaObj.schema.$async===true)callValidate.$async=true;return callValidate}schemaObj.compiling=true;var currentOpts;if(schemaObj.meta){currentOpts=this._opts;this._opts=this._metaOpts}var v;try{v=compileSchema.call(this,schemaObj.schema,root,schemaObj.localRefs)}catch(e){delete schemaObj.validate;throw e}finally{schemaObj.compiling=false;if(schemaObj.meta)this._opts=currentOpts}schemaObj.validate=v;schemaObj.refs=v.refs;schemaObj.refVal=v.refVal;schemaObj.root=v.root;return v;function callValidate(){var _validate=schemaObj.validate;var result=_validate.apply(this,arguments);callValidate.errors=_validate.errors;return result}}function chooseGetId(opts){switch(opts.schemaId){case"auto":return _get$IdOrId;case"id":return _getId;default:return _get$Id}}function _getId(schema){if(schema.$id)this.logger.warn("schema $id ignored",schema.$id);return schema.id}function _get$Id(schema){if(schema.id)this.logger.warn("schema id ignored",schema.id);return schema.$id}function _get$IdOrId(schema){if(schema.$id&&schema.id&&schema.$id!=schema.id)throw new Error("schema $id is different from id");return schema.$id||schema.id}function errorsText(errors,options){errors=errors||this.errors;if(!errors)return"No errors";options=options||{};var separator=options.separator===undefined?", ":options.separator;var dataVar=options.dataVar===undefined?"data":options.dataVar;var text="";for(var i=0;i<errors.length;i++){var e=errors[i];if(e)text+=dataVar+e.dataPath+" "+e.message+separator}return text.slice(0,-separator.length)}function addFormat(name,format){
|
|
34
34
|
if(typeof format=="string")format=new RegExp(format);this._formats[name]=format;return this}function addDefaultMetaSchema(self){var $dataSchema;if(self._opts.$data){$dataSchema=require("./refs/data.json");self.addMetaSchema($dataSchema,$dataSchema.$id,true)}if(self._opts.meta===false)return;var metaSchema=require("./refs/json-schema-draft-07.json");if(self._opts.$data)metaSchema=$dataMetaSchema(metaSchema,META_SUPPORT_DATA);self.addMetaSchema(metaSchema,META_SCHEMA_ID,true);self._refs["http://json-schema.org/schema"]=META_SCHEMA_ID}function addInitialSchemas(self){var optsSchemas=self._opts.schemas;if(!optsSchemas)return;if(Array.isArray(optsSchemas))self.addSchema(optsSchemas);else for(var key in optsSchemas)self.addSchema(optsSchemas[key],key)}function addInitialFormats(self){for(var name in self._opts.formats){var format=self._opts.formats[name];self.addFormat(name,format)}}function addInitialKeywords(self){for(var name in self._opts.keywords){var keyword=self._opts.keywords[name];self.addKeyword(name,keyword)}}function checkUnique(self,id){if(self._schemas[id]||self._refs[id])throw new Error('schema with key or id "'+id+'" already exists')}function getMetaSchemaOptions(self){var metaOpts=util.copy(self._opts);for(var i=0;i<META_IGNORE_OPTIONS.length;i++)delete metaOpts[META_IGNORE_OPTIONS[i]];return metaOpts}function setLogger(self){var logger=self._opts.logger;if(logger===false){self.logger={log:noop,warn:noop,error:noop}}else{if(logger===undefined)logger=console;if(!(typeof logger=="object"&&logger.log&&logger.warn&&logger.error))throw new Error("logger must implement log, warn and error methods");self.logger=logger}}function noop(){}},{"./cache":340,"./compile":344,"./compile/async":341,"./compile/error_classes":342,"./compile/formats":343,"./compile/resolve":345,"./compile/rules":346,"./compile/schema_obj":347,"./compile/util":349,"./data":350,"./keyword":378,"./refs/data.json":379,"./refs/json-schema-draft-07.json":381,"fast-json-stable-stringify":403}],340:[function(require,module,exports){"use strict";var Cache=module.exports=function Cache(){this._cache={}};Cache.prototype.put=function Cache_put(key,value){this._cache[key]=value};Cache.prototype.get=function Cache_get(key){return this._cache[key]};Cache.prototype.del=function Cache_del(key){delete this._cache[key]};Cache.prototype.clear=function Cache_clear(){this._cache={}}},{}],341:[function(require,module,exports){"use strict";var MissingRefError=require("./error_classes").MissingRef;module.exports=compileAsync;function compileAsync(schema,meta,callback){var self=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");if(typeof meta=="function"){callback=meta;meta=undefined}var p=loadMetaSchemaOf(schema).then(function(){var schemaObj=self._addSchema(schema,undefined,meta);return schemaObj.validate||_compileAsync(schemaObj)});if(callback){p.then(function(v){callback(null,v)},callback)}return p;function loadMetaSchemaOf(sch){var $schema=sch.$schema;return $schema&&!self.getSchema($schema)?compileAsync.call(self,{$ref:$schema},true):Promise.resolve()}function _compileAsync(schemaObj){try{return self._compile(schemaObj)}catch(e){if(e instanceof MissingRefError)return loadMissingSchema(e);throw e}function loadMissingSchema(e){var ref=e.missingSchema;if(added(ref))throw new Error("Schema "+ref+" is loaded but "+e.missingRef+" cannot be resolved");var schemaPromise=self._loadingSchemas[ref];if(!schemaPromise){schemaPromise=self._loadingSchemas[ref]=self._opts.loadSchema(ref);schemaPromise.then(removePromise,removePromise)}return schemaPromise.then(function(sch){if(!added(ref)){return loadMetaSchemaOf(sch).then(function(){if(!added(ref))self.addSchema(sch,ref,undefined,meta)})}}).then(function(){return _compileAsync(schemaObj)});function removePromise(){delete self._loadingSchemas[ref]}function added(ref){return self._refs[ref]||self._schemas[ref]}}}}},{"./error_classes":342}],342:[function(require,module,exports){"use strict";var resolve=require("./resolve");module.exports={Validation:errorSubclass(ValidationError),MissingRef:errorSubclass(MissingRefError)};function ValidationError(errors){this.message="validation failed";this.errors=errors;this.ajv=this.validation=true}MissingRefError.message=function(baseId,ref){return"can't resolve reference "+ref+" from id "+baseId};function MissingRefError(baseId,ref,message){this.message=message||MissingRefError.message(baseId,ref);this.missingRef=resolve.url(baseId,ref);this.missingSchema=resolve.normalizeId(resolve.fullPath(this.missingRef))}function errorSubclass(Subclass){Subclass.prototype=Object.create(Error.prototype);Subclass.prototype.constructor=Subclass;return Subclass}},{"./resolve":345}],343:[function(require,module,exports){"use strict";var util=require("./util");var DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;var DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31];var TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;var HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;var URI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;var URIREF=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;var URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#.\/;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;var URL=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;var UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var JSON_POINTER=/^(?:\/(?:[^~\/]|~0|~1)*)*$/;var JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;var RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;module.exports=formats;function formats(mode){mode=mode=="full"?"full":"fast";return util.copy(formats[mode])}formats.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":URITEMPLATE,url:URL,email:/^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};formats.full={date:date,time:time,"date-time":date_time,uri:uri,"uri-reference":URIREF,"uri-template":URITEMPLATE,url:URL,email:/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:HOSTNAME,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:regex,uuid:UUID,"json-pointer":JSON_POINTER,"json-pointer-uri-fragment":JSON_POINTER_URI_FRAGMENT,"relative-json-pointer":RELATIVE_JSON_POINTER};function isLeapYear(year){return year%4===0&&(year%100!==0||year%400===0)}function date(str){var matches=str.match(DATE);if(!matches)return false;var year=+matches[1];var month=+matches[2];var day=+matches[3];return month>=1&&month<=12&&day>=1&&day<=(month==2&&isLeapYear(year)?29:DAYS[month])}function time(str,full){var matches=str.match(TIME);if(!matches)return false;var hour=matches[1];var minute=matches[2];var second=matches[3];var timeZone=matches[5];return(hour<=23&&minute<=59&&second<=59||hour==23&&minute==59&&second==60)&&(!full||timeZone)}var DATE_TIME_SEPARATOR=/t|\s/i;function date_time(str){var dateTime=str.split(DATE_TIME_SEPARATOR);return dateTime.length==2&&date(dateTime[0])&&time(dateTime[1],true)}var NOT_URI_FRAGMENT=/\/|:/;function uri(str){return NOT_URI_FRAGMENT.test(str)&&URI.test(str)}var Z_ANCHOR=/[^\\]\\Z/;function regex(str){if(Z_ANCHOR.test(str))return false;try{new RegExp(str);return true}catch(e){return false}}},{"./util":349}],344:[function(require,module,exports){"use strict";var resolve=require("./resolve"),util=require("./util"),errorClasses=require("./error_classes"),stableStringify=require("fast-json-stable-stringify");var validateGenerator=require("../dotjs/validate");var ucs2length=util.ucs2length;var equal=require("fast-deep-equal");var ValidationError=errorClasses.Validation;module.exports=compile;function compile(schema,root,localRefs,baseId){var self=this,opts=this._opts,refVal=[undefined],refs={},patterns=[],patternsHash={},defaults=[],defaultsHash={},customRules=[];root=root||{schema:schema,refVal:refVal,refs:refs};var c=checkCompiling.call(this,schema,root,baseId);var compilation=this._compilations[c.index];if(c.compiling)return compilation.callValidate=callValidate;var formats=this._formats;var RULES=this.RULES;try{var v=localCompile(schema,root,localRefs,baseId);compilation.validate=v;var cv=compilation.callValidate;if(cv){cv.schema=v.schema;cv.errors=null;cv.refs=v.refs;cv.refVal=v.refVal;cv.root=v.root;cv.$async=v.$async;if(opts.sourceCode)cv.source=v.source}return v}finally{endCompiling.call(this,schema,root,baseId)}function callValidate(){var validate=compilation.validate;var result=validate.apply(this,arguments);callValidate.errors=validate.errors;return result}function localCompile(_schema,_root,localRefs,baseId){var isRoot=!_root||_root&&_root.schema==_schema;if(_root.schema!=root.schema)return compile.call(self,_schema,_root,localRefs,baseId);var $async=_schema.$async===true;var sourceCode=validateGenerator({isTop:true,schema:_schema,isRoot:isRoot,baseId:baseId,root:_root,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:errorClasses.MissingRef,RULES:RULES,validate:validateGenerator,util:util,resolve:resolve,resolveRef:resolveRef,usePattern:usePattern,useDefault:useDefault,useCustomRule:useCustomRule,opts:opts,formats:formats,logger:self.logger,self:self});sourceCode=vars(refVal,refValCode)+vars(patterns,patternCode)+vars(defaults,defaultCode)+vars(customRules,customRuleCode)+sourceCode;if(opts.processCode)sourceCode=opts.processCode(sourceCode,_schema);var validate;try{var makeValidate=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",sourceCode);validate=makeValidate(self,RULES,formats,root,refVal,defaults,customRules,equal,ucs2length,ValidationError);refVal[0]=validate}catch(e){self.logger.error("Error compiling schema, function code:",sourceCode);throw e}validate.schema=_schema;validate.errors=null;validate.refs=refs;validate.refVal=refVal;validate.root=isRoot?validate:_root;if($async)validate.$async=true;if(opts.sourceCode===true){validate.source={code:sourceCode,patterns:patterns,defaults:defaults}}return validate}function resolveRef(baseId,ref,isRoot){ref=resolve.url(baseId,ref);var refIndex=refs[ref];var _refVal,refCode;if(refIndex!==undefined){_refVal=refVal[refIndex];refCode="refVal["+refIndex+"]";return resolvedRef(_refVal,refCode)}if(!isRoot&&root.refs){var rootRefId=root.refs[ref];if(rootRefId!==undefined){_refVal=root.refVal[rootRefId];refCode=addLocalRef(ref,_refVal);return resolvedRef(_refVal,refCode)}}refCode=addLocalRef(ref);var v=resolve.call(self,localCompile,root,ref);if(v===undefined){var localSchema=localRefs&&localRefs[ref];if(localSchema){v=resolve.inlineRef(localSchema,opts.inlineRefs)?localSchema:compile.call(self,localSchema,root,localRefs,baseId)}}if(v===undefined){removeLocalRef(ref)}else{replaceLocalRef(ref,v);return resolvedRef(v,refCode)}}function addLocalRef(ref,v){var refId=refVal.length;refVal[refId]=v;refs[ref]=refId;return"refVal"+refId}function removeLocalRef(ref){delete refs[ref]}function replaceLocalRef(ref,v){var refId=refs[ref];refVal[refId]=v}function resolvedRef(refVal,code){return typeof refVal=="object"||typeof refVal=="boolean"?{code:code,schema:refVal,inline:true}:{code:code,$async:refVal&&!!refVal.$async}}function usePattern(regexStr){var index=patternsHash[regexStr];if(index===undefined){index=patternsHash[regexStr]=patterns.length;patterns[index]=regexStr}return"pattern"+index}function useDefault(value){switch(typeof value){case"boolean":case"number":return""+value;case"string":return util.toQuotedString(value);case"object":if(value===null)return"null";var valueStr=stableStringify(value);var index=defaultsHash[valueStr];if(index===undefined){index=defaultsHash[valueStr]=defaults.length;defaults[index]=value}return"default"+index}}function useCustomRule(rule,schema,parentSchema,it){if(self._opts.validateSchema!==false){var deps=rule.definition.dependencies;if(deps&&!deps.every(function(keyword){return Object.prototype.hasOwnProperty.call(parentSchema,keyword)}))throw new Error("parent schema must have all required keywords: "+deps.join(","));var validateSchema=rule.definition.validateSchema;if(validateSchema){var valid=validateSchema(schema);if(!valid){var message="keyword schema is invalid: "+self.errorsText(validateSchema.errors);if(self._opts.validateSchema=="log")self.logger.error(message);else throw new Error(message)}}}var compile=rule.definition.compile,inline=rule.definition.inline,macro=rule.definition.macro;var validate;if(compile){validate=compile.call(self,schema,parentSchema,it)}else if(macro){validate=macro.call(self,schema,parentSchema,it);if(opts.validateSchema!==false)self.validateSchema(validate,true)}else if(inline){validate=inline.call(self,it,rule.keyword,schema,parentSchema)}else{validate=rule.definition.validate;if(!validate)return}if(validate===undefined)throw new Error('custom keyword "'+rule.keyword+'"failed to compile');var index=customRules.length;customRules[index]=validate;return{code:"customRule"+index,validate:validate}}}function checkCompiling(schema,root,baseId){var index=compIndex.call(this,schema,root,baseId);if(index>=0)return{index:index,compiling:true};index=this._compilations.length;this._compilations[index]={schema:schema,root:root,baseId:baseId};return{index:index,compiling:false}}function endCompiling(schema,root,baseId){var i=compIndex.call(this,schema,root,baseId);if(i>=0)this._compilations.splice(i,1)}function compIndex(schema,root,baseId){for(var i=0;i<this._compilations.length;i++){var c=this._compilations[i];if(c.schema==schema&&c.root==root&&c.baseId==baseId)return i}return-1}function patternCode(i,patterns){return"var pattern"+i+" = new RegExp("+util.toQuotedString(patterns[i])+");"}function defaultCode(i){return"var default"+i+" = defaults["+i+"];"}function refValCode(i,refVal){return refVal[i]===undefined?"":"var refVal"+i+" = refVal["+i+"];"}function customRuleCode(i){return"var customRule"+i+" = customRules["+i+"];"}function vars(arr,statement){if(!arr.length)return"";var code="";for(var i=0;i<arr.length;i++)code+=statement(i,arr);return code}},{"../dotjs/validate":377,"./error_classes":342,"./resolve":345,"./util":349,"fast-deep-equal":402,"fast-json-stable-stringify":403}],345:[function(require,module,exports){"use strict";var URI=require("uri-js"),equal=require("fast-deep-equal"),util=require("./util"),SchemaObject=require("./schema_obj"),traverse=require("json-schema-traverse");module.exports=resolve;resolve.normalizeId=normalizeId;resolve.fullPath=getFullPath;resolve.url=resolveUrl;resolve.ids=resolveIds;resolve.inlineRef=inlineRef;resolve.schema=resolveSchema;function resolve(compile,root,ref){var refVal=this._refs[ref];if(typeof refVal=="string"){if(this._refs[refVal])refVal=this._refs[refVal];else return resolve.call(this,compile,root,refVal)}refVal=refVal||this._schemas[ref];if(refVal instanceof SchemaObject){return inlineRef(refVal.schema,this._opts.inlineRefs)?refVal.schema:refVal.validate||this._compile(refVal)}var res=resolveSchema.call(this,root,ref);var schema,v,baseId;if(res){schema=res.schema;root=res.root;baseId=res.baseId}if(schema instanceof SchemaObject){v=schema.validate||compile.call(this,schema.schema,root,undefined,baseId)}else if(schema!==undefined){v=inlineRef(schema,this._opts.inlineRefs)?schema:compile.call(this,schema,root,undefined,baseId)}return v}function resolveSchema(root,ref){var p=URI.parse(ref),refPath=_getFullPath(p),baseId=getFullPath(this._getId(root.schema));if(Object.keys(root.schema).length===0||refPath!==baseId){var id=normalizeId(refPath);var refVal=this._refs[id];if(typeof refVal=="string"){return resolveRecursive.call(this,root,refVal,p)}else if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);root=refVal}else{refVal=this._schemas[id];if(refVal instanceof SchemaObject){if(!refVal.validate)this._compile(refVal);if(id==normalizeId(ref))return{schema:refVal,root:root,baseId:baseId};root=refVal}else{return}}if(!root.schema)return;baseId=getFullPath(this._getId(root.schema))}return getJsonPointer.call(this,p,baseId,root.schema,root)}function resolveRecursive(root,ref,parsedRef){var res=resolveSchema.call(this,root,ref);if(res){var schema=res.schema;var baseId=res.baseId;root=res.root;var id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);return getJsonPointer.call(this,parsedRef,baseId,schema,root)}}var PREVENT_SCOPE_CHANGE=util.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function getJsonPointer(parsedRef,baseId,schema,root){parsedRef.fragment=parsedRef.fragment||"";if(parsedRef.fragment.slice(0,1)!="/")return;var parts=parsedRef.fragment.split("/");for(var i=1;i<parts.length;i++){var part=parts[i];if(part){part=util.unescapeFragment(part);schema=schema[part];if(schema===undefined)break;var id;if(!PREVENT_SCOPE_CHANGE[part]){id=this._getId(schema);if(id)baseId=resolveUrl(baseId,id);if(schema.$ref){var $ref=resolveUrl(baseId,schema.$ref);var res=resolveSchema.call(this,root,$ref);if(res){schema=res.schema;root=res.root;baseId=res.baseId}}}}}if(schema!==undefined&&schema!==root.schema)return{schema:schema,root:root,baseId:baseId}}var SIMPLE_INLINED=util.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function inlineRef(schema,limit){if(limit===false)return false;if(limit===undefined||limit===true)return checkNoRef(schema);else if(limit)return countKeys(schema)<=limit}function checkNoRef(schema){var item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object"&&!checkNoRef(item))return false}}else{for(var key in schema){if(key=="$ref")return false;item=schema[key];if(typeof item=="object"&&!checkNoRef(item))return false}}return true}function countKeys(schema){var count=0,item;if(Array.isArray(schema)){for(var i=0;i<schema.length;i++){item=schema[i];if(typeof item=="object")count+=countKeys(item);if(count==Infinity)return Infinity}}else{for(var key in schema){if(key=="$ref")return Infinity;if(SIMPLE_INLINED[key]){count++}else{item=schema[key];if(typeof item=="object")count+=countKeys(item)+1;if(count==Infinity)return Infinity}}}return count}function getFullPath(id,normalize){if(normalize!==false)id=normalizeId(id);var p=URI.parse(id);return _getFullPath(p)}function _getFullPath(p){return URI.serialize(p).split("#")[0]+"#"}var TRAILING_SLASH_HASH=/#\/?$/;function normalizeId(id){return id?id.replace(TRAILING_SLASH_HASH,""):""}function resolveUrl(baseId,id){id=normalizeId(id);return URI.resolve(baseId,id)}function resolveIds(schema){var schemaId=normalizeId(this._getId(schema));var baseIds={"":schemaId};var fullPaths={"":getFullPath(schemaId,false)};var localRefs={};var self=this;traverse(schema,{allKeys:true},function(sch,jsonPtr,rootSchema,parentJsonPtr,parentKeyword,parentSchema,keyIndex){if(jsonPtr==="")return;var id=self._getId(sch);var baseId=baseIds[parentJsonPtr];var fullPath=fullPaths[parentJsonPtr]+"/"+parentKeyword;if(keyIndex!==undefined)fullPath+="/"+(typeof keyIndex=="number"?keyIndex:util.escapeFragment(keyIndex));if(typeof id=="string"){id=baseId=normalizeId(baseId?URI.resolve(baseId,id):id);var refVal=self._refs[id];if(typeof refVal=="string")refVal=self._refs[refVal];if(refVal&&refVal.schema){if(!equal(sch,refVal.schema))throw new Error('id "'+id+'" resolves to more than one schema')}else if(id!=normalizeId(fullPath)){if(id[0]=="#"){if(localRefs[id]&&!equal(sch,localRefs[id]))throw new Error('id "'+id+'" resolves to more than one schema');localRefs[id]=sch}else{self._refs[id]=fullPath}}}baseIds[jsonPtr]=baseId;fullPaths[jsonPtr]=fullPath});return localRefs}},{"./schema_obj":347,"./util":349,"fast-deep-equal":402,"json-schema-traverse":435,"uri-js":506}],346:[function(require,module,exports){"use strict";var ruleModules=require("../dotjs"),toHash=require("./util").toHash;module.exports=function rules(){var RULES=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}];var ALL=["type","$comment"];var KEYWORDS=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"];var TYPES=["number","integer","string","array","object","boolean","null"];RULES.all=toHash(ALL);RULES.types=toHash(TYPES);RULES.forEach(function(group){group.rules=group.rules.map(function(keyword){var implKeywords;if(typeof keyword=="object"){var key=Object.keys(keyword)[0];implKeywords=keyword[key];keyword=key;implKeywords.forEach(function(k){ALL.push(k);RULES.all[k]=true})}ALL.push(keyword);var rule=RULES.all[keyword]={keyword:keyword,code:ruleModules[keyword],implements:implKeywords};return rule});RULES.all.$comment={keyword:"$comment",code:ruleModules.$comment};if(group.type)RULES.types[group.type]=group});RULES.keywords=toHash(ALL.concat(KEYWORDS));RULES.custom={};return RULES}},{"../dotjs":366,"./util":349}],347:[function(require,module,exports){"use strict";var util=require("./util");module.exports=SchemaObject;function SchemaObject(obj){util.copy(obj,this)}},{"./util":349}],348:[function(require,module,exports){"use strict";module.exports=function ucs2length(str){var length=0,len=str.length,pos=0,value;while(pos<len){length++;value=str.charCodeAt(pos++);if(value>=55296&&value<=56319&&pos<len){value=str.charCodeAt(pos);if((value&64512)==56320)pos++}}return length}},{}],349:[function(require,module,exports){"use strict";module.exports={copy:copy,checkDataType:checkDataType,checkDataTypes:checkDataTypes,coerceToTypes:coerceToTypes,toHash:toHash,getProperty:getProperty,escapeQuotes:escapeQuotes,equal:require("fast-deep-equal"),ucs2length:require("./ucs2length"),varOccurences:varOccurences,varReplace:varReplace,schemaHasRules:schemaHasRules,schemaHasRulesExcept:schemaHasRulesExcept,schemaUnknownRules:schemaUnknownRules,toQuotedString:toQuotedString,getPathExpr:getPathExpr,getPath:getPath,getData:getData,unescapeFragment:unescapeFragment,unescapeJsonPointer:unescapeJsonPointer,escapeFragment:escapeFragment,escapeJsonPointer:escapeJsonPointer};function copy(o,to){to=to||{};for(var key in o)to[key]=o[key];return to}function checkDataType(dataType,data,strictNumbers,negate){var EQUAL=negate?" !== ":" === ",AND=negate?" || ":" && ",OK=negate?"!":"",NOT=negate?"":"!";switch(dataType){case"null":return data+EQUAL+"null";case"array":return OK+"Array.isArray("+data+")";case"object":return"("+OK+data+AND+"typeof "+data+EQUAL+'"object"'+AND+NOT+"Array.isArray("+data+"))";case"integer":return"(typeof "+data+EQUAL+'"number"'+AND+NOT+"("+data+" % 1)"+AND+data+EQUAL+data+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";case"number":return"(typeof "+data+EQUAL+'"'+dataType+'"'+(strictNumbers?AND+OK+"isFinite("+data+")":"")+")";default:return"typeof "+data+EQUAL+'"'+dataType+'"'}}function checkDataTypes(dataTypes,data,strictNumbers){switch(dataTypes.length){case 1:return checkDataType(dataTypes[0],data,strictNumbers,true);default:var code="";var types=toHash(dataTypes);if(types.array&&types.object){code=types.null?"(":"(!"+data+" || ";code+="typeof "+data+' !== "object")';delete types.null;delete types.array;delete types.object}if(types.number)delete types.integer;for(var t in types)code+=(code?" && ":"")+checkDataType(t,data,strictNumbers,true);return code}}var COERCE_TO_TYPES=toHash(["string","number","integer","boolean","null"]);function coerceToTypes(optionCoerceTypes,dataTypes){if(Array.isArray(dataTypes)){var types=[];for(var i=0;i<dataTypes.length;i++){var t=dataTypes[i];if(COERCE_TO_TYPES[t])types[types.length]=t;else if(optionCoerceTypes==="array"&&t==="array")types[types.length]=t}if(types.length)return types}else if(COERCE_TO_TYPES[dataTypes]){return[dataTypes]}else if(optionCoerceTypes==="array"&&dataTypes==="array"){return["array"]}}function toHash(arr){var hash={};for(var i=0;i<arr.length;i++)hash[arr[i]]=true;return hash}var IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var SINGLE_QUOTE=/'|\\/g;function getProperty(key){return typeof key=="number"?"["+key+"]":IDENTIFIER.test(key)?"."+key:"['"+escapeQuotes(key)+"']"}function escapeQuotes(str){return str.replace(SINGLE_QUOTE,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function varOccurences(str,dataVar){dataVar+="[^0-9]";var matches=str.match(new RegExp(dataVar,"g"));return matches?matches.length:0}function varReplace(str,dataVar,expr){dataVar+="([^0-9])";expr=expr.replace(/\$/g,"$$$$")
|
|
35
35
|
;return str.replace(new RegExp(dataVar,"g"),expr+"$1")}function schemaHasRules(schema,rules){if(typeof schema=="boolean")return!schema;for(var key in schema)if(rules[key])return true}function schemaHasRulesExcept(schema,rules,exceptKeyword){if(typeof schema=="boolean")return!schema&&exceptKeyword!="not";for(var key in schema)if(key!=exceptKeyword&&rules[key])return true}function schemaUnknownRules(schema,rules){if(typeof schema=="boolean")return;for(var key in schema)if(!rules[key])return key}function toQuotedString(str){return"'"+escapeQuotes(str)+"'"}function getPathExpr(currentPath,expr,jsonPointers,isNumber){var path=jsonPointers?"'/' + "+expr+(isNumber?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):isNumber?"'[' + "+expr+" + ']'":"'[\\'' + "+expr+" + '\\']'";return joinPaths(currentPath,path)}function getPath(currentPath,prop,jsonPointers){var path=jsonPointers?toQuotedString("/"+escapeJsonPointer(prop)):toQuotedString(getProperty(prop));return joinPaths(currentPath,path)}var JSON_POINTER=/^\/(?:[^~]|~0|~1)*$/;var RELATIVE_JSON_POINTER=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function getData($data,lvl,paths){var up,jsonPointer,data,matches;if($data==="")return"rootData";if($data[0]=="/"){if(!JSON_POINTER.test($data))throw new Error("Invalid JSON-pointer: "+$data);jsonPointer=$data;data="rootData"}else{matches=$data.match(RELATIVE_JSON_POINTER);if(!matches)throw new Error("Invalid JSON-pointer: "+$data);up=+matches[1];jsonPointer=matches[2];if(jsonPointer=="#"){if(up>=lvl)throw new Error("Cannot access property/index "+up+" levels up, current level is "+lvl);return paths[lvl-up]}if(up>lvl)throw new Error("Cannot access data "+up+" levels up, current level is "+lvl);data="data"+(lvl-up||"");if(!jsonPointer)return data}var expr=data;var segments=jsonPointer.split("/");for(var i=0;i<segments.length;i++){var segment=segments[i];if(segment){data+=getProperty(unescapeJsonPointer(segment));expr+=" && "+data}}return expr}function joinPaths(a,b){if(a=='""')return b;return(a+" + "+b).replace(/([^\\])' \+ '/g,"$1")}function unescapeFragment(str){return unescapeJsonPointer(decodeURIComponent(str))}function escapeFragment(str){return encodeURIComponent(escapeJsonPointer(str))}function escapeJsonPointer(str){return str.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeJsonPointer(str){return str.replace(/~1/g,"/").replace(/~0/g,"~")}},{"./ucs2length":348,"fast-deep-equal":402}],350:[function(require,module,exports){"use strict";var KEYWORDS=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];module.exports=function(metaSchema,keywordsJsonPointers){for(var i=0;i<keywordsJsonPointers.length;i++){metaSchema=JSON.parse(JSON.stringify(metaSchema));var segments=keywordsJsonPointers[i].split("/");var keywords=metaSchema;var j;for(j=1;j<segments.length;j++)keywords=keywords[segments[j]];for(j=0;j<KEYWORDS.length;j++){var key=KEYWORDS[j];var schema=keywords[key];if(schema){keywords[key]={anyOf:[schema,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}}}}return metaSchema}},{}],351:[function(require,module,exports){"use strict";var metaSchema=require("./refs/json-schema-draft-07.json");module.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:metaSchema.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:metaSchema.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},{"./refs/json-schema-draft-07.json":381}],352:[function(require,module,exports){"use strict";module.exports=function generate__limit(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $isMax=$keyword=="maximum",$exclusiveKeyword=$isMax?"exclusiveMaximum":"exclusiveMinimum",$schemaExcl=it.schema[$exclusiveKeyword],$isDataExcl=it.opts.$data&&$schemaExcl&&$schemaExcl.$data,$op=$isMax?"<":">",$notOp=$isMax?">":"<",$errorKeyword=undefined;if(!($isData||typeof $schema=="number"||$schema===undefined)){throw new Error($keyword+" must be number")}if(!($isDataExcl||$schemaExcl===undefined||typeof $schemaExcl=="number"||typeof $schemaExcl=="boolean")){throw new Error($exclusiveKeyword+" must be number or boolean")}if($isDataExcl){var $schemaValueExcl=it.util.getData($schemaExcl.$data,$dataLvl,it.dataPathArr),$exclusive="exclusive"+$lvl,$exclType="exclType"+$lvl,$exclIsNumber="exclIsNumber"+$lvl,$opExpr="op"+$lvl,$opStr="' + "+$opExpr+" + '";out+=" var schemaExcl"+$lvl+" = "+$schemaValueExcl+"; ";$schemaValueExcl="schemaExcl"+$lvl;out+=" var "+$exclusive+"; var "+$exclType+" = typeof "+$schemaValueExcl+"; if ("+$exclType+" != 'boolean' && "+$exclType+" != 'undefined' && "+$exclType+" != 'number') { ";var $errorKeyword=$exclusiveKeyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: '"+$exclusiveKeyword+" should be boolean' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$exclType+" == 'number' ? ( ("+$exclusive+" = "+$schemaValue+" === undefined || "+$schemaValueExcl+" "+$op+"= "+$schemaValue+") ? "+$data+" "+$notOp+"= "+$schemaValueExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) : ( ("+$exclusive+" = "+$schemaValueExcl+" === true) ? "+$data+" "+$notOp+"= "+$schemaValue+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { var op"+$lvl+" = "+$exclusive+" ? '"+$op+"' : '"+$op+"='; ";if($schema===undefined){$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaValueExcl;$isData=$isDataExcl}}else{var $exclIsNumber=typeof $schemaExcl=="number",$opStr=$op;if($exclIsNumber&&$isData){var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" ( "+$schemaValue+" === undefined || "+$schemaExcl+" "+$op+"= "+$schemaValue+" ? "+$data+" "+$notOp+"= "+$schemaExcl+" : "+$data+" "+$notOp+" "+$schemaValue+" ) || "+$data+" !== "+$data+") { "}else{if($exclIsNumber&&$schema===undefined){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$schemaValue=$schemaExcl;$notOp+="="}else{if($exclIsNumber)$schemaValue=Math[$isMax?"min":"max"]($schemaExcl,$schema);if($schemaExcl===($exclIsNumber?$schemaValue:true)){$exclusive=true;$errorKeyword=$exclusiveKeyword;$errSchemaPath=it.errSchemaPath+"/"+$exclusiveKeyword;$notOp+="="}else{$exclusive=false;$opStr+="="}}var $opExpr="'"+$opStr+"'";out+=" if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+" "+$notOp+" "+$schemaValue+" || "+$data+" !== "+$data+") { "}}$errorKeyword=$errorKeyword||$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limit")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { comparison: "+$opExpr+", limit: "+$schemaValue+", exclusive: "+$exclusive+" } ";if(it.opts.messages!==false){out+=" , message: 'should be "+$opStr+" ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],353:[function(require,module,exports){"use strict";module.exports=function generate__limitItems(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxItems"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" "+$data+".length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitItems")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxItems"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" items' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],354:[function(require,module,exports){"use strict";module.exports=function generate__limitLength(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxLength"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}if(it.opts.unicode===false){out+=" "+$data+".length "}else{out+=" ucs2length("+$data+") "}out+=" "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitLength")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT be ";if($keyword=="maxLength"){out+="longer"}else{out+="shorter"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" characters' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],355:[function(require,module,exports){"use strict";module.exports=function generate__limitProperties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}var $op=$keyword=="maxProperties"?">":"<";out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'number') || "}out+=" Object.keys("+$data+").length "+$op+" "+$schemaValue+") { ";var $errorKeyword=$keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"_limitProperties")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have ";if($keyword=="maxProperties"){out+="more"}else{out+="fewer"}out+=" than ";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+$schema}out+=" properties' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],356:[function(require,module,exports){"use strict";module.exports=function generate_allOf(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$allSchemasEmpty=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$allSchemasEmpty=false;$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if($breakOnError){if($allSchemasEmpty){out+=" if (true) { "}else{out+=" "+$closingBraces.slice(0,-1)+" "}}return out}},{}],357:[function(require,module,exports){"use strict";module.exports=function generate_anyOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $noEmptySchema=$schema.every(function($sch){return it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)});if($noEmptySchema){var $currentBaseId=$it.baseId;out+=" var "+$errs+" = errors; var "+$valid+" = false; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$valid+" || "+$nextValid+"; if (!"+$valid+") { ";$closingBraces+="}"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"anyOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should match some schema in anyOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],358:[function(require,module,exports){"use strict";module.exports=function generate_comment(it,$keyword,$ruleType){var out=" ";var $schema=it.schema[$keyword];var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $comment=it.util.toQuotedString($schema);if(it.opts.$comment===true){out+=" console.log("+$comment+");"}else if(typeof it.opts.$comment=="function"){out+=" self._opts.$comment("+$comment+", "+it.util.toQuotedString($errSchemaPath)+", validate.root.schema);"}return out}},{}],359:[function(require,module,exports){"use strict";module.exports=function generate_const(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!$isData){out+=" var schema"+$lvl+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+" = equal("+$data+", schema"+$lvl+"); if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"const"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValue: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to constant' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],360:[function(require,module,exports){"use strict";module.exports=function generate_contains(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId,$nonEmptySchema=it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all);out+="var "+$errs+" = errors;var "+$valid+";";if($nonEmptySchema){var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$nextValid+" = false; for (var "+$idx+" = 0; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" if ("+$nextValid+") break; } ";it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$closingBraces+" if (!"+$nextValid+") {"}else{out+=" if ("+$data+".length == 0) {"}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"contains"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should contain a valid item' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { ";if($nonEmptySchema){out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } "}if(it.opts.allErrors){out+=" } "}return out}},{}],361:[function(require,module,exports){"use strict";module.exports=function generate_custom(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $errorKeyword;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $rule=this,$definition="definition"+$lvl,$rDef=$rule.definition,$closingBraces="";var $compile,$inline,$macro,$ruleValidate,$validateCode;if($isData&&$rDef.$data){$validateCode="keywordValidate"+$lvl;var $validateSchema=$rDef.validateSchema;out+=" var "+$definition+" = RULES.custom['"+$keyword+"'].definition; var "+$validateCode+" = "+$definition+".validate;"}else{$ruleValidate=it.useCustomRule($rule,$schema,it.schema,it);if(!$ruleValidate)return;$schemaValue="validate.schema"+$schemaPath;$validateCode=$ruleValidate.code;$compile=$rDef.compile;$inline=$rDef.inline;$macro=$rDef.macro}var $ruleErrs=$validateCode+".errors",$i="i"+$lvl,$ruleErr="ruleErr"+$lvl,$asyncKeyword=$rDef.async;if($asyncKeyword&&!it.async)throw new Error("async keyword in sync schema");if(!($inline||$macro)){out+=""+$ruleErrs+" = null;"}out+="var "+$errs+" = errors;var "+$valid+";";if($isData&&$rDef.$data){$closingBraces+="}";out+=" if ("+$schemaValue+" === undefined) { "+$valid+" = true; } else { ";if($validateSchema){$closingBraces+="}";out+=" "+$valid+" = "+$definition+".validateSchema("+$schemaValue+"); if ("+$valid+") { "}}if($inline){if($rDef.statements){out+=" "+$ruleValidate.validate+" "}else{out+=" "+$valid+" = "+$ruleValidate.validate+"; "}}else if($macro){var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;$it.schema=$ruleValidate.validate;$it.schemaPath="";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var $code=it.validate($it).replace(/validate\.schema/g,$validateCode);it.compositeRule=$it.compositeRule=$wasComposite;out+=" "+$code}else{var $$outStack=$$outStack||[];$$outStack.push(out);out="";out+=" "+$validateCode+".call( ";if(it.opts.passContext){out+="this"}else{out+="self"}if($compile||$rDef.schema===false){out+=" , "+$data+" "}else{out+=" , "+$schemaValue+" , "+$data+" , validate.schema"+it.schemaPath+" "}out+=" , (dataPath || '')";if(it.errorPath!='""'){out+=" + "+it.errorPath}var $parentData=$dataLvl?"data"+($dataLvl-1||""):"parentData",$parentDataProperty=$dataLvl?it.dataPathArr[$dataLvl]:"parentDataProperty";out+=" , "+$parentData+" , "+$parentDataProperty+" , rootData ) ";var def_callRuleValidate=out;out=$$outStack.pop();if($rDef.errors===false){out+=" "+$valid+" = ";if($asyncKeyword){out+="await "}out+=""+def_callRuleValidate+"; "}else{if($asyncKeyword){$ruleErrs="customErrors"+$lvl;out+=" var "+$ruleErrs+" = null; try { "+$valid+" = await "+def_callRuleValidate+"; } catch (e) { "+$valid+" = false; if (e instanceof ValidationError) "+$ruleErrs+" = e.errors; else throw e; } "}else{out+=" "+$ruleErrs+" = null; "+$valid+" = "+def_callRuleValidate+"; "}}}if($rDef.modifying){out+=" if ("+$parentData+") "+$data+" = "+$parentData+"["+$parentDataProperty+"];"}out+=""+$closingBraces;if($rDef.valid){if($breakOnError){out+=" if (true) { "}}else{out+=" if ( ";if($rDef.valid===undefined){out+=" !";if($macro){out+=""+$nextValid}else{out+=""+$valid}}else{out+=" "+!$rDef.valid+" "}out+=") { ";$errorKeyword=$rule.keyword;var $$outStack=$$outStack||[];$$outStack.push(out);out="";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}var def_customError=out;out=$$outStack.pop();if($inline){if($rDef.errors){if($rDef.errors!="full"){out+=" for (var "+$i+"="+$errs+"; "+$i+"<errors; "+$i+"++) { var "+$ruleErr+" = vErrors["+$i+"]; if ("+$ruleErr+".dataPath === undefined) "+$ruleErr+".dataPath = (dataPath || '') + "+it.errorPath+"; if ("+$ruleErr+".schemaPath === undefined) { "+$ruleErr+'.schemaPath = "'+$errSchemaPath+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } "}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{out+=" if ("+$errs+" == errors) { "+def_customError+" } else { for (var "+$i+"="+$errs+"; "+$i+"<errors; "+$i+"++) { var "+$ruleErr+" = vErrors["+$i+"]; if ("+$ruleErr+".dataPath === undefined) "+$ruleErr+".dataPath = (dataPath || '') + "+it.errorPath+"; if ("+$ruleErr+".schemaPath === undefined) { "+$ruleErr+'.schemaPath = "'+$errSchemaPath+'"; } ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } "}}}else if($macro){out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+($errorKeyword||"custom")+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { keyword: '"+$rule.keyword+"' } ";if(it.opts.messages!==false){out+=" , message: 'should pass \""+$rule.keyword+"\" keyword validation' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}}else{if($rDef.errors===false){out+=" "+def_customError+" "}else{out+=" if (Array.isArray("+$ruleErrs+")) { if (vErrors === null) vErrors = "+$ruleErrs+"; else vErrors = vErrors.concat("+$ruleErrs+"); errors = vErrors.length; for (var "+$i+"="+$errs+"; "+$i+"<errors; "+$i+"++) { var "+$ruleErr+" = vErrors["+$i+"]; if ("+$ruleErr+".dataPath === undefined) "+$ruleErr+".dataPath = (dataPath || '') + "+it.errorPath+"; "+$ruleErr+'.schemaPath = "'+$errSchemaPath+'"; ';if(it.opts.verbose){out+=" "+$ruleErr+".schema = "+$schemaValue+"; "+$ruleErr+".data = "+$data+"; "}out+=" } } else { "+def_customError+" } "}}out+=" } ";if($breakOnError){out+=" else { "}}return out}},{}],362:[function(require,module,exports){"use strict";module.exports=function generate_dependencies(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $schemaDeps={},$propertyDeps={},$ownProperties=it.opts.ownProperties;for($property in $schema){if($property=="__proto__")continue;var $sch=$schema[$property];var $deps=Array.isArray($sch)?$propertyDeps:$schemaDeps;$deps[$property]=$sch}out+="var "+$errs+" = errors;";var $currentErrorPath=it.errorPath;out+="var missing"+$lvl+";";for(var $property in $propertyDeps){$deps=$propertyDeps[$property];if($deps.length){out+=" if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}if($breakOnError){out+=" && ( ";var arr1=$deps;if(arr1){var $propertyKey,$i=-1,l1=arr1.length-1
|
|
36
36
|
;while($i<l1){$propertyKey=arr1[$i+=1];if($i){out+=" || "}var $prop=it.util.getProperty($propertyKey),$useData=$data+$prop;out+=" ( ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") && (missing"+$lvl+" = "+it.util.toQuotedString(it.opts.jsonPointers?$propertyKey:$prop)+") ) "}}out+=")) { ";var $propertyPath="missing"+$lvl,$missingProperty="' + "+$propertyPath+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.opts.jsonPointers?it.util.getPathExpr($currentErrorPath,$propertyPath,true):$currentErrorPath+" + "+$propertyPath}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"dependencies"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { property: '"+it.util.escapeQuotes($property)+"', missingProperty: '"+$missingProperty+"', depsCount: "+$deps.length+", deps: '"+it.util.escapeQuotes($deps.length==1?$deps[0]:$deps.join(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}}else{out+=" ) { ";var arr2=$deps;if(arr2){var $propertyKey,i2=-1,l2=arr2.length-1;while(i2<l2){$propertyKey=arr2[i2+=1];var $prop=it.util.getProperty($propertyKey),$missingProperty=it.util.escapeQuotes($propertyKey),$useData=$data+$prop;if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPath($currentErrorPath,$propertyKey,it.opts.jsonPointers)}out+=" if ( "+$useData+" === undefined ";if($ownProperties){out+=" || ! Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($propertyKey)+"') "}out+=") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"dependencies"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { property: '"+it.util.escapeQuotes($property)+"', missingProperty: '"+$missingProperty+"', depsCount: "+$deps.length+", deps: '"+it.util.escapeQuotes($deps.length==1?$deps[0]:$deps.join(", "))+"' } ";if(it.opts.messages!==false){out+=" , message: 'should have ";if($deps.length==1){out+="property "+it.util.escapeQuotes($deps[0])}else{out+="properties "+it.util.escapeQuotes($deps.join(", "))}out+=" when property "+it.util.escapeQuotes($property)+" is present' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}}out+=" } ";if($breakOnError){$closingBraces+="}";out+=" else { "}}}it.errorPath=$currentErrorPath;var $currentBaseId=$it.baseId;for(var $property in $schemaDeps){var $sch=$schemaDeps[$property];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ( "+$data+it.util.getProperty($property)+" !== undefined ";if($ownProperties){out+=" && Object.prototype.hasOwnProperty.call("+$data+", '"+it.util.escapeQuotes($property)+"') "}out+=") { ";$it.schema=$sch;$it.schemaPath=$schemaPath+it.util.getProperty($property);$it.errSchemaPath=$errSchemaPath+"/"+it.util.escapeFragment($property);out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],363:[function(require,module,exports){"use strict";module.exports=function generate_enum(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $i="i"+$lvl,$vSchema="schema"+$lvl;if(!$isData){out+=" var "+$vSchema+" = validate.schema"+$schemaPath+";"}out+="var "+$valid+";";if($isData){out+=" if (schema"+$lvl+" === undefined) "+$valid+" = true; else if (!Array.isArray(schema"+$lvl+")) "+$valid+" = false; else {"}out+=""+$valid+" = false;for (var "+$i+"=0; "+$i+"<"+$vSchema+".length; "+$i+"++) if (equal("+$data+", "+$vSchema+"["+$i+"])) { "+$valid+" = true; break; }";if($isData){out+=" } "}out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"enum"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { allowedValues: schema"+$lvl+" } ";if(it.opts.messages!==false){out+=" , message: 'should be equal to one of the allowed values' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" }";if($breakOnError){out+=" else { "}return out}},{}],364:[function(require,module,exports){"use strict";module.exports=function generate_format(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");if(it.opts.format===false){if($breakOnError){out+=" if (true) { "}return out}var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $unknownFormats=it.opts.unknownFormats,$allowUnknown=Array.isArray($unknownFormats);if($isData){var $format="format"+$lvl,$isObject="isObject"+$lvl,$formatType="formatType"+$lvl;out+=" var "+$format+" = formats["+$schemaValue+"]; var "+$isObject+" = typeof "+$format+" == 'object' && !("+$format+" instanceof RegExp) && "+$format+".validate; var "+$formatType+" = "+$isObject+" && "+$format+".type || 'string'; if ("+$isObject+") { ";if(it.async){out+=" var async"+$lvl+" = "+$format+".async; "}out+=" "+$format+" = "+$format+".validate; } if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" (";if($unknownFormats!="ignore"){out+=" ("+$schemaValue+" && !"+$format+" ";if($allowUnknown){out+=" && self._opts.unknownFormats.indexOf("+$schemaValue+") == -1 "}out+=") || "}out+=" ("+$format+" && "+$formatType+" == '"+$ruleType+"' && !(typeof "+$format+" == 'function' ? ";if(it.async){out+=" (async"+$lvl+" ? await "+$format+"("+$data+") : "+$format+"("+$data+")) "}else{out+=" "+$format+"("+$data+") "}out+=" : "+$format+".test("+$data+"))))) {"}else{var $format=it.formats[$schema];if(!$format){if($unknownFormats=="ignore"){it.logger.warn('unknown format "'+$schema+'" ignored in schema at path "'+it.errSchemaPath+'"');if($breakOnError){out+=" if (true) { "}return out}else if($allowUnknown&&$unknownFormats.indexOf($schema)>=0){if($breakOnError){out+=" if (true) { "}return out}else{throw new Error('unknown format "'+$schema+'" is used in schema at path "'+it.errSchemaPath+'"')}}var $isObject=typeof $format=="object"&&!($format instanceof RegExp)&&$format.validate;var $formatType=$isObject&&$format.type||"string";if($isObject){var $async=$format.async===true;$format=$format.validate}if($formatType!=$ruleType){if($breakOnError){out+=" if (true) { "}return out}if($async){if(!it.async)throw new Error("async format in sync schema");var $formatRef="formats"+it.util.getProperty($schema)+".validate";out+=" if (!(await "+$formatRef+"("+$data+"))) { "}else{out+=" if (! ";var $formatRef="formats"+it.util.getProperty($schema);if($isObject)$formatRef+=".validate";if(typeof $format=="function"){out+=" "+$formatRef+"("+$data+") "}else{out+=" "+$formatRef+".test("+$data+") "}out+=") { "}}var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"format"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { format: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match format \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";if($breakOnError){out+=" else { "}return out}},{}],365:[function(require,module,exports){"use strict";module.exports=function generate_if(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;var $thenSch=it.schema["then"],$elseSch=it.schema["else"],$thenPresent=$thenSch!==undefined&&(it.opts.strictKeywords?typeof $thenSch=="object"&&Object.keys($thenSch).length>0||$thenSch===false:it.util.schemaHasRules($thenSch,it.RULES.all)),$elsePresent=$elseSch!==undefined&&(it.opts.strictKeywords?typeof $elseSch=="object"&&Object.keys($elseSch).length>0||$elseSch===false:it.util.schemaHasRules($elseSch,it.RULES.all)),$currentBaseId=$it.baseId;if($thenPresent||$elsePresent){var $ifClause;$it.createErrors=false;$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; var "+$valid+" = true; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;$it.createErrors=true;out+=" errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";it.compositeRule=$it.compositeRule=$wasComposite;if($thenPresent){out+=" if ("+$nextValid+") { ";$it.schema=it.schema["then"];$it.schemaPath=it.schemaPath+".then";$it.errSchemaPath=it.errSchemaPath+"/then";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'then'; "}else{$ifClause="'then'"}out+=" } ";if($elsePresent){out+=" else { "}}else{out+=" if (!"+$nextValid+") { "}if($elsePresent){$it.schema=it.schema["else"];$it.schemaPath=it.schemaPath+".else";$it.errSchemaPath=it.errSchemaPath+"/else";out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId;out+=" "+$valid+" = "+$nextValid+"; ";if($thenPresent&&$elsePresent){$ifClause="ifClause"+$lvl;out+=" var "+$ifClause+" = 'else'; "}else{$ifClause="'else'"}out+=" } "}out+=" if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"if"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { failingKeyword: "+$ifClause+" } ";if(it.opts.messages!==false){out+=" , message: 'should match \"' + "+$ifClause+" + '\" schema' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+=" } ";if($breakOnError){out+=" else { "}}else{if($breakOnError){out+=" if (true) { "}}return out}},{}],366:[function(require,module,exports){"use strict";module.exports={$ref:require("./ref"),allOf:require("./allOf"),anyOf:require("./anyOf"),$comment:require("./comment"),const:require("./const"),contains:require("./contains"),dependencies:require("./dependencies"),enum:require("./enum"),format:require("./format"),if:require("./if"),items:require("./items"),maximum:require("./_limit"),minimum:require("./_limit"),maxItems:require("./_limitItems"),minItems:require("./_limitItems"),maxLength:require("./_limitLength"),minLength:require("./_limitLength"),maxProperties:require("./_limitProperties"),minProperties:require("./_limitProperties"),multipleOf:require("./multipleOf"),not:require("./not"),oneOf:require("./oneOf"),pattern:require("./pattern"),properties:require("./properties"),propertyNames:require("./propertyNames"),required:require("./required"),uniqueItems:require("./uniqueItems"),validate:require("./validate")}},{"./_limit":352,"./_limitItems":353,"./_limitLength":354,"./_limitProperties":355,"./allOf":356,"./anyOf":357,"./comment":358,"./const":359,"./contains":360,"./dependencies":362,"./enum":363,"./format":364,"./if":365,"./items":367,"./multipleOf":368,"./not":369,"./oneOf":370,"./pattern":371,"./properties":372,"./propertyNames":373,"./ref":374,"./required":375,"./uniqueItems":376,"./validate":377}],367:[function(require,module,exports){"use strict";module.exports=function generate_items(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $idx="i"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$currentBaseId=it.baseId;out+="var "+$errs+" = errors;var "+$valid+";";if(Array.isArray($schema)){var $additionalItems=it.schema.additionalItems;if($additionalItems===false){out+=" "+$valid+" = "+$data+".length <= "+$schema.length+"; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" if (!"+$valid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalItems"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { limit: "+$schema.length+" } ";if(it.opts.messages!==false){out+=" , message: 'should NOT have more than "+$schema.length+" items' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } ";$errSchemaPath=$currErrSchemaPath;if($breakOnError){$closingBraces+="}";out+=" else { "}}var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){out+=" "+$nextValid+" = true; if ("+$data+".length > "+$i+") { ";var $passData=$data+"["+$i+"]";$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;$it.errorPath=it.util.getPathExpr(it.errorPath,$i,it.opts.jsonPointers,true);$it.dataPathArr[$dataNxt]=$i;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}out+=" } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}}if(typeof $additionalItems=="object"&&(it.opts.strictKeywords?typeof $additionalItems=="object"&&Object.keys($additionalItems).length>0||$additionalItems===false:it.util.schemaHasRules($additionalItems,it.RULES.all))){$it.schema=$additionalItems;$it.schemaPath=it.schemaPath+".additionalItems";$it.errSchemaPath=it.errSchemaPath+"/additionalItems";out+=" "+$nextValid+" = true; if ("+$data+".length > "+$schema.length+") { for (var "+$idx+" = "+$schema.length+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" } } ";if($breakOnError){out+=" if ("+$nextValid+") { ";$closingBraces+="}"}}}else if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" for (var "+$idx+" = "+0+"; "+$idx+" < "+$data+".length; "+$idx+"++) { ";$it.errorPath=it.util.getPathExpr(it.errorPath,$idx,it.opts.jsonPointers,true);var $passData=$data+"["+$idx+"]";$it.dataPathArr[$dataNxt]=$idx;var $code=it.validate($it);$it.baseId=$currentBaseId;if(it.util.varOccurences($code,$nextData)<2){out+=" "+it.util.varReplace($code,$nextData,$passData)+" "}else{out+=" var "+$nextData+" = "+$passData+"; "+$code+" "}if($breakOnError){out+=" if (!"+$nextValid+") break; "}out+=" }"}if($breakOnError){out+=" "+$closingBraces+" if ("+$errs+" == errors) {"}return out}},{}],368:[function(require,module,exports){"use strict";module.exports=function generate_multipleOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}if(!($isData||typeof $schema=="number")){throw new Error($keyword+" must be number")}out+="var division"+$lvl+";if (";if($isData){out+=" "+$schemaValue+" !== undefined && ( typeof "+$schemaValue+" != 'number' || "}out+=" (division"+$lvl+" = "+$data+" / "+$schemaValue+", ";if(it.opts.multipleOfPrecision){out+=" Math.abs(Math.round(division"+$lvl+") - division"+$lvl+") > 1e-"+it.opts.multipleOfPrecision+" "}else{out+=" division"+$lvl+" !== parseInt(division"+$lvl+") "}out+=" ) ";if($isData){out+=" ) "}out+=" ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"multipleOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { multipleOf: "+$schemaValue+" } ";if(it.opts.messages!==false){out+=" , message: 'should be multiple of ";if($isData){out+="' + "+$schemaValue}else{out+=""+$schemaValue+"'"}}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+$schema}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],369:[function(require,module,exports){"use strict";module.exports=function generate_not(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);$it.level++;var $nextValid="valid"+$it.level;if(it.opts.strictKeywords?typeof $schema=="object"&&Object.keys($schema).length>0||$schema===false:it.util.schemaHasRules($schema,it.RULES.all)){$it.schema=$schema;$it.schemaPath=$schemaPath;$it.errSchemaPath=$errSchemaPath;out+=" var "+$errs+" = errors; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;$it.createErrors=false;var $allErrorsOption;if($it.opts.allErrors){$allErrorsOption=$it.opts.allErrors;$it.opts.allErrors=false}out+=" "+it.validate($it)+" ";$it.createErrors=true;if($allErrorsOption)$it.opts.allErrors=$allErrorsOption;it.compositeRule=$it.compositeRule=$wasComposite;out+=" if ("+$nextValid+") { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+=" } else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; } ";if(it.opts.allErrors){out+=" } "}}else{out+=" var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"not"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: {} ";if(it.opts.messages!==false){out+=" , message: 'should NOT be valid' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if($breakOnError){out+=" if (false) { "}}return out}},{}],370:[function(require,module,exports){"use strict";module.exports=function generate_oneOf(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $valid="valid"+$lvl;var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $currentBaseId=$it.baseId,$prevValid="prevValid"+$lvl,$passingSchemas="passingSchemas"+$lvl;out+="var "+$errs+" = errors , "+$prevValid+" = false , "+$valid+" = false , "+$passingSchemas+" = null; ";var $wasComposite=it.compositeRule;it.compositeRule=$it.compositeRule=true;var arr1=$schema;if(arr1){var $sch,$i=-1,l1=arr1.length-1;while($i<l1){$sch=arr1[$i+=1];if(it.opts.strictKeywords?typeof $sch=="object"&&Object.keys($sch).length>0||$sch===false:it.util.schemaHasRules($sch,it.RULES.all)){$it.schema=$sch;$it.schemaPath=$schemaPath+"["+$i+"]";$it.errSchemaPath=$errSchemaPath+"/"+$i;out+=" "+it.validate($it)+" ";$it.baseId=$currentBaseId}else{out+=" var "+$nextValid+" = true; "}if($i){out+=" if ("+$nextValid+" && "+$prevValid+") { "+$valid+" = false; "+$passingSchemas+" = ["+$passingSchemas+", "+$i+"]; } else { ";$closingBraces+="}"}out+=" if ("+$nextValid+") { "+$valid+" = "+$prevValid+" = true; "+$passingSchemas+" = "+$i+"; }"}}it.compositeRule=$it.compositeRule=$wasComposite;out+=""+$closingBraces+"if (!"+$valid+") { var err = ";if(it.createErrors!==false){out+=" { keyword: '"+"oneOf"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { passingSchemas: "+$passingSchemas+" } ";if(it.opts.messages!==false){out+=" , message: 'should match exactly one schema in oneOf' "}if(it.opts.verbose){out+=" , schema: validate.schema"+$schemaPath+" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}out+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(vErrors); "}else{out+=" validate.errors = vErrors; return false; "}}out+="} else { errors = "+$errs+"; if (vErrors !== null) { if ("+$errs+") vErrors.length = "+$errs+"; else vErrors = null; }";if(it.opts.allErrors){out+=" } "}return out}},{}],371:[function(require,module,exports){"use strict";module.exports=function generate_pattern(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $isData=it.opts.$data&&$schema&&$schema.$data,$schemaValue;if($isData){out+=" var schema"+$lvl+" = "+it.util.getData($schema.$data,$dataLvl,it.dataPathArr)+"; ";$schemaValue="schema"+$lvl}else{$schemaValue=$schema}var $regexp=$isData?"(new RegExp("+$schemaValue+"))":it.usePattern($schema);out+="if ( ";if($isData){out+=" ("+$schemaValue+" !== undefined && typeof "+$schemaValue+" != 'string') || "}out+=" !"+$regexp+".test("+$data+") ) { ";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"pattern"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { pattern: ";if($isData){out+=""+$schemaValue}else{out+=""+it.util.toQuotedString($schema)}out+=" } ";if(it.opts.messages!==false){out+=" , message: 'should match pattern \"";if($isData){out+="' + "+$schemaValue+" + '"}else{out+=""+it.util.escapeQuotes($schema)}out+="\"' "}if(it.opts.verbose){out+=" , schema: ";if($isData){out+="validate.schema"+$schemaPath}else{out+=""+it.util.toQuotedString($schema)}out+=" , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){out+=" throw new ValidationError(["+__err+"]); "}else{out+=" validate.errors = ["+__err+"]; return false; "}}else{out+=" var err = "+__err+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}out+="} ";if($breakOnError){out+=" else { "}return out}},{}],372:[function(require,module,exports){"use strict";module.exports=function generate_properties(it,$keyword,$ruleType){var out=" ";var $lvl=it.level;var $dataLvl=it.dataLevel;var $schema=it.schema[$keyword];var $schemaPath=it.schemaPath+it.util.getProperty($keyword);var $errSchemaPath=it.errSchemaPath+"/"+$keyword;var $breakOnError=!it.opts.allErrors;var $data="data"+($dataLvl||"");var $errs="errs__"+$lvl;var $it=it.util.copy(it);var $closingBraces="";$it.level++;var $nextValid="valid"+$it.level;var $key="key"+$lvl,$idx="idx"+$lvl,$dataNxt=$it.dataLevel=it.dataLevel+1,$nextData="data"+$dataNxt,$dataProperties="dataProperties"+$lvl;var $schemaKeys=Object.keys($schema||{}).filter(notProto),$pProperties=it.schema.patternProperties||{},$pPropertyKeys=Object.keys($pProperties).filter(notProto),$aProperties=it.schema.additionalProperties,$someProperties=$schemaKeys.length||$pPropertyKeys.length,$noAdditional=$aProperties===false,$additionalIsSchema=typeof $aProperties=="object"&&Object.keys($aProperties).length,$removeAdditional=it.opts.removeAdditional,$checkAdditional=$noAdditional||$additionalIsSchema||$removeAdditional,$ownProperties=it.opts.ownProperties,$currentBaseId=it.baseId;var $required=it.schema.required;if($required&&!(it.opts.$data&&$required.$data)&&$required.length<it.opts.loopRequired){var $requiredHash=it.util.toHash($required)}function notProto(p){return p!=="__proto__"}out+="var "+$errs+" = errors;var "+$nextValid+" = true;";if($ownProperties){out+=" var "+$dataProperties+" = undefined;"}if($checkAdditional){if($ownProperties){out+=" "+$dataProperties+" = "+$dataProperties+" || Object.keys("+$data+"); for (var "+$idx+"=0; "+$idx+"<"+$dataProperties+".length; "+$idx+"++) { var "+$key+" = "+$dataProperties+"["+$idx+"]; "}else{out+=" for (var "+$key+" in "+$data+") { "}if($someProperties){out+=" var isAdditional"+$lvl+" = !(false ";if($schemaKeys.length){if($schemaKeys.length>8){out+=" || validate.schema"+$schemaPath+".hasOwnProperty("+$key+") "}else{var arr1=$schemaKeys;if(arr1){var $propertyKey,i1=-1,l1=arr1.length-1;while(i1<l1){$propertyKey=arr1[i1+=1];out+=" || "+$key+" == "+it.util.toQuotedString($propertyKey)+" "}}}}if($pPropertyKeys.length){var arr2=$pPropertyKeys;if(arr2){var $pProperty,$i=-1,l2=arr2.length-1;while($i<l2){$pProperty=arr2[$i+=1];out+=" || "+it.usePattern($pProperty)+".test("+$key+") "}}}out+=" ); if (isAdditional"+$lvl+") { "}if($removeAdditional=="all"){out+=" delete "+$data+"["+$key+"]; "}else{var $currentErrorPath=it.errorPath;var $additionalProperty="' + "+$key+" + '";if(it.opts._errorDataPathProperty){it.errorPath=it.util.getPathExpr(it.errorPath,$key,it.opts.jsonPointers)}if($noAdditional){if($removeAdditional){out+=" delete "+$data+"["+$key+"]; "}else{out+=" "+$nextValid+" = false; ";var $currErrSchemaPath=$errSchemaPath;$errSchemaPath=it.errSchemaPath+"/additionalProperties";var $$outStack=$$outStack||[];$$outStack.push(out);out="";if(it.createErrors!==false){out+=" { keyword: '"+"additionalProperties"+"' , dataPath: (dataPath || '') + "+it.errorPath+" , schemaPath: "+it.util.toQuotedString($errSchemaPath)+" , params: { additionalProperty: '"+$additionalProperty+"' } ";if(it.opts.messages!==false){out+=" , message: '";if(it.opts._errorDataPathProperty){out+="is an invalid additional property"}else{out+="should NOT have additional properties"}out+="' "}if(it.opts.verbose){out+=" , schema: false , parentSchema: validate.schema"+it.schemaPath+" , data: "+$data+" "}out+=" } "}else{out+=" {} "}var __err=out;out=$$outStack.pop();if(!it.compositeRule&&$breakOnError){if(it.async){
|