UNPKG

277 kBJavaScriptView Raw
1"use strict";function _interopDefault(t){return t&&"object"==typeof t&&"default"in t?t.default:t}var net=require("net"),http=require("http"),https=require("https"),url=require("url"),fs=require("fs"),os=require("os"),zlib$1=require("zlib"),path$4=_interopDefault(require("path")),util=require("util"),util__default=_interopDefault(util),child_process=require("child_process");function __awaiter(t,e,s,a){return new(s||(s=Promise))(function(r,i){function fulfilled(t){try{step(a.next(t))}catch(t){i(t)}}function rejected(t){try{step(a.throw(t))}catch(t){i(t)}}function step(t){t.done?r(t.value):new s(function(e){e(t.value)}).then(fulfilled,rejected)}step((a=a.apply(t,e||[])).next())})}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function unwrapExports(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function createCommonjsModule(t,e){return t(e={exports:{}},e.exports),e.exports}var binary_carrier=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=function(){return function(t){this.buffer=t}}();e.default=s});unwrapExports(binary_carrier);var tags=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.SPAN_KIND="span.kind",e.SPAN_KIND_RPC_CLIENT="client",e.SPAN_KIND_RPC_SERVER="server",e.SPAN_KIND_MESSAGING_PRODUCER="producer",e.SPAN_KIND_MESSAGING_CONSUMER="consumer",e.ERROR="error",e.COMPONENT="component",e.SAMPLING_PRIORITY="sampling.priority",e.PEER_SERVICE="peer.service",e.PEER_HOSTNAME="peer.hostname",e.PEER_ADDRESS="peer.address",e.PEER_HOST_IPV4="peer.ipv4",e.PEER_HOST_IPV6="peer.ipv6",e.PEER_PORT="peer.port",e.HTTP_URL="http.url",e.HTTP_METHOD="http.method",e.HTTP_STATUS_CODE="http.status_code",e.MESSAGE_BUS_DESTINATION="message_bus.destination",e.DB_INSTANCE="db.instance",e.DB_STATEMENT="db.statement",e.DB_TYPE="db.type",e.DB_USER="db.user"});unwrapExports(tags);var tags_1=tags.SPAN_KIND,tags_2=tags.SPAN_KIND_RPC_CLIENT,tags_3=tags.SPAN_KIND_RPC_SERVER,tags_4=tags.SPAN_KIND_MESSAGING_PRODUCER,tags_5=tags.SPAN_KIND_MESSAGING_CONSUMER,tags_6=tags.ERROR,tags_7=tags.COMPONENT,tags_8=tags.SAMPLING_PRIORITY,tags_9=tags.PEER_SERVICE,tags_10=tags.PEER_HOSTNAME,tags_11=tags.PEER_ADDRESS,tags_12=tags.PEER_HOST_IPV4,tags_13=tags.PEER_HOST_IPV6,tags_14=tags.PEER_PORT,tags_15=tags.HTTP_URL,tags_16=tags.HTTP_METHOD,tags_17=tags.HTTP_STATUS_CODE,tags_18=tags.MESSAGE_BUS_DESTINATION,tags_19=tags.DB_INSTANCE,tags_20=tags.DB_STATEMENT,tags_21=tags.DB_TYPE,tags_22=tags.DB_USER,span=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function Span(){}return Span.prototype.context=function(){return this._context()},Span.prototype.tracer=function(){return this._tracer()},Span.prototype.setOperationName=function(t){return this._setOperationName(t),this},Span.prototype.setBaggageItem=function(t,e){return this._setBaggageItem(t,e),this},Span.prototype.getBaggageItem=function(t){return this._getBaggageItem(t)},Span.prototype.setTag=function(t,e){return this._addTags(((s={})[t]=e,s)),this;var s},Span.prototype.addTags=function(t){return this._addTags(t),this},Span.prototype.log=function(t,e){return this._log(t,e),this},Span.prototype.logEvent=function(t,e){return this._log({event:t,payload:e})},Span.prototype.finish=function(t){this._finish(t)},Span.prototype._context=function(){return noop.spanContext},Span.prototype._tracer=function(){return noop.tracer},Span.prototype._setOperationName=function(t){},Span.prototype._setBaggageItem=function(t,e){},Span.prototype._getBaggageItem=function(t){},Span.prototype._addTags=function(t){},Span.prototype._log=function(t,e){},Span.prototype._finish=function(t){},Span}();e.Span=s,e.default=s});unwrapExports(span);var span_1=span.Span,span_context=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=function(){return function(){}}();e.SpanContext=s,e.default=s});unwrapExports(span_context);var span_context_1=span_context.SpanContext,constants=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.FORMAT_BINARY="binary",e.FORMAT_TEXT_MAP="text_map",e.FORMAT_HTTP_HEADERS="http_headers",e.REFERENCE_CHILD_OF="child_of",e.REFERENCE_FOLLOWS_FROM="follows_from"});unwrapExports(constants);var constants_1=constants.FORMAT_BINARY,constants_2=constants.FORMAT_TEXT_MAP,constants_3=constants.FORMAT_HTTP_HEADERS,constants_4=constants.REFERENCE_CHILD_OF,constants_5=constants.REFERENCE_FOLLOWS_FROM,reference=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function Reference(t,e){this._type=t,this._referencedContext=e instanceof span.default?e.context():e}return Reference.prototype.type=function(){return this._type},Reference.prototype.referencedContext=function(){return this._referencedContext},Reference}();e.default=s}),Reference=unwrapExports(reference),functions=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.childOf=function(t){return t instanceof span.default&&(t=t.context()),new reference.default(constants.REFERENCE_CHILD_OF,t)},e.followsFrom=function(t){return t instanceof span.default&&(t=t.context()),new reference.default(constants.REFERENCE_FOLLOWS_FROM,t)}});unwrapExports(functions);var functions_1=functions.childOf,functions_2=functions.followsFrom,tracer=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function Tracer(){}return Tracer.prototype.startSpan=function(t,e){if(void 0===e&&(e={}),e.childOf){var s=functions.childOf(e.childOf);e.references?e.references.push(s):e.references=[s],delete e.childOf}return this._startSpan(t,e)},Tracer.prototype.inject=function(t,e,s){return t instanceof span.default&&(t=t.context()),this._inject(t,e,s)},Tracer.prototype.extract=function(t,e){return this._extract(t,e)},Tracer.prototype._startSpan=function(t,e){return noop.span},Tracer.prototype._inject=function(t,e,s){},Tracer.prototype._extract=function(t,e){return noop.spanContext},Tracer}();e.Tracer=s,e.default=s});unwrapExports(tracer);var tracer_1=tracer.Tracer,noop=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.tracer=null,e.spanContext=null,e.span=null,e.initialize=function(){e.tracer=new tracer.default,e.span=new span.default,e.spanContext=new span_context.default}});unwrapExports(noop);var noop_1=noop.tracer,noop_2=noop.spanContext,noop_3=noop.span,noop_4=noop.initialize,global_tracer=createCommonjsModule(function(t,e){var s,a=commonjsGlobal&&commonjsGlobal.__extends||(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var s in e)e.hasOwnProperty(s)&&(t[s]=e[s])},function(t,e){function __(){this.constructor=t}s(t,e),t.prototype=null===e?Object.create(e):(__.prototype=e.prototype,new __)});Object.defineProperty(e,"__esModule",{value:!0});var r=new tracer.default,i=null,n=new(function(t){function GlobalTracerDelegate(){return null!==t&&t.apply(this,arguments)||this}return a(GlobalTracerDelegate,t),GlobalTracerDelegate.prototype.startSpan=function(){var t=i||r;return t.startSpan.apply(t,arguments)},GlobalTracerDelegate.prototype.inject=function(){var t=i||r;return t.inject.apply(t,arguments)},GlobalTracerDelegate.prototype.extract=function(){var t=i||r;return t.extract.apply(t,arguments)},GlobalTracerDelegate}(tracer.default));e.initGlobalTracer=function(t){i=t},e.globalTracer=function(){return n}});unwrapExports(global_tracer);var MonitoringDataType,global_tracer_1=global_tracer.initGlobalTracer,global_tracer_2=global_tracer.globalTracer,lib=createCommonjsModule(function(t,e){function __export(t){for(var s in t)e.hasOwnProperty(s)||(e[s]=t[s])}Object.defineProperty(e,"__esModule",{value:!0}),e.BinaryCarrier=binary_carrier.default,e.Tags=tags,e.Reference=reference.default,e.Span=span.default,e.SpanContext=span_context.default,e.Tracer=tracer.default,__export(global_tracer),__export(constants),__export(functions),noop.initialize()}),index=unwrapExports(lib),lib_1=lib.initGlobalTracer,lib_2=lib.BinaryCarrier,lib_3=lib.Tags,lib_4=lib.Reference,lib_5=lib.Span,lib_6=lib.SpanContext,lib_7=lib.Tracer,opentracing=Object.freeze({default:index,__moduleExports:lib,initGlobalTracer:lib_1,BinaryCarrier:lib_2,Tags:lib_3,Reference:lib_4,Span:lib_5,SpanContext:lib_6,Tracer:lib_7});class ThundraSpanContext extends lib_6{constructor(t){super(),this.transactionId=t.transactionId,this.traceId=t.traceId,this.spanId=t.spanId,this.parentId=t.parentId||null,this.sampled=void 0===t.sampled||t.sampled,this.baggageItems=t.baggageItems||{}}}!function(t){t.INVOCATION="Invocation",t.SPAN="Span",t.METRIC="Metric",t.LOG="Log",t.COMPOSITE="Composite"}(MonitoringDataType||(MonitoringDataType={}));var MonitoringDataType$1=MonitoringDataType;class BaseMonitoringData{constructor(t){this.applicationRuntime="node",this.type=t,this.applicationTags={}}initWithBaseMonitoringDataValues(t){this.agentVersion=t.agentVersion,this.dataModelVersion=t.dataModelVersion,this.applicationId=t.applicationId,this.applicationInstanceId=t.applicationInstanceId,this.applicationDomainName=t.applicationDomainName,this.applicationClassName=t.applicationClassName,this.applicationName=t.applicationName,this.applicationVersion=t.applicationVersion,this.applicationStage=t.applicationStage,this.applicationRuntimeVersion=t.applicationRuntimeVersion,this.applicationTags=Object.assign({},t.applicationTags)}}class ThundraLogger{constructor(){this.enabled="true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_AGENT_DEBUG_ENABLE),ThundraLogger.instance=this}static getInstance(){return ThundraLogger.instance?ThundraLogger.instance:new ThundraLogger}debug(t){this.enabled&&console.log(t)}info(t){console.log(t)}error(t){console.error(t)}toggle(){this.enabled=!this.enabled}}class InvocationData extends BaseMonitoringData{constructor(){super(MonitoringDataType$1.INVOCATION)}setTags(t){try{Object.keys(t).forEach(e=>{this.tags[e]=t[e]})}catch(t){ThundraLogger.getInstance().error(t)}}setUserTags(t){try{Object.keys(t).forEach(e=>{this.userTags[e]=t[e]})}catch(t){ThundraLogger.getInstance().error(t)}}setError(t){this.erroneous=!0,this.errorType=t.errorType,this.errorMessage=t.errorMessage}}class MetricData extends BaseMonitoringData{constructor(){super(MonitoringDataType$1.METRIC),this.tags={}}initWithMetricMonitoringDataValues(t){this.initWithBaseMonitoringDataValues(t),this.traceId=t.traceId,this.transactionId=t.transactionId,this.spanId=t.spanId,this.tags=t.tags}}class SpanData extends BaseMonitoringData{constructor(){super(MonitoringDataType$1.SPAN)}}class LogData extends BaseMonitoringData{constructor(){super(MonitoringDataType$1.LOG)}initWithLogDataValues(t,e,s){this.initWithBaseMonitoringDataValues(t),this.id=Utils.generateId(),this.traceId=t.traceId,this.transactionId=t.transactionId,this.spanId=e,this.logMessage=s.logMessage,this.logTimestamp=s.logTimestamp,this.logLevel=s.logLevel,this.logLevelCode=s.logLevelCode,this.logContextName=s.logContextName,this.tags={}}}class ApplicationSupport{static parseApplicationTags(){ApplicationSupport.applicationTags={};for(const t of Object.keys(process.env))if(t.startsWith(envVariableKeys.THUNDRA_APPLICATION_TAG_PROP_NAME_PREFIX))try{const e=t.substring(envVariableKeys.THUNDRA_APPLICATION_TAG_PROP_NAME_PREFIX.length),s=process.env[t];isNaN(parseFloat(s))?ApplicationSupport.applicationTags[e]="true"===s||"false"===s?"true"===s:s:ApplicationSupport.applicationTags[e]=parseFloat(s)}catch(e){ThundraLogger.getInstance().error(`Cannot parse application tag ${t}`)}}}ApplicationSupport.applicationTags={};class CompositeMonitoringData extends BaseMonitoringData{constructor(){super(MonitoringDataType$1.COMPOSITE),this.allMonitoringData=[]}}class InvocationSupport{static setAgentTag(t,e){try{InvocationSupport.tags[t]=e}catch(t){ThundraLogger.getInstance().error(t)}}static getAgentTag(t){return InvocationSupport.tags[t]}static setAgentTags(t){try{Object.keys(t).forEach(e=>{InvocationSupport.tags[e]=t[e]})}catch(t){ThundraLogger.getInstance().error(t)}}static removeAgentTags(){InvocationSupport.tags={}}static setTag(t,e){try{InvocationSupport.userTags[t]=e}catch(t){ThundraLogger.getInstance().error(t)}}static getTag(t){return InvocationSupport.userTags[t]}static removeTag(t){try{InvocationSupport.userTags[t]&&delete InvocationSupport.userTags[t]}catch(t){ThundraLogger.getInstance().error(t)}}static setTags(t){try{Object.keys(t).forEach(e=>{InvocationSupport.userTags[e]=t[e]})}catch(t){ThundraLogger.getInstance().error(t)}}static removeTags(){InvocationSupport.userTags={}}static setFunctionName(t){InvocationSupport.functionName=t}static getFunctionName(){return InvocationSupport.functionName}static setErrorenous(t){InvocationSupport.errorenous=t}static isErrorenous(){return InvocationSupport.errorenous}static setError(t){t instanceof Error&&(InvocationSupport.error=Utils.parseError(t))}static hasError(){return void 0!==InvocationSupport.error}static clearError(){InvocationSupport.error&&delete InvocationSupport.error}}InvocationSupport.tags={},InvocationSupport.userTags={},InvocationSupport.functionName="";const parse=require("module-details-from-path"),uuidv4=require("uuid/v4"),zlib=require("zlib"),customReq="undefined"!=typeof __non_webpack_require__?__non_webpack_require__:require;class Utils{static generateId(){return uuidv4()}static generateReport(t,e){return{data:t,type:t.type,apiKey:e,dataModelVersion:DATA_MODEL_VERSION}}static getConfiguration(t,e){return process.env[t]?process.env[t]:e}static getNumericConfiguration(t,e){return parseInt(Utils.getConfiguration(t,e),10)}static getCpuUsage(){const t=os.cpus(),e=process.cpuUsage(),s=e.user+e.system;let a=0,r=0;return t.forEach(t=>{a+=t.times.user+t.times.nice+t.times.sys+t.times.idle+t.times.irq,r+=t.times.idle}),{procCpuUsed:s,sysCpuUsed:a-r,sysCpuTotal:a}}static getCpuLoad(t,e,s){const a=e.sysCpuTotal-t.sysCpuTotal;let r=(e.procCpuUsed-t.procCpuUsed)/s/a,i=(e.sysCpuUsed-t.sysCpuUsed)/a;return r=Number.isNaN(r)?0:r,i=Number.isNaN(i)?0:i,{procCpuLoad:Math.min(r,i),sysCpuLoad:i}}static isString(t){return"string"==typeof t||t instanceof String}static capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}static parseError(t){const e={errorMessage:"",errorType:"Unknown Error",stack:null,code:0};if(t instanceof Error)e.errorType=t.name,e.errorMessage=t.message,e.stack=t.stack;else if("string"==typeof t)e.errorMessage=t.toString();else try{e.errorMessage=JSON.stringify(t)}catch(t){e.errorMessage=""}return Utils.isString(e.errorMessage)||(e.errorMessage=JSON.stringify(e.errorMessage)),e.stack=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_ERROR_STACK_TRACE)?"":e.stack,e}static readProcMetricPromise(){return new Promise((t,e)=>{fs.readFile(PROC_STAT_PATH,(e,s)=>{const a={threadCount:0};if(e)ThundraLogger.getInstance().error(`Cannot read ${PROC_STAT_PATH} file. Setting Thread Metrics to 0.`);else{const t=s.toString().split(" ");a.threadCount=parseInt(t[19],0)}return t(a)})})}static readProcIoPromise(){return new Promise((t,e)=>{fs.readFile(PROC_IO_PATH,(e,s)=>{const a={readBytes:0,writeBytes:0};if(e)ThundraLogger.getInstance().error(`Cannot read ${PROC_IO_PATH} file. Setting Metrics to 0.`);else{const t=s.toString().split("\n");a.readBytes=parseInt(t[4].substr(t[4].indexOf(" ")+1),0),a.writeBytes=parseInt(t[5].substr(t[5].indexOf(" ")+1),0)}return t(a)})})}static readProcNetworkIoSync(t){return new Promise((t,e)=>{fs.readFile(PROC_IO_PATH,(e,s)=>{const a={readBytes:0,writeBytes:0};if(e)ThundraLogger.getInstance().error(`Cannot read ${PROC_IO_PATH} file. Setting Metrics to 0.`);else{const t=s.toString().split("\n");a.readBytes=parseInt(t[4].substr(t[4].indexOf(" ")+1),0),a.writeBytes=parseInt(t[5].substr(t[5].indexOf(" ")+1),0)}return t(a)})})}static getParentContext(t){let e=null;if(t)for(const s of t){if(!(s instanceof Reference)){ThundraLogger.getInstance().error(`Expected ${s} to be an instance of opentracing.Reference`);break}const t=s.referencedContext();if(!(t instanceof ThundraSpanContext)){ThundraLogger.getInstance().error(`Expected ${t} to be an instance of SpanContext`);break}if(void 0===s.type()){e=s.referencedContext();break}void 0===s.type()&&(e||(e=s.referencedContext()))}return e}static replaceArgs(t,e){const s=Array.prototype.slice.call(e);return t.replace(/(\$\d+)/gm,t=>s[parseInt(t.substr(1),10)-1])}static getDynamoDBTableName(t){let e;return t.params&&t.params.TableName&&(e=t.params.TableName),t.params&&t.params.RequestItems&&(e=Object.keys(t.params.RequestItems).join(",")),e}static getQueueName(t){return t?t.split("/").pop():null}static getTopicName(t){return t?t.split(":").pop():""}static getServiceName(t){return t?t.split(".")[0]:""}static tryRequire(t,e){try{let s;return s=void 0!==e?customReq.resolve(t,{paths:e}):customReq.resolve(t),customReq(s)}catch(t){}}static getModuleInfo(t,e){try{let s;return s=void 0!==e?customReq.resolve(t,{paths:e}):customReq.resolve(t),parse(s)}catch(t){return{}}}static initMonitoringData(t,e){const s=this.createMonitoringData(e),a=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_DOMAIN_NAME),r=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_CLASS_NAME),i=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_STAGE),n=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_ID),o=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_NAME),p=Utils.getConfiguration(envVariableKeys.THUNDRA_APPLICATION_VERSION);return s.id=Utils.generateId(),s.agentVersion=AGENT_VERSION,s.dataModelVersion=DATA_MODEL_VERSION,s.applicationInstanceId=t?t.applicationInstanceId:"",s.applicationId=n||(t?t.applicationId:""),s.applicationDomainName=a||LAMBDA_APPLICATION_DOMAIN_NAME,s.applicationClassName=r||LAMBDA_APPLICATION_CLASS_NAME,s.applicationName=o||(InvocationSupport.getFunctionName()?InvocationSupport.getFunctionName():""),s.applicationVersion=p||(t?t.applicationVersion:""),s.applicationStage=i||"",s.applicationRuntimeVersion=process.version,s.applicationTags=Object.assign({},s.applicationTags,ApplicationSupport.applicationTags),s}static initCompositeMonitoringData(t){const e=this.createMonitoringData(MonitoringDataType$1.COMPOSITE);return e.id=Utils.generateId(),e.agentVersion=t.agentVersion,e.dataModelVersion=t.dataModelVersion,e.applicationId=t.applicationId,e.applicationDomainName=t.applicationDomainName,e.applicationClassName=t.applicationClassName,e.applicationName=t.applicationName,e.applicationVersion=t.applicationVersion,e.applicationStage=t.applicationStage,e.applicationRuntime=t.applicationRuntime,e.applicationRuntimeVersion=t.applicationRuntimeVersion,e.applicationTags=t.applicationTags,e}static createMonitoringData(t){let e;switch(t){case MonitoringDataType$1.INVOCATION:e=new InvocationData;break;case MonitoringDataType$1.METRIC:e=new MetricData;break;case MonitoringDataType$1.SPAN:e=new SpanData;break;case MonitoringDataType$1.LOG:e=new LogData;break;case MonitoringDataType$1.COMPOSITE:e=new CompositeMonitoringData}return e}static sleep(t){return new Promise(e=>setTimeout(e,t))}static getRandomInt(t){return 1+Math.floor(Math.random()*t)}static registerSpanListenersFromConfigurations(t){const e=[];for(const s of Object.keys(process.env))if(s.startsWith(envVariableKeys.THUNDRA_AGENT_LAMBDA_SPAN_LISTENER_DEF))try{let a=process.env[s];a.startsWith("{")||(a=this.decodeSpanListenerConfig(a));const r=JSON.parse(a),i=new(0,LISTENERS[r.type])(r.config);t.addSpanListener(i),e.push(i)}catch(t){ThundraLogger.getInstance().error(`Cannot parse span listener def ${s} with reason: ${t.message}`)}return e}static decodeSpanListenerConfig(t){const e=Buffer.from(t,"base64");return zlib.unzipSync(e).toString()}static stripCommonFields(t){return t.agentVersion=void 0,t.dataModelVersion=void 0,t.applicationId=void 0,t.applicationClassName=void 0,t.applicationDomainName=void 0,t.applicationName=void 0,t.applicationVersion=void 0,t.applicationStage=void 0,t.applicationRuntime=void 0,t.applicationRuntimeVersion=void 0,t.applicationTags=void 0,t}static getAWSAccountNo(t){return Utils.getARNPart(t,4)}static getAWSRegion(t){return Utils.getARNPart(t,3)}static getAccountNo(t,e){return Utils.getIfSAMLocalDebugging()?"sam_local":Utils.getIfSLSLocalDebugging()?"sls_local":Utils.getAWSAccountNo(t)||e.apiKey||"guest"}static getApplicationId(t,e){const s=t.invokedFunctionArn;return`aws:lambda:${Utils.getConfiguration(envVariableKeys.AWS_REGION)||"local"}:${Utils.getAccountNo(s,e)}:${t.functionName||Utils.getConfiguration(envVariableKeys.AWS_LAMBDA_FUNCTION_NAME)||"lambda-app"}`}static getARNPart(t,e){try{return t.split(":")[e]}catch(t){return""}}static getIfSAMLocalDebugging(){return"true"===Utils.getConfiguration(envVariableKeys.AWS_SAM_LOCAL)}static getIfSLSLocalDebugging(){return"true"===Utils.getConfiguration(envVariableKeys.SLS_LOCAL)}static getXRayTraceInfo(){let t="",e="";const s=Utils.getConfiguration(envVariableKeys._X_AMZN_TRACE_ID);if(s)for(const a of s.split(";")){const s=a.split("=");if(2!==s.length)continue;const[r,i]=s;"Root"===r?t=i:"Parent"===r&&(e=i)}return{traceID:t,segmentID:e}}}class HttpError extends Error{constructor(t){super(),this.message=t,this.name="HttpError",Error.captureStackTrace(this,HttpError),Object.setPrototypeOf(this,HttpError.prototype)}}class ThundraChaosError extends Error{constructor(t){super(),this.message=t,this.name="ThundraChaosError",Error.captureStackTrace(this,ThundraChaosError),Object.setPrototypeOf(this,ThundraChaosError.prototype)}}const shimmer=require("shimmer"),has=require("lodash.has"),semver=require("semver"),thundraEndpointPattern=/^api[-\w]*\.thundra\.io$/;class HttpIntegration{constructor(t){this.wrapped=!1,this.lib=[Utils.tryRequire("http"),Utils.tryRequire("https")],this.config=t,this.wrap.call(this,this.lib,t)}static isValidUrl(t){return-1!==t.indexOf("amazonaws.com")&&-1!==t.indexOf("execute-api")||!thundraEndpointPattern.test(t)&&"serverless.com"!==t&&-1===t.indexOf("amazonaws.com")}getNormalizedPath(t){try{const e=this.config.httpPathDepth;return e<=0?"":"/"+t.split("/").filter(t=>""!==t).slice(0,e).join("/")}catch(e){return t}}wrap(t,e){const s=t[0],a=t[1],r=process.version,i=this;function wrapper(t){return function(s,a){let r;try{const n=i.config.tracer;if(!n)return t.apply(this,[s,a]);const o=InvocationSupport.getFunctionName(),p=(s.method||"GET").toUpperCase(),c=(s="string"==typeof s?url.parse(s):s).hostname||s.host||"localhost";let h=s.path||s.pathname||"/";const l=c+h,u=h.split("?"),g=u.length>1?u[1]:"";if(h=u[0],!HttpIntegration.isValidUrl(c))return t.apply(this,[s,a]);const d=n.getActiveSpan(),T=c+i.getNormalizedPath(h);if(r=n._startSpan(T,{childOf:d,domainName:DomainNames.API,className:ClassNames.HTTP,disableActiveStart:!0}),"true"!==Utils.getConfiguration(envVariableKeys.DISABLE_SPAN_CONTEXT_INJECTION)){const t=s.headers?s.headers:{};n.inject(r.spanContext,void 0,t),s.headers=t}r.addTags({[SpanTags.OPERATION_TYPE]:p,[SpanTags.SPAN_TYPE]:SpanTypes.HTTP,[HttpTags.HTTP_METHOD]:p,[HttpTags.HTTP_HOST]:c,[HttpTags.HTTP_PATH]:h,[HttpTags.HTTP_URL]:l,[HttpTags.QUERY_PARAMS]:g,[SpanTags.TRACE_LINKS]:[r.spanContext.spanId],[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[o]});const E=this,m=(t,e)=>{t&&r&&r.setErrorTag(t),r&&r.closeWithCallback(E,a,[t,e])};r._initialized();const A=t.call(this,s,m);A.on("response",t=>{if("x-amzn-requestid"in t.headers&&r._setClassName(ClassNames.APIGATEWAY),TriggerHeaderTags.RESOURCE_NAME in t.headers){const e=t.headers[TriggerHeaderTags.RESOURCE_NAME];r._setOperationName(e)}const s=t.statusCode.toString();!e.disableHttp5xxError&&s.startsWith("5")&&r.setErrorTag(new HttpError(t.statusMessage)),!e.disableHttp4xxError&&s.startsWith("4")&&r.setErrorTag(new HttpError(t.statusMessage)),r.setTag(HttpTags.HTTP_STATUS,t.statusCode)});const f=A.emit;return A.emit=function(t,s){if("socket"===t){1===A.listenerCount("response")&&A.on("response",t=>t.resume());const t=s._httpMessage;if(!e.maskHttpBody&&t._hasBody)try{let e;has(t,"outputData")?e=t.outputData[0].data.split("\n"):has(t,"output")&&(e=t.output[0].split("\n")),r.setTag(HttpTags.BODY,e[e.length-1])}catch(t){ThundraLogger.getInstance().debug(t)}}return f.apply(this,arguments)},A}catch(e){if(r&&r.close(),e instanceof ThundraChaosError)throw e;return ThundraLogger.getInstance().error(e),t.apply(this,[s,a])}}}this.wrapped&&this.unwrap(),has(s,"request")&&(shimmer.wrap(s,"request",wrapper),semver.satisfies(r,">=8")&&has(s,"get")&&shimmer.wrap(s,"get",wrapper)),semver.satisfies(r,">=9")&&has(a,"request")&&has(a,"get")&&(shimmer.wrap(a,"request",wrapper),shimmer.wrap(a,"get",wrapper)),this.wrapped=!0}unwrap(){const t=this.lib[0],e=this.lib[1],s=process.version;has(t,"request")&&(shimmer.unwrap(t,"request"),semver.satisfies(s,">=8")&&has(t,"get")&&shimmer.unwrap(t,"get")),semver.satisfies(s,">=9")&&has(e,"request")&&has(e,"get")&&(shimmer.unwrap(e,"request"),shimmer.unwrap(e,"get")),this.wrapped=!1}}const semver$1=require("semver");class ModuleVersionValidator{constructor(){this.moduleMap=new Map}validateModuleVersion(t,e){try{if(t){let s=this.moduleMap.get(t);if(!s){const e=`${t}/package.json`;s=fs.readFileSync(e,"utf8"),this.moduleMap.set(t,s)}const a=JSON.parse(s).version;return semver$1.satisfies(a,e)}return!1}catch(t){return!1}}}const shimmer$1=require("shimmer"),has$1=require("lodash.has"),moduleName="pg";class PostgreIntegration{constructor(t){if(this.version="6.x || 7.x",this.wrapped=!1,this.lib=Utils.tryRequire(moduleName),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version. for ${moduleName} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}getStatement(t){let e,s;return"string"==typeof t[0]?e=t[0]:"object"==typeof t[0]&&(e=t[0].text),t[1]instanceof Array?s=t[1]:"object"==typeof t[0]&&(s=t[0].values),s&&(e=Utils.replaceArgs(e,s)),e}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$1(t,"Client.prototype.query")&&(shimmer$1.wrap(t.Client.prototype,"query",function(t,a){return function(){let a;try{const r=s.config.tracer;if(!r)return t.apply(this,arguments);const i=InvocationSupport.getFunctionName(),n=r.getActiveSpan(),o=this.connectionParameters,p=this;a=r._startSpan(o.database,{childOf:n,domainName:DomainNames.DB,className:DBTypes.PG.toUpperCase(),disableActiveStart:!0}),o&&a.addTags({[SpanTags.SPAN_TYPE]:SpanTypes.RDB,[DBTags.DB_INSTANCE]:o.database,[DBTags.DB_USER]:o.user,[DBTags.DB_HOST]:o.host,[DBTags.DB_PORT]:o.port,[DBTags.DB_TYPE]:DBTypes.PG,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[i]});const c=[...arguments],h=c.length>0&&"function"==typeof c[c.length-1];let l=()=>{};h&&(l=c.pop());const u=(t,e)=>{t&&a.setErrorTag(t),a.closeWithCallback(p,l,[t,e])};c.push(u);const g=t.apply(this,c),d=s.getStatement(c);if(d){const t=d.split(" ")[0].toUpperCase();a.addTags({[DBTags.DB_STATEMENT_TYPE]:t,[DBTags.DB_STATEMENT]:e.maskRdbStatement?void 0:d,[SpanTags.OPERATION_TYPE]:SQLQueryOperationTypes[t]?SQLQueryOperationTypes[t]:""})}return a._initialized(),g}catch(e){if(a&&a.close(),e instanceof ThundraChaosError)throw e;ThundraLogger.getInstance().error(e),t.apply(this,arguments)}}}),this.wrapped=!0)}unwrap(){shimmer$1.unwrap(this.lib.Client.prototype,"query"),this.wrapped=!1}}const shimmer$2=require("shimmer"),has$2=require("lodash.has"),path=require("path"),moduleName$1="mysql2",fileName="lib/connection";class MySQL2Integration{constructor(t){if(this.version="^1.5",this.wrapped=!1,this.lib=Utils.tryRequire(path.join(moduleName$1,fileName)),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$1);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$1}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$1} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$2(t,"prototype.query")&&(shimmer$2.wrap(t.prototype,"query",function(t){let a;return function(r,i,n){try{const o=s.config.tracer;if(!o)return t.call(this,r,i,n);const p=this,c=InvocationSupport.getFunctionName(),h=o.getActiveSpan();(a=o._startSpan(this.config.database,{childOf:h,domainName:DomainNames.DB,className:ClassNames.MYSQL,disableActiveStart:!0})).addTags({[SpanTags.SPAN_TYPE]:SpanTypes.RDB,[DBTags.DB_INSTANCE]:this.config.database,[DBTags.DB_USER]:this.config.user,[DBTags.DB_HOST]:this.config.host,[DBTags.DB_PORT]:this.config.port,[DBTags.DB_TYPE]:DBTypes.MYSQL,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[c]});const l=t.call(this,r,i,n),u=l.sql;if(u){const t=u.split(" ")[0].toUpperCase();a.addTags({[DBTags.DB_STATEMENT_TYPE]:t,[DBTags.DB_STATEMENT]:e.maskRdbStatement?void 0:u,[SpanTags.OPERATION_TYPE]:SQLQueryOperationTypes[t]?SQLQueryOperationTypes[t]:""})}a._initialized();const g=l.onResult,d=(t,e)=>{t&&a.setErrorTag(t),a.closeWithCallback(p,g,[t,e])};return l.onResult?l.onResult=d:l.on("end",()=>{a.close()}),l}catch(e){if(a&&a.close(),e instanceof ThundraChaosError)throw e;ThundraLogger.getInstance().error(e),t.call(this,r,i,n)}}}),this.wrapped=!0)}unwrap(){shimmer$2.unwrap(this.lib.prototype,"query"),this.wrapped=!1}}const shimmer$3=require("shimmer"),has$3=require("lodash.has"),path$1=require("path"),moduleName$2="mysql",fileName$1="lib/Connection";class MySQLIntegration{constructor(t){if(this.version=">=2",this.wrapped=!1,this.lib=Utils.tryRequire(path$1.join(moduleName$2,fileName$1)),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$2);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$2}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$2} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$3(t,"prototype.query")&&(shimmer$3.wrap(t.prototype,"query",function(t){let a;return function(r,i,n){try{const o=s.config.tracer;if(!o)return t.call(this,r,i,n);const p=this,c=InvocationSupport.getFunctionName(),h=o.getActiveSpan();(a=o._startSpan(this.config.database,{childOf:h,domainName:DomainNames.DB,className:ClassNames.MYSQL,disableActiveStart:!0})).addTags({[SpanTags.SPAN_TYPE]:SpanTypes.RDB,[DBTags.DB_INSTANCE]:this.config.database,[DBTags.DB_USER]:this.config.user,[DBTags.DB_HOST]:this.config.host,[DBTags.DB_PORT]:this.config.port,[DBTags.DB_TYPE]:DBTypes.MYSQL,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[c]});const l=r;if(l){const t=l.split(" ")[0].toUpperCase();a.addTags({[DBTags.DB_STATEMENT_TYPE]:t,[DBTags.DB_STATEMENT]:e.maskRdbStatement?void 0:l,[SpanTags.OPERATION_TYPE]:SQLQueryOperationTypes[t]?SQLQueryOperationTypes[t]:""})}a._initialized();const u=t.call(this,r,i,n),g=u.onResult,d=(t,e)=>{t&&a.setErrorTag(t),a.closeWithCallback(p,g,[t,e])};return u.onResult?u.onResult=d:u.on("end",()=>{a.close()}),u}catch(e){if(a&&a.close(),e instanceof ThundraChaosError)throw e;ThundraLogger.getInstance().error(e),t.call(this,r,i,n)}}}),this.wrapped=!0)}unwrap(){shimmer$3.unwrap(this.lib.prototype,"query"),this.wrapped=!1}}const shimmer$4=require("shimmer"),has$4=require("lodash.has"),moduleName$3="redis";class RedisIntegration{constructor(t){if(this.wrapped=!1,this.version="^2.6",this.lib=Utils.tryRequire(moduleName$3),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$3);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$3}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$3} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$4(t,"RedisClient.prototype.internal_send_command")&&(shimmer$4.wrap(t.RedisClient.prototype,"internal_send_command",function(t){return function(a){let r;try{const i=s.config.tracer;if(!i)return t.call(this,a);if(!a)return t.call(this,a);const n=this,o=InvocationSupport.getFunctionName(),p=i.getActiveSpan();let c="localhost",h="6379",l="";this.connection_options&&(c=String(this.connection_options.host),h=String(this.connection_options.port),l=a.command.toUpperCase());const u=RedisCommandTypes[l]?RedisCommandTypes[l]:"";(r=i._startSpan(c,{childOf:p,domainName:DomainNames.CACHE,className:ClassNames.REDIS,disableActiveStart:!0,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.REDIS,[tags_21]:DBTypes.REDIS,[tags_19]:c,[DBTags.DB_STATEMENT_TYPE]:u,[RedisTags.REDIS_HOST]:c,[RedisTags.REDIS_PORT]:h,[RedisTags.REDIS_COMMAND]:e.maskRedisStatement?void 0:l,[RedisTags.REDIS_COMMAND_ARGS]:e.maskRedisStatement?void 0:a.args.join(","),[RedisTags.REDIS_COMMAND_TYPE]:u,[SpanTags.OPERATION_TYPE]:u,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[o]}}))._initialized();const g=a.callback,d=(t,e)=>{t&&r.setErrorTag(t),r.closeWithCallback(n,g,[t,e])};return a.callback=d,t.call(this,a)}catch(e){if(r&&r.close(),e instanceof ThundraChaosError)throw e;ThundraLogger.getInstance().error(e),t.call(this,a)}}}),this.wrapped=!0)}unwrap(){shimmer$4.unwrap(this.lib.RedisClient.prototype,"internal_send_command"),this.wrapped=!1}}const get=require("lodash.get"),moduleName$4="mongodb";class MongoDBIntegration{constructor(t){this.lib=Utils.tryRequire(moduleName$4),this.spans={},this.config=t,this.lib&&(this.listener=this.lib.instrument(),this.listener.on("started",this.onStarted.bind(this)),this.listener.on("succeeded",this.onSucceeded.bind(this)),this.listener.on("failed",this.onFailed.bind(this)))}onStarted(t){let e;try{const s=this.config.tracer;if(!s)return;const a=s.getActiveSpan(),r=InvocationSupport.getFunctionName(),i=get(t,"commandName",""),n=i.toUpperCase(),o=get(t.command,i,""),p=get(t,"databaseName",""),c=get(t,"connectionId","").split(":",2),h=c[0],l=2===c.length?c[1]:"",u=get(MongoDBCommandTypes,n,"");let g;this.config.maskMongoDBCommand||(g=JSON.stringify(t.command).substr(0,DefaultMongoCommandSizeLimit)),(e=s._startSpan(p,{childOf:a,domainName:DomainNames.DB,className:ClassNames.MONGODB,disableActiveStart:!0,tags:{[DBTags.DB_TYPE]:DBTypes.MONGODB,[DBTags.DB_HOST]:h,[DBTags.DB_PORT]:l,[DBTags.DB_INSTANCE]:p,[DBTags.DB_STATEMENT]:g,[MongoDBTags.MONGODB_COMMAND_NAME]:n,[MongoDBTags.MONGODB_COLLECTION]:o,[MongoDBTags.MONGODB_COMMAND]:g,[SpanTags.OPERATION_TYPE]:u,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[r]}}))._initialized(),this.spans[t.requestId]=e}catch(t){if(e&&e.close(),t instanceof ThundraChaosError)throw t;ThundraLogger.getInstance().error(t)}}onSucceeded(t){const e=get(this.spans,t.requestId,null);if(null!==e){delete this.spans[t.requestId];try{e.close()}catch(t){ThundraLogger.getInstance().error(t)}}}onFailed(t){const e=get(this.spans,t.requestId,null);if(null!==e){delete this.spans[t.requestId];try{e.setErrorTag(t.failure),e.close()}catch(t){ThundraLogger.getInstance().error(t)}}}wrap(){}unwrap(){}}const shimmer$5=require("shimmer"),has$5=require("lodash.has"),get$1=require("lodash.get"),moduleName$5="ioredis";class IORedisIntegration{constructor(t){if(this.wrapped=!1,this.version=">=2",this.lib=Utils.tryRequire(moduleName$5),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$5);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$5}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$5} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$5(t,"prototype.sendCommand")&&(shimmer$5.wrap(t.prototype,"sendCommand",function(t){return function(a){let r;try{const i=s.config.tracer;if(!i||!a||"ready"!==this.status)return t.call(this,a);const n=InvocationSupport.getFunctionName(),o=i.getActiveSpan(),p=get$1(this.options,"host","localhost"),c=get$1(this.options,"port","6379"),h=get$1(a,"name","").toUpperCase(),l=get$1(RedisCommandTypes,h,"");return(r=i._startSpan(p,{childOf:o,domainName:DomainNames.CACHE,className:ClassNames.REDIS,disableActiveStart:!0,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.REDIS,[tags_21]:DBTypes.REDIS,[tags_19]:p,[DBTags.DB_STATEMENT_TYPE]:l,[RedisTags.REDIS_HOST]:p,[RedisTags.REDIS_PORT]:c,[RedisTags.REDIS_COMMAND]:e.maskRedisStatement?void 0:h,[RedisTags.REDIS_COMMAND_ARGS]:e.maskRedisStatement?void 0:a.args.join(","),[RedisTags.REDIS_COMMAND_TYPE]:l,[SpanTags.OPERATION_TYPE]:l,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[n]}}))._initialized(),"function"==typeof a.callback&&(a.callback=s.patchEnd(r,a.callback)),"object"==typeof a.promise&&("function"==typeof a.promise.finally?a.promise.finally(s.patchEnd(r)):"function"==typeof a.promise.then&&a.promise.then(s.patchEnd(r)).catch(s.patchEnd(r))),t.call(this,a)}catch(e){if(r&&r.close(),e instanceof ThundraChaosError)throw e;return ThundraLogger.getInstance().error(e),t.call(this,a)}}}),this.wrapped=!0)}unwrap(){shimmer$5.unwrap(this.lib.prototype,"sendCommand"),this.wrapped=!1}patchEnd(t,e){return function(s){if(s instanceof Error&&t.setErrorTag(s),t.close(),"function"==typeof e)return e.apply(this,arguments)}}}class Resource{constructor(t={}){this.resourceType=t.resourceType,this.resourceName=t.resourceOperation,this.resourceOperation=t.resourceOperation,this.resourceCount=t.resourceCount,this.resourceErrorCount=t.resourceErrorCount,this.resourceErrors=t.resourceErrors?t.resourceErrors:[],this.resourceDuration=t.resourceDuration,this.resourceMaxDuration=t.resourceMaxDuration,this.resourceAvgDuration=t.resourceAvgDuration,this.resourceBlockedCount=t.resourceBlockedCount||0,this.resourceViolatedCount=t.resourceViolatedCount||0}init(t){this.resourceType=t.className,this.resourceName=t.operationName,this.resourceOperation=t.getTag(SpanTags.OPERATION_TYPE),this.resourceCount=1,this.resourceErrorCount=t.getTag("error")?1:0,t.getTag("error.kind")&&-1===this.resourceErrors.indexOf(t.getTag("error.kind"))&&this.resourceErrors.push(t.getTag("error.kind")),this.resourceDuration=t.getDuration(),this.resourceMaxDuration=t.getDuration(),this.resourceAvgDuration=t.getDuration(),this.resourceBlockedCount=t.getTag(SecurityTags.BLOCKED)?1:0,this.resourceViolatedCount=t.getTag(SecurityTags.VIOLATED)?1:0}merge(t){this.resourceType===t.resourceType&&this.resourceName===t.resourceName&&this.resourceOperation===t.resourceOperation&&(this.resourceCount+=t.resourceCount,this.resourceErrorCount+=t.resourceErrorCount,t.resourceErrors&&t.resourceErrors.forEach(t=>{t&&-1===this.resourceErrors.indexOf(t)&&this.resourceErrors.push(t)}),this.resourceDuration+=t.resourceDuration,this.resourceAvgDuration=Math.round(this.resourceDuration/this.resourceCount*100)/100,t.resourceMaxDuration>this.resourceMaxDuration&&(this.resourceMaxDuration=t.resourceMaxDuration),this.resourceBlockedCount+=t.resourceBlockedCount,this.resourceViolatedCount+=t.resourceViolatedCount)}generateId(){return`${this.resourceType.toUpperCase()}$${this.resourceName}$${this.resourceOperation}`}}const flatten=require("lodash.flatten");class InvocationTraceSupport{static getResources(t=""){try{const e=InvocationTraceSupport.tracer;if(!e)return;const s=new Map,a=e.recorder.getSpanList().filter(t=>t.getTag(SpanTags.TOPOLOGY_VERTEX)).filter(e=>e.spanContext.spanId!==t);for(const t of a){const e=InvocationTraceSupport.generateResourceIdFromSpan(t);if(e){const a=s.get(e),r=new Resource;r.init(t),a?a.merge(r):s.set(e,r)}}return Array.from(s.values())}catch(t){ThundraLogger.getInstance().error(`Error while creating the resources data for invocation. ${t}`)}}static generateResourceIdFromSpan(t){if(t.className&&t.operationName){let e=`${t.className.toUpperCase()}$${t.operationName}`;return t.getTag(SpanTags.OPERATION_TYPE)&&(e+=`$${t.getTag(SpanTags.OPERATION_TYPE)}`),e}}static addIncomingTraceLink(t){InvocationTraceSupport.incomingTraceLinks.push(t)}static addIncomingTraceLinks(t){InvocationTraceSupport.incomingTraceLinks.push(...t)}static getIncomingTraceLinks(){return[...new Set(InvocationTraceSupport.incomingTraceLinks)].filter(t=>t)}static addOutgoingTraceLink(t){InvocationTraceSupport.outgoingTraceLinks.push(t)}static addOutgoingTraceLinks(t){InvocationTraceSupport.outgoingTraceLinks.push(...t)}static getOutgoingTraceLinks(){const t=InvocationTraceSupport.tracer;if(t)try{const e=t.recorder.getSpanList(),s=flatten(e.filter(t=>t.getTag(SpanTags.TRACE_LINKS)).map(t=>t.getTag(SpanTags.TRACE_LINKS)));return s.push(...InvocationTraceSupport.outgoingTraceLinks),[...new Set(s)]}catch(t){ThundraLogger.getInstance().error(`Error while getting the outgoing trace links for invocation. ${t}`)}}static clear(){InvocationTraceSupport.incomingTraceLinks=[],InvocationTraceSupport.outgoingTraceLinks=[]}}InvocationTraceSupport.incomingTraceLinks=[],InvocationTraceSupport.outgoingTraceLinks=[];const get$2=require("lodash.get");class LambdaEventUtils{static getLambdaEventType(t,e){return t.Records&&Array.isArray(t.Records)&&t.Records[0]&&t.Records[0].kinesis?LambdaEventType.Kinesis:t.deliveryStreamArn&&Array.isArray(t.records)?LambdaEventType.FireHose:t.Records&&Array.isArray(t.Records)&&t.Records[0]&&t.Records[0].dynamodb?LambdaEventType.DynamoDB:t.Records&&Array.isArray(t.Records)&&t.Records[0]&&"aws:sns"===t.Records[0].EventSource?LambdaEventType.SNS:t.Records&&Array.isArray(t.Records)&&t.Records[0]&&"aws:sqs"===t.Records[0].eventSource?LambdaEventType.SQS:t.Records&&Array.isArray(t.Records)&&t.Records[0]&&t.Records[0].s3?LambdaEventType.S3:t["detail-type"]&&"Scheduled Event"===t["detail-type"]&&Array.isArray(t.resources)?LambdaEventType.CloudWatchSchedule:t.awslogs&&t.awslogs.data?LambdaEventType.CloudWatchLog:t.Records&&Array.isArray(t.Records)&&t.Records[0]&&t.Records[0].cf?LambdaEventType.CloudFront:t.requestContext&&t.resource&&t.path?LambdaEventType.APIGatewayProxy:t.context&&t.context.stage&&t.context["resource-path"]?LambdaEventType.APIGatewayPassThrough:e.clientContext?LambdaEventType.Lambda:void 0}static injectTriggerTagsForKinesis(t,e){const s=DomainNames.STREAM,a=ClassNames.KINESIS,r=[],i=new Set;for(const t of e.Records){const e=t.awsRegion||"",s=t.eventID||!1,a=t.eventSourceARN,n=a.substring(a.indexOf("/")+1);i.add(n),s&&r.push(`${e}:${n}:${s}`)}return InvocationTraceSupport.addIncomingTraceLinks(r),this.injectTrigerTragsForInvocation(s,a,Array.from(i)),this.injectTrigerTragsForSpan(t,s,a,Array.from(i)),a}static injectTriggerTagsForFirehose(t,e){const s=DomainNames.STREAM,a=ClassNames.FIREHOSE,r=e.deliveryStreamArn,i=r.substring(r.indexOf("/")+1),n=e.region||"",o=e.records||[],p=[];for(const t of o){const e=t.approximateArrivalTimestamp,s=t.data;if(e&&s){const t=Math.floor(e/1e3)-1;p.push(...AWSIntegration.generateFirehoseTraceLinks(n,i,t,Buffer.from(s,"base64")))}}return InvocationTraceSupport.addIncomingTraceLinks(p),this.injectTrigerTragsForInvocation(s,a,[i]),this.injectTrigerTragsForSpan(t,s,a,[i]),a}static injectTriggerTagsForDynamoDB(t,e){const s=DomainNames.DB,a=ClassNames.DYNAMODB,r=[],i=new Set;for(const t of e.Records){const e=t.eventSourceARN,s=e.indexOf("/"),a=e.indexOf("/",s+1),n=e.substring(s+1,a),o=t.awsRegion||"";i.add(n);let p=!1;if("INSERT"===t.eventName||"MODIFY"===t.eventName){const e=get$2(t,"dynamodb.NewImage.x-thundra-span-id",!1);e&&(p=!0,r.push(`SAVE:${e}`))}else if("REMOVE"===t.eventName){const e=get$2(t,"dynamodb.OldImage.x-thundra-span-id",!1);e&&(p=!0,r.push(`DELETE:${e}`))}if(!p){const e=get$2(t,"dynamodb.ApproximateCreationDateTime",!1);if(e){const s=get$2(t,"dynamodb.NewImage",{}),a=get$2(t,"dynamodb.Keys",{}),i=e-1;"INSERT"===t.eventName||"MODIFY"===t.eventName?(r.push(...AWSIntegration.generateDynamoTraceLinks(s,"SAVE",n,o,i)),r.push(...AWSIntegration.generateDynamoTraceLinks(a,"SAVE",n,o,i))):"REMOVE"===t.eventName&&r.push(...AWSIntegration.generateDynamoTraceLinks(a,"DELETE",n,o,i))}}}return InvocationTraceSupport.addIncomingTraceLinks(r),this.injectTrigerTragsForInvocation(s,a,Array.from(i)),this.injectTrigerTragsForSpan(t,s,a,Array.from(i)),a}static injectTriggerTagsForSNS(t,e){const s=DomainNames.MESSAGING,a=ClassNames.SNS,r=[],i=new Set;for(const t of e.Records){const e=t.Sns.TopicArn,s=e.substring(e.lastIndexOf(":")+1),a=t.Sns.MessageId;i.add(s),r.push(a)}return InvocationTraceSupport.addIncomingTraceLinks(r),this.injectTrigerTragsForInvocation(s,a,Array.from(i)),this.injectTrigerTragsForSpan(t,s,a,Array.from(i)),a}static injectTriggerTagsForSQS(t,e){const s=DomainNames.MESSAGING,a=ClassNames.SQS,r=[],i=new Set;for(const t of e.Records){const e=t.eventSourceARN,s=e.substring(e.lastIndexOf(":")+1),a=t.messageId;i.add(s),r.push(a)}return InvocationTraceSupport.addIncomingTraceLinks(r),this.injectTrigerTragsForInvocation(s,a,Array.from(i)),this.injectTrigerTragsForSpan(t,s,a,Array.from(i)),a}static injectTriggerTagsForS3(t,e){const s=DomainNames.STORAGE,a=ClassNames.S3,r=[],i=new Set;for(const t of e.Records){const e=t.s3.bucket.name,s=get$2(t,"responseElements.x-amz-request-id",!1);i.add(e),s&&r.push(s)}return InvocationTraceSupport.addIncomingTraceLinks(r),this.injectTrigerTragsForInvocation(s,a,Array.from(i)),this.injectTrigerTragsForSpan(t,s,a,Array.from(i)),a}static injectTriggerTagsForCloudWatchSchedule(t,e){const s=DomainNames.SCHEDULE,a=ClassNames.CLOUDWATCH,r=new Set;for(const t of e.resources){const e=t.substring(t.indexOf("/")+1);r.add(e)}return this.injectTrigerTragsForInvocation(s,a,Array.from(r)),this.injectTrigerTragsForSpan(t,s,a,Array.from(r)),a}static injectTriggerTagsForCloudWatchLogs(t,e){try{const s=Buffer.from(e.awslogs.data,"base64"),a=JSON.parse(zlib$1.gunzipSync(s).toString("utf-8")),r="Log",i="AWS-CloudWatch-Log";return this.injectTrigerTragsForInvocation(r,i,[a.logGroup]),this.injectTrigerTragsForSpan(t,r,i,[a.logGroup]),i}catch(t){ThundraLogger.getInstance().error("Cannot read CloudWatch log data. "+t)}}static injectTriggerTagsForCloudFront(t,e){const s=DomainNames.CDN,a=ClassNames.CLOUDFRONT,r=new Set;for(const t of e.Records){const e=t.cf.request.uri;r.add(e)}return this.injectTrigerTragsForInvocation(s,a,Array.from(r)),this.injectTrigerTragsForSpan(t,s,a,Array.from(r)),a}static injectTriggerTagsForAPIGatewayProxy(t,e){const s=DomainNames.API,a=ClassNames.APIGATEWAY,r=e.resource,i=get$2(e,"headers.x-thundra-span-id",!1);return i&&InvocationTraceSupport.addIncomingTraceLinks([i]),this.injectTrigerTragsForInvocation(s,a,[r]),this.injectTrigerTragsForSpan(t,s,a,[r]),a}static injectTriggerTagsForAPIGatewayPassThrough(t,e){const s=DomainNames.API,a=ClassNames.APIGATEWAY,r=get$2(e,"params.header.Host","")+"/"+e.context.stage+e.context["resource-path"];return this.injectTrigerTragsForInvocation(s,a,[r]),this.injectTrigerTragsForSpan(t,s,a,[r]),a}static injectTriggerTagsForLambda(t,e){if(e&&e.clientContext&&e.clientContext.custom&&e.clientContext.custom[LambdaEventUtils.LAMBDA_TRIGGER_OPERATION_NAME]){const s=DomainNames.API,a=ClassNames.LAMBDA,r=[e.clientContext.custom[LambdaEventUtils.LAMBDA_TRIGGER_OPERATION_NAME]],i=e.awsRequestId;return InvocationTraceSupport.addIncomingTraceLinks([i]),this.injectTrigerTragsForInvocation(s,a,r),this.injectTrigerTragsForSpan(t,s,a,r),a}}static extractSpanContextFromSNSEvent(t,e){let s;for(const a of e.Records){const e={},r=a.Sns.MessageAttributes;for(const t of Object.keys(r)){const s=r[t];"String"===s.Type&&(e[t]=s.Value)}const i=t.extract(void 0,e);if(!i)return;if(s){if(s.traceId!==i.traceId&&s.transactionId!==i.transactionId&&s.spanId!==i.spanId)return}else s=i}return s}static extractSpanContextFromSQSEvent(t,e){let s;for(const a of e.Records){const e={},r=a.messageAttributes;for(const t of Object.keys(r)){const s=r[t];"String"===s.dataType&&(e[t]=s.stringValue)}const i=t.extract(void 0,e);if(!i)return;if(s){if(s.traceId!==i.traceId&&s.transactionId!==i.transactionId&&s.spanId!==i.spanId)return}else s=i}return s}static injectTrigerTragsForInvocation(t,e,s){InvocationSupport.setAgentTag(SpanTags.TRIGGER_DOMAIN_NAME,t),InvocationSupport.setAgentTag(SpanTags.TRIGGER_CLASS_NAME,e),InvocationSupport.setAgentTag(SpanTags.TRIGGER_OPERATION_NAMES,s)}static injectTrigerTragsForSpan(t,e,s,a){t.setTag(SpanTags.TRIGGER_DOMAIN_NAME,e),t.setTag(SpanTags.TRIGGER_CLASS_NAME,s),t.setTag(SpanTags.TRIGGER_OPERATION_NAMES,a)}}var LambdaEventType;LambdaEventUtils.LAMBDA_TRIGGER_OPERATION_NAME="x-thundra-lambda-trigger-operation-name",function(t){t[t.Kinesis=0]="Kinesis",t[t.FireHose=1]="FireHose",t[t.DynamoDB=2]="DynamoDB",t[t.SNS=3]="SNS",t[t.SQS=4]="SQS",t[t.S3=5]="S3",t[t.CloudWatchSchedule=6]="CloudWatchSchedule",t[t.CloudWatchLog=7]="CloudWatchLog",t[t.CloudFront=8]="CloudFront",t[t.APIGatewayProxy=9]="APIGatewayProxy",t[t.APIGatewayPassThrough=10]="APIGatewayPassThrough",t[t.Lambda=11]="Lambda"}(LambdaEventType||(LambdaEventType={}));const AWSOperationTypes={exclusions:{"AWS-Lambda":{ListTags:"READ",TagResource:"WRITE",UntagResource:"WRITE",EnableReplication:"PERMISSION",InvokeAsync:"WRITE",Invoke:"WRITE"},"AWS-S3":{HeadBucket:"LIST",ListBucketByTags:"READ",ListBucketMultipartUploads:"READ",ListBucketVersions:"READ",ListJobs:"READ",ListMultipartUploadParts:"READ",GetBucketTagging:"READ",GetObjectVersionTagging:"READ",GetObjectTagging:"READ",GetBucketObjectLockConfiguration:"WRITE",GetObjectLegalHold:"WRITE",GetObjectRetention:"WRITE",DeleteObjectTagging:"TAGGING",DeleteObjectVersionTagging:"TAGGING",PutBucketTagging:"TAGGING",PutObjectTagging:"TAGGING",PutObjectVersionTagging:"TAGGING",AbortMultipartUpload:"WRITE",ReplicateDelete:"WRITE",ReplicateObject:"WRITE",RestoreObject:"WRITE",DeleteBucketPolicy:"PERMISSION",ObjectOwnerOverrideToBucketOwner:"PERMISSION",PutAccountPublicAccessBlock:"PERMISSION",PutBucketAcl:"PERMISSION",PutBucketPolicy:"PERMISSION",PutBucketPublicAccessBlock:"PERMISSION",PutObjectAcl:"PERMISSION",PutObjectVersionAcl:"PERMISSION",deleteBucket:"WRITE",CreateBucket:"WRITE",CopyObject:"WRITE",DeleteObject:"WRITE",DeleteObjects:"WRITE",GetObject:"READ",GetObjects:"READ",ListBuckets:"LIST",PutObject:"WRITE",GetBucketAcl:"READ",GetObjectAcl:"READ",GetSignedUrl:"READ",HeadObject:"READ",ListObjects:"READ",ListObjectsV2:"READ"},"AWS-SNS":{ListPhoneNumbersOptedOut:"READ",ListTagsForResource:"READ",CheckIfPhoneNumberIsOptedOut:"READ",UntagResource:"TAGGING",ConfirmSubscription:"WRITE",OptInPhoneNumber:"WRITE",Subscribe:"WRITE",Unsubscribe:"WRITE",Write:"WRITE",Publish:"WRITE"},"AWS-Athena":{BatchGetNamedQuery:"READ",BatchGetQueryExecution:"READ",ListTagsForResource:"LIST",CreateWorkGroup:"WRITE",UntagResource:"TAGGING",TagResource:"TAGGING",CancelQueryExecution:"WRITE",RunQuery:"WRITE",StartQueryExecution:"WRITE",StopQueryExecution:"WRITE",CreateNamedQuery:"WRITE",DeleteNamedQuery:"WRITE",DeleteWorkGroup:"WRITE",GetNamedQuery:"READ",GetQueryExecution:"READ",GetQueryResults:"READ",GetWorkGroup:"READ",ListNamedQueries:"READ",ListQueryExecutions:"READ",ListWorkGroups:"READ",UpdateWorkGroup:"WRITE"},"AWS-Kinesis":{ListTagsForStream:"READ",SubscribeToShard:"READ",AddTagsToStream:"TAGGING",RemoveTagsFromStream:"TAGGING",DecreaseStreamRetentionPeriod:"WRITE",DeregisterStreamConsumer:"WRITE",DisableEnhancedMonitoring:"WRITE",EnableEnhancedMonitoring:"WRITE",IncreaseStreamRetentionPeriod:"WRITE",MergeShards:"WRITE",RegisterStreamConsumer:"WRITE",SplitShard:"WRITE",UpdateShardCount:"WRITE",GetRecords:"READ",PutRecords:"WRITE",PutRecord:"WRITE"},"AWS-Firehose":{DescribeDeliveryStream:"LIST",StartDeliveryStreamEncryption:"WRITE",StopDeliveryStreamEncryption:"WRITE",TagDeliveryStream:"WRITE",UntagDeliveryStream:"WRITE",PutRecordBatch:"WRITE",PutRecord:"WRITE"},"AWS-SQS":{ListDeadLetterSourceQueues:"READ",ListQueueTags:"READ",ReceiveMessage:"READ",TagQueue:"TAGGING",UntagQueue:"TAGGING",PurgeQueue:"WRITE",SetQueueAttributes:"WRITE",SendMessage:"WRITE",SendMessageBatch:"WRITE",DeleteMessage:"WRITE",DeleteMessageBatch:"WRITE"},"AWS-DynamoDB":{BatchGetItem:"READ",ConditionCheckItem:"READ",ListStreams:"READ",ListTagsOfResource:"READ",Query:"READ",Scan:"READ",TagResource:"TAGGING",UntagResource:"TAGGING",BatchWriteItem:"WRITE",PurchaseReservedCapacityOfferings:"WRITE",RestoreTableFromBackup:"WRITE",RestoreTableToPointInTime:"WRITE",CreateTable:"WRITE",CreateGlobalTable:"WRITE",DeleteItem:"WRITE",DeleteTable:"WRITE",GetItem:"READ",PutItem:"WRITE",UpdateItem:"WRITE"}},patterns:{"^List.*$":"LIST","^Get.*$":"READ","^Create.*$":"WRITE","^Delete.*$":"WRITE","^Invoke.*$":"WRITE","^Publish.*$":"WRITE","^Put.*$":"WRITE","^Update.*$":"WRITE","^Describe.*$":"READ","^Change.*$":"WRITE","^Send.*$":"WRITE","^.*Permission$":"PERMISSION","^.*Tagging$":"TAGGING","^.*Tags$":"TAGGING","^Set.*$":"WRITE"}},shimmer$6=require("shimmer"),Hook=require("require-in-the-middle"),md5=require("md5"),has$6=require("lodash.has"),trim=require("lodash.trim"),get$3=require("lodash.get"),thundraWrapped="__thundra_wrapped",moduleName$6="aws-sdk",resolvePaths=["/var/task"];class AWSIntegration{constructor(t){if(this.version="2.x",this.wrappedFuncs={},this.config=t,this.lib=Utils.tryRequire(moduleName$6,resolvePaths),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$6,resolvePaths);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$6}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$6} integration.\n Supported version is ${this.version}`);this.basedir=e,this.wrap.call(this,this.lib,t)}this.config.instrumentAWSOnLoad&&(this.hook=Hook("aws-sdk",{internals:!0},(e,s,a)=>{if("aws-sdk"===s){(new ModuleVersionValidator).validateModuleVersion(a,this.version)?(this.lib=e,this.basedir=a,this.wrap.call(this,e,t)):ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$6} integration.\n Supported version is ${this.version}`)}return e}))}static injectSpanContextIntoMessageAttributes(t,e){if("true"!==Utils.getConfiguration(envVariableKeys.DISABLE_SPAN_CONTEXT_INJECTION)){const s={};t.inject(e.spanContext,void 0,s);const a={};for(const t of Object.keys(s))a[t]={DataType:"String",StringValue:s[t]};return a}}static injectSpanContexIntoLambdaClientContext(t,e){if("true"!==Utils.getConfiguration(envVariableKeys.DISABLE_SPAN_CONTEXT_INJECTION)){const s={};return t.inject(e.spanContext,void 0,s),s}}static injectDynamoDBTraceLinkOnPut(t,e){const s=e.spanContext.spanId;t.Item=Object.assign({},{"x-thundra-span-id":{S:s}},t.Item),e.setTag(SpanTags.TRACE_LINKS,[`SAVE:${s}`])}static injectDynamoDBTraceLinkOnUpdate(t,e){const s=e.spanContext.spanId;if(has$6(t,"AttributeUpdates")){const a={Action:"PUT",Value:{S:s}};t.AttributeUpdates=Object.assign({},{"x-thundra-span-id":a},t.AttributeUpdates),e.setTag(SpanTags.TRACE_LINKS,[`SAVE:${s}`])}else if(has$6(t,"UpdateExpression")){const a=t.UpdateExpression,r={"#xThundraSpanId":"x-thundra-span-id"},i={":xThundraSpanId":{S:s}};t.ExpressionAttributeNames=Object.assign({},t.ExpressionAttributeNames,r),t.ExpressionAttributeValues=Object.assign({},t.ExpressionAttributeValues,i),a.indexOf("SET")<0?t.UpdateExpression=`SET #xThundraSpanId = :xThundraSpanId ${a}`:t.UpdateExpression=a.replace(/SET (.+)/,"SET #xThundraSpanId = :xThundraSpanId, $1"),e.setTag(SpanTags.TRACE_LINKS,[`SAVE:${s}`])}}static serializeAttributes(t){return Object.keys(t).sort().map(e=>{const s=Object.keys(t[e])[0];return`${e}={${s}: ${trim(JSON.stringify(t[e][s]),'"')}}`}).join(", ")}static injectDynamoDBTraceLinkOnDelete(t){t.ReturnValues="ALL_OLD"}static generateDynamoTraceLinks(t,e,s,a,r){if(t){const i=md5(AWSIntegration.serializeAttributes(t));return[0,1,2].map(t=>`${a}:${s}:${r+t}:${e}:${i}`)}return[]}static generateFirehoseTraceLinks(t,e,s,a){try{if(a){const r=md5(a);return[0,1,2].map(a=>`${t}:${e}:${s+a}:${r}`)}}catch(t){}return[]}static getOperationType(t,e){const s=AWSIntegration.AWSOperationTypes;if(!s)return"";const{exclusions:a,patterns:r}=s;if(t=Utils.capitalize(t),has$6(a,`${e}.${t}`))return get$3(a,`${e}.${t}`);for(const e of r)if(e.expression.test(t))return e.operationType;return""}static parseAWSOperationTypes(){if(!AWSIntegration.AWSOperationTypes){AWSIntegration.AWSOperationTypes={exclusions:AWSOperationTypes.exclusions,patterns:[]};for(const t in AWSOperationTypes.patterns){const e=AWSOperationTypes.patterns[t];AWSIntegration.AWSOperationTypes.patterns.push({expression:new RegExp(t,"i"),operationType:e})}}}static injectTraceLink(t,e,s){try{if(t.getTag(SpanTags.TRACE_LINKS)||!e)return;const a=get$3(e,"service.config.region",""),r=get$3(e,"service.config.endpoint",""),i=Utils.getServiceName(r),n=e.operation,o=e.response,p=Object.assign({},e.params);let c=[];if("dynamodb"===i){const t=Utils.getDynamoDBTableName(e);let r;if(r=has$6(o,"httpResponse.headers.date")?Date.parse(o.httpResponse.headers.date)/1e3:Math.floor(Date.now()/1e3)-1,"putItem"===n)c=AWSIntegration.generateDynamoTraceLinks(p.Item,"SAVE",t,a,r);else if("updateItem"===n)c=AWSIntegration.generateDynamoTraceLinks(p.Key,"SAVE",t,a,r);else if("deleteItem"===n)if(s.dynamoDBTraceInjectionEnabled&&has$6(o,"data.Attributes.x-thundra-span-id")){const t=o.data.Attributes["x-thundra-span-id"];c=[`DELETE:${t}`]}else c=AWSIntegration.generateDynamoTraceLinks(p.Key,"DELETE",t,a,r)}else if("sqs"===i){if("sendMessage"===n){const t=o.data.MessageId||"";c=[t]}else if("sendMessageBatch"===n){(o.data.Successful||[]).map(t=>c.push(t.MessageId))}}else if("sns"===i){const t=get$3(o,"data.MessageId",!1);t&&(c=[t])}else if("kinesis"===i){const t=get$3(o,"data.Records",!1),e=p.StreamName||"";if(t)for(const s of t){const t=get$3(s,"ShardId",!1),r=get$3(s,"SequenceNumber",!1);t&&r&&c.push(`${a}:${e}:${t}:${r}`)}else{const t=get$3(o,"data.ShardId",!1),s=get$3(o,"data.SequenceNumber",!1);t&&s&&(c=[`${a}:${e}:${t}:${s}`])}}else if("s3"===i){const t=get$3(o,"httpResponse.headers.x-amz-request-id",!1);t&&(c=[t])}else if("lambda"===i){const t=get$3(o,"httpResponse.headers.x-amzn-requestid",!1);t&&(c=[t])}else if("firehose"===i){const t=p.DeliveryStreamName||"";let e;if(e=has$6(o,"httpResponse.headers.date")?Date.parse(o.httpResponse.headers.date)/1e3:Math.floor(Date.now()/1e3)-1,"putRecord"===n){const s=get$3(p,"Record.Data",!1);s&&(c=AWSIntegration.generateFirehoseTraceLinks(a,t,e,s))}else if("putRecordBatch"===n){const s=p.Records||[];for(const r of s){const s=r.Data;s&&c.push(...AWSIntegration.generateFirehoseTraceLinks(a,t,e,s))}}}else"athena"===i&&(has$6(o,"data.QueryExecutionIds")&&t.setTag(AwsAthenaTags.RESPONSE_QUERY_EXECUTION_IDS,o.data.QueryExecutionIds),has$6(o,"data.QueryExecutionId")&&t.setTag(AwsAthenaTags.REQUEST_QUERY_EXECUTION_IDS,[o.data.QueryExecutionId]),has$6(o,"data.NamedQueryIds")&&t.setTag(AwsAthenaTags.RESPONSE_NAMED_QUERY_IDS,o.data.NamedQueryIds),has$6(o,"data.NamedQueryId")&&t.setTag(AwsAthenaTags.RESPONSE_NAMED_QUERY_IDS,[o.data.NamedQueryId]));c.length>0&&t.setTag(SpanTags.TRACE_LINKS,c)}catch(t){ThundraLogger.getInstance().debug(`Error while injecting trace links, ${t}`)}}wrap(t,e){AWSIntegration.parseAWSOperationTypes();const s=this;function wrapper(t,a){return s.wrappedFuncs[a]=t,function(r){let i;try{const n=s.config.tracer;if(!n)return t.apply(this,[r]);const o=this,p=o.service.config.endpoint,c=Utils.getServiceName(p),h=n.getActiveSpan(),l=r,u=InvocationSupport.getFunctionName();o.params=o.params?o.params:{};const g=o.operation?o.operation:AWS_SERVICE_REQUEST;if("sqs"===c){const t=AWSIntegration.getOperationType(g,ClassNames.SQS);let s=Utils.getQueueName(o.params.QueueUrl);const a=(s=s?s.substring(s.lastIndexOf("/")+1):s)||AWS_SERVICE_REQUEST;i=n._startSpan(a,{childOf:h,domainName:DomainNames.MESSAGING,className:ClassNames.SQS,disableActiveStart:!0,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.AWS_SQS,[AwsSDKTags.REQUEST_NAME]:g,[SpanTags.OPERATION_TYPE]:t}}),t&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsSQSTags.QUEUE_NAME,s));const r=AWSIntegration.injectSpanContextIntoMessageAttributes(n,i);if("sendMessage"===g){if(r){const t=o.params.MessageAttributes||{};o.params.MessageAttributes=Object.assign({},t,r)}e.maskSQSMessage||i.setTag(AwsSQSTags.MESSAGE,o.params.MessageBody)}else if("sendMessageBatch"===g&&o.params.Entries&&Array.isArray(o.params.Entries)){const t=[];for(const e of o.params.Entries){if(r){const t=e.MessageAttributes?e.MessageAttributes:{};e.MessageAttributes=Object.assign({},t,r)}t.push(e.MessageBody)}e.maskSQSMessage||i.setTag(AwsSQSTags.MESSAGES,t)}}else if("sns"===c){const t=AWSIntegration.getOperationType(g,ClassNames.SNS);let s=null,a=null,r=null,p=null;if(o.params.TopicArn&&(s=a=o.params.TopicArn.substring(o.params.TopicArn.lastIndexOf(":")+1)),!s&&o.params.TargetArn&&(s=r=o.params.TargetArn.substring(o.params.TargetArn.lastIndexOf(":")+1)),!s&&o.params.PhoneNumber&&(s=p=o.params.PhoneNumber),s=s||AWS_SERVICE_REQUEST,i=n._startSpan(s,{childOf:h,domainName:DomainNames.MESSAGING,className:ClassNames.SNS,disableActiveStart:!0,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.AWS_SNS,[AwsSDKTags.REQUEST_NAME]:g,[SpanTags.OPERATION_TYPE]:t}}),t&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),a&&i.setTag(AwsSNSTags.TOPIC_NAME,a),r&&i.setTag(AwsSNSTags.TARGET_NAME,r),p&&i.setTag(AwsSNSTags.SMS_PHONE_NUMBER,p),e&&!e.maskSNSMessage&&i.setTag(AwsSNSTags.MESSAGE,o.params.Message)),"publish"===g){const t=AWSIntegration.injectSpanContextIntoMessageAttributes(n,i);if(t){const e=o.params.MessageAttributes?o.params.MessageAttributes:{};o.params.MessageAttributes=Object.assign({},e,t)}}}else if("dynamodb"===c){const t=Utils.getDynamoDBTableName(o),s=AWSIntegration.getOperationType(g,ClassNames.DYNAMODB),a=t||AWS_SERVICE_REQUEST;i=n._startSpan(a,{childOf:h,domainName:DomainNames.DB,className:ClassNames.DYNAMODB,disableActiveStart:!0,tags:{[tags_21]:DBTypes.DYNAMODB,[tags_19]:p,[DBTags.DB_STATEMENT_TYPE]:s,[SpanTags.OPERATION_TYPE]:s,[SpanTags.SPAN_TYPE]:SpanTypes.AWS_DYNAMO,[AwsSDKTags.REQUEST_NAME]:g,[DBTags.DB_STATEMENT]:e.maskDynamoDBStatement?void 0:Object.assign({},o.params)}}),s&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsDynamoTags.TABLE_NAME,t)),e.dynamoDBTraceInjectionEnabled&&("putItem"===g?AWSIntegration.injectDynamoDBTraceLinkOnPut(o.params,i):"updateItem"===g?AWSIntegration.injectDynamoDBTraceLinkOnUpdate(o.params,i):"deleteItem"===g&&AWSIntegration.injectDynamoDBTraceLinkOnDelete(o.params))}else if("s3"===c){const t=AWSIntegration.getOperationType(g,ClassNames.S3),e=get$3(o,"params.Bucket",AWS_SERVICE_REQUEST);i=n._startSpan(e,{childOf:h,domainName:DomainNames.STORAGE,className:ClassNames.S3,disableActiveStart:!0,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.AWS_S3,[SpanTags.OPERATION_TYPE]:t,[AwsS3Tags.BUCKET_NAME]:o.params.Bucket,[AwsSDKTags.REQUEST_NAME]:g}}),t&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsS3Tags.OBJECT_NAME,o.params.Key))}else if("lambda"===c){const t=AWSIntegration.getOperationType(g,ClassNames.LAMBDA),s=get$3(o,"params.FunctionName",AWS_SERVICE_REQUEST);i=n._startSpan(s,{childOf:h,disableActiveStart:!0,domainName:DomainNames.API,className:ClassNames.LAMBDA,tags:{[SpanTags.SPAN_TYPE]:SpanTypes.AWS_LAMBDA,[SpanTags.OPERATION_TYPE]:t,[AwsLambdaTags.FUNCTION_QUALIFIER]:o.params.Qualifier,[AwsLambdaTags.INVOCATION_PAYLOAD]:e.maskLambdaPayload?void 0:o.params.Payload,[AwsSDKTags.REQUEST_NAME]:g,[AwsLambdaTags.INVOCATION_TYPE]:o.params.InvocationType}});const a=AWSIntegration.injectSpanContexIntoLambdaClientContext(n,i);if(t&&(a[LambdaEventUtils.LAMBDA_TRIGGER_OPERATION_NAME]=u,i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsLambdaTags.FUNCTION_NAME,s)),a&&g&&g.includes&&g.includes("invoke"))if(o.params.ClientContext){const t=Buffer.from(o.params.ClientContext,"base64").toString("utf8");try{const e=JSON.parse(t);e.custom=a,o.params.ClientContext=Buffer.from(JSON.stringify({custom:e})).toString("base64")}catch(t){ThundraLogger.getInstance().debug("Cannot parse lambda client context not a valid JSON")}}else o.params.ClientContext=Buffer.from(JSON.stringify({custom:a})).toString("base64")}else if("kinesis"===c){const t=AWSIntegration.getOperationType(g,ClassNames.KINESIS),e=get$3(o,"params.StreamName",AWS_SERVICE_REQUEST);i=n._startSpan(e,{childOf:h,domainName:DomainNames.STREAM,className:ClassNames.KINESIS,disableActiveStart:!0,tags:{[SpanTags.OPERATION_TYPE]:t,[SpanTags.SPAN_TYPE]:SpanTypes.AWS_KINESIS,[AwsSDKTags.REQUEST_NAME]:g}}),o.params.StreamName&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsKinesisTags.STREAM_NAME,o.params.StreamName))}else if("firehose"===c){const t=AWSIntegration.getOperationType(g,ClassNames.FIREHOSE),e=get$3(o,"params.DeliveryStreamName",AWS_SERVICE_REQUEST);i=n._startSpan(e,{childOf:h,domainName:DomainNames.STREAM,className:ClassNames.FIREHOSE,disableActiveStart:!0,tags:{[SpanTags.OPERATION_TYPE]:t,[SpanTags.SPAN_TYPE]:SpanTypes.AWS_FIREHOSE,[AwsSDKTags.REQUEST_NAME]:g}}),o.params.DeliveryStreamName&&(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),i.setTag(AwsFirehoseTags.STREAM_NAME,o.params.DeliveryStreamName))}else if("athena"===c){const t=get$3(o,"params.Database",get$3(o,"params.QueryExecutionContext.Database","")),s=get$3(o,"params.ResultConfiguration.OutputLocation",""),a=AWSIntegration.getOperationType(g,ClassNames.ATHENA);let r=[],p=[];has$6(o,"params.QueryExecutionIds")?r=o.params.QueryExecutionIds:has$6(o,"params.QueryExecutionId")&&(r=[o.params.QueryExecutionId]),has$6(o,"params.NamedQueryIds")?p=o.params.NamedQueryIds:has$6(o,"params.NamedQueryId")&&(p=[o.params.NamedQueryId]);const c=t||AWS_SERVICE_REQUEST;if(i=n._startSpan(c,{childOf:h,domainName:DomainNames.DB,className:ClassNames.ATHENA,disableActiveStart:!0,tags:{[SpanTags.OPERATION_TYPE]:a,[SpanTags.SPAN_TYPE]:SpanTypes.AWS_ATHENA,[AwsSDKTags.REQUEST_NAME]:g}}),a){if(i.setTag(SpanTags.TRIGGER_OPERATION_NAMES,[u]),i.setTag(SpanTags.TOPOLOGY_VERTEX,!0),i.setTag(SpanTags.TRIGGER_DOMAIN_NAME,LAMBDA_APPLICATION_DOMAIN_NAME),i.setTag(SpanTags.TRIGGER_CLASS_NAME,LAMBDA_APPLICATION_CLASS_NAME),""!==s&&i.setTag(AwsAthenaTags.S3_OUTPUT_LOCATION,s),""!==t&&i.setTag(DBTags.DB_INSTANCE,t),!e.maskAthenaStatement){""!==get$3(o,"params.QueryString","")&&i.setTag(DBTags.DB_STATEMENT,o.params.QueryString)}r.length>0&&i.setTag(AwsAthenaTags.REQUEST_QUERY_EXECUTION_IDS,r),p.length>0&&i.setTag(AwsAthenaTags.REQUEST_NAMED_QUERY_IDS,p)}}else{const t=AWSIntegration.getOperationType(g,ClassNames.AWSSERVICE);i=n._startSpan(AWS_SERVICE_REQUEST,{childOf:h,domainName:DomainNames.AWS,className:ClassNames.AWSSERVICE,disableActiveStart:!0,tags:{[SpanTags.OPERATION_TYPE]:t,[AwsSDKTags.SERVICE_NAME]:c,[AwsSDKTags.REQUEST_NAME]:g}})}const d=s.getOriginalFuntion(a);if(i._initialized(),l){const t=function(t,s){t&&i&&i.setErrorTag(t),s&&AWSIntegration.injectTraceLink(i,o,e),i&&i.closeWithCallback(this,l,[t,s])};return d.apply(this,[t])}return o.on("error",t=>{t&&i&&(i.setErrorTag(t),t.injectedByThundra&&i.close())}).on("complete",t=>{if(t&&AWSIntegration.injectTraceLink(i,o,e),i)try{i.close()}catch(t){t instanceof ThundraChaosError?o.emit("error",t):ThundraLogger.getInstance().error(t)}}),d.apply(this,[l])}catch(t){if(i&&i.close(),t instanceof ThundraChaosError)throw this.response.error=t,t;return ThundraLogger.getInstance().error(t),s.getOriginalFuntion(a).apply(this,[r])}}}this.isWrapped(t)&&this.unwrap(),has$6(t,"Request.prototype.send")&&has$6(t,"Request.prototype.promise")&&(shimmer$6.wrap(t.Request.prototype,"send",t=>wrapper(t,"send")),shimmer$6.wrap(t.Request.prototype,"promise",t=>wrapper(t,"promise")),this.setWrapped(t))}setWrapped(t){this.lib&&(t[thundraWrapped]=!0)}getOriginalFuntion(t){return get$3(this,`wrappedFuncs.${t}`)}setUnwrapped(t){this.lib&&delete t[thundraWrapped]}isWrapped(t){return get$3(t,thundraWrapped,!1)}unhook(){this.config.instrumentAWSOnLoad&&this.hook.unhook()}unwrap(){has$6(this.lib,"Request.prototype.send")&&has$6(this.lib,"Request.prototype.promise")&&(shimmer$6.unwrap(this.lib.Request.prototype,"send"),shimmer$6.unwrap(this.lib.Request.prototype,"promise"),this.setUnwrapped(this.lib))}}AWSIntegration.AWSOperationTypes=void 0;const has$7=require("lodash.has"),shimmer$7=require("shimmer"),moduleName$7="elasticsearch";class ESIntegration{constructor(t){if(this.wrapped=!1,this.version=">=10.5",this.lib=Utils.tryRequire(moduleName$7),this.lib){const{basedir:e}=Utils.getModuleInfo(moduleName$7);if(!e)return void ThundraLogger.getInstance().error(`Base directory is not found for the package ${moduleName$7}`);if(!(new ModuleVersionValidator).validateModuleVersion(e,this.version))return void ThundraLogger.getInstance().error(`Invalid module version for ${moduleName$7} integration.\n Supported version is ${this.version}`);this.config=t,this.basedir=e,this.wrap.call(this,this.lib,t)}}static hostSelect(t){const e={host:"unknown",port:0};return new Promise((s,a)=>{if(!t||!t.connectionPool||!t.connectionPool.select)return s(e);t.connectionPool.select((t,a)=>t?(ThundraLogger.getInstance().error(`Could not get host information. ${t}`),s(e)):s(a.host))})}getNormalizedPath(t){try{const e=this.config.esPathDepth;return e<=0?"":"/"+t.split("/").filter(t=>""!==t).slice(0,e).join("/")}catch(e){return t}}wrap(t,e){const s=this;this.wrapped&&this.unwrap(),has$7(t,"Transport.prototype.request")&&(shimmer$7.wrap(t.Transport.prototype,"request",function(t){let a;return function(r,i){return __awaiter(this,arguments,void 0,function*(){try{const n=s.config.tracer;if(!n)return t.call(this,r,i);const o=this,p=InvocationSupport.getFunctionName(),c=n.getActiveSpan(),h=yield ESIntegration.hostSelect(o),l=s.getNormalizedPath(r.path);(a=n._startSpan(l,{childOf:c,domainName:DomainNames.DB,className:ClassNames.ELASTICSEARCH,disableActiveStart:!0})).addTags({[SpanTags.SPAN_TYPE]:SpanTypes.ELASTIC,[DBTags.DB_HOST]:h?h.host:void 0,[DBTags.DB_PORT]:h?h.port:void 0,[DBTags.DB_TYPE]:DBTypes.ELASTICSEARCH,[SpanTags.TOPOLOGY_VERTEX]:!0,[SpanTags.TRIGGER_DOMAIN_NAME]:LAMBDA_APPLICATION_DOMAIN_NAME,[SpanTags.TRIGGER_CLASS_NAME]:LAMBDA_APPLICATION_CLASS_NAME,[SpanTags.TRIGGER_OPERATION_NAMES]:[p],[ESTags.ES_URI]:r.path,[ESTags.ES_NORMALIZED_URI]:l,[ESTags.ES_METHOD]:r.method,[ESTags.ES_PARAMS]:e.maskElasticSearchStatement?void 0:JSON.stringify(r.query)}),JSON.stringify(r.body)&&(a.setTag(ESTags.ES_BODY,e.maskElasticSearchStatement?void 0:JSON.stringify(r.body)),a.setTag(DBTags.DB_STATEMENT,e.maskElasticSearchStatement?void 0:JSON.stringify(r.body))),a.addTags({[DBTags.DB_STATEMENT_TYPE]:r.method,[SpanTags.OPERATION_TYPE]:r.method}),a._initialized();const u=i,g=(t,e)=>{t&&a.setErrorTag(t),a.closeWithCallback(o,u,[t,e])};if("function"==typeof i)return t.call(this,r,g);{const e=t.apply(this,arguments);return e.then(()=>{a.finish()}).catch(t=>{a.setErrorTag(t),a.finish()}),e}}catch(e){if(a&&a.close(),e instanceof ThundraChaosError)throw e;return ThundraLogger.getInstance().error(e),t.call(this,r,i)}})}}),this.wrapped=!0)}unwrap(){shimmer$7.unwrap(this.lib.Transport.prototype,"request"),this.wrapped=!1}}class StandardSpanFilter{constructor(t={}){this.$domainName=t.domainName,this.$className=t.className,this.$operationName=t.operationName,this.$reverse=t.reverse,this.$tags=t.tags?t.tags:{}}get domainName(){return this.$domainName}set domainName(t){this.$domainName=t}get className(){return this.$className}set className(t){this.$className=t}get operationName(){return this.$operationName}set operationName(t){this.$operationName=t}get reverse(){return this.$reverse}set reverse(t){this.$reverse=t}get tags(){return this.$tags}set tags(t){this.$tags=t}getTag(t){return this.$tags[t]}setTag(t,e){this.$tags[t]=e}accept(t){let e=!0;if(this.domainName&&(e=this.domainName===t.domainName),e&&this.className&&(e=this.className===t.className),e&&this.operationName&&(e=this.operationName===t.operationName),e){const s=this.tags;if(s)for(const a of Object.keys(s))if(this.getTag(a)!==t.getTag(a)){e=!1;break}}return this.reverse?!e:e}}const get$4=require("lodash.get");class CompositeSpanFilter{constructor(t={}){this.composite=!0,this.all=get$4(t,"all",!1),this.filters=[]}getFilters(){return this.filters}setFilters(t){this.filters=t}accept(t){if(!this.filters||0===this.filters.length)return!0;let e=this.all;for(const s of this.filters)e=this.all?e&&s.accept(t):e||s.accept(t);return e}}class StandardSpanFilterer{constructor(t,e=!1){this.all=e,this.spanFilters=t||[]}accept(t){if(!this.spanFilters||0===this.spanFilters.length)return!0;let e=this.all;for(const s of this.spanFilters)e=this.all?e&&s.accept(t):e||s.accept(t);return e}addFilter(t){this.spanFilters.push(t)}clearFilters(){this.spanFilters=[]}}const get$5=require("lodash.get");class FilteringSpanListener{constructor(t={}){if(t.listener)try{this.all=get$5(t,"all",!1),this.listener=this._getListenerFromConfig(t),this.spanFilterer=new StandardSpanFilterer(this._getSpanFiltererFromConfig(t),this.all)}catch(t){ThundraLogger.getInstance().error(`Cannot parse span listener config with reason: ${t.message}`)}}onSpanStarted(t,e,s,a,r){return!1}onSpanInitialized(t,e,s,a,r){return!(!this.spanFilterer||!this.spanFilterer.accept(t))&&this.listener.onSpanInitialized(t,e,s,a,r)}onSpanFinished(t,e,s,a,r){return!(!this.spanFilterer||!this.spanFilterer.accept(t))&&(this.listener.onSpanFinished(t,e,s,a,r),!0)}failOnError(){return this.listener.failOnError()}_getListenerFromConfig(t){const e=get$5(t,"listener.type",""),s=LISTENERS[e];if(!s)throw new Error("No listener found with name: "+e);return new s(get$5(t,"listener.config",{}))}_getSpanFiltererFromConfig(t){const e=[];for(const s of t.filters){if(get$5(s,"composite",!1)){const t=new CompositeSpanFilter(s),a=this._getSpanFiltererFromConfig(s);t.setFilters(a),e.push(t)}else e.push(new StandardSpanFilter(s))}return e}}const get$6=require("lodash.get");class ErrorInjectorSpanListener{constructor(t={}){this.DEFAULT_ERROR_MESSAGE="Error injected by Thundra!",this.DEFAULT_INJECT_COUNT_FREQ=1,this.DEFAULT_INJECT_ON_FINISH=!1,this.DEFAULT_ERROR_TYPE="Error",this.injectCountFreq=get$6(t,"injectCountFreq",this.DEFAULT_INJECT_COUNT_FREQ),this.injectOnFinish=get$6(t,"injectOnFinish",this.DEFAULT_INJECT_ON_FINISH),this.errorType=get$6(t,"errorType",this.DEFAULT_ERROR_TYPE),this.errorMessage=get$6(t,"errorMessage",this.DEFAULT_ERROR_MESSAGE),this.counter=0}onSpanStarted(t,e,s,a,r){return!1}onSpanInitialized(t,e,s,a,r){return s&&!this.injectOnFinish?(void 0===r||!1===r)&&(this._injectErrorWithCallback(t,e,s),!0):s||this.injectOnFinish||!this.failOnError()?void 0:(this._injectError(t,e),!1)}onSpanFinished(t,e,s,a,r){return s&&this.injectOnFinish?(void 0===r||!1===r)&&(this._injectErrorWithCallback(t,e,s),!0):!s&&this.injectOnFinish&&this.failOnError()?(this._injectError(t,e),!1):void 0}failOnError(){return!0}_injectErrorWithCallback(t,e,s){if(this.counter%this.injectCountFreq==0){const a=new ThundraChaosError(this.errorMessage);a.name=this.errorType,t.setErrorTag(a),"function"==typeof s&&s.apply(e,[a])}this.counter++}_injectError(t,e){if(this.counter%this.injectCountFreq==0){const e=new ThundraChaosError(this.errorMessage);throw e.name=this.errorType,t.setErrorTag(e),this.counter++,e}this.counter++}}const get$7=require("lodash.get");class LatencyInjectorSpanListener{constructor(t={}){this.DEFAULT_DELAY=100,this.DEFAULT_INJECT_ON_FINISH=!1,this.DEFAULT_RANDOMIZE_DELAY=!1,this.injectOnFinish=get$7(t,"injectOnFinish",this.DEFAULT_INJECT_ON_FINISH),this.delay=get$7(t,"delay",this.DEFAULT_DELAY),this.randomizeDelay=get$7(t,"randomizeDelay",this.DEFAULT_RANDOMIZE_DELAY)}onSpanStarted(t,e,s,a,r){return!1}onSpanInitialized(t,e,s,a,r){if(void 0===r||!1===r){if(s&&!this.injectOnFinish){const t=this.randomizeDelay?Utils.getRandomInt(this.delay):this.delay;Utils.sleep(t).then(()=>{"function"==typeof s&&s.apply(e,a)})}return!0}return!1}onSpanFinished(t,e,s,a){if(s&&this.injectOnFinish){const t=this.randomizeDelay?Utils.getRandomInt(this.delay):this.delay;Utils.sleep(t).then(()=>{"function"==typeof s&&s.apply(e,a)})}return!0}failOnError(){return!1}invokesCallback(){return!0}}const get$8=require("lodash.get");class TagInjectorSpanListener{constructor(t={}){this.tags=get$8(t,"tags",{})}setTags(t){this.tags=t}getTags(){return this.tags}onSpanStarted(t,e,s,a,r){return!1}onSpanInitialized(t,e,s,a,r){const i=get$8(t,"tags",{}),n=Object.assign({},i,this.tags);return t.tags=n,!1}onSpanFinished(t,e,s,a,r){return!1}failOnError(){return!1}}const get$9=require("lodash.get");class SecurityAwareSpanListener{constructor(t={}){this.block=get$9(t,"block",!1),this.whitelist=get$9(t,"whitelist"),this.blacklist=get$9(t,"blacklist"),Array.isArray(this.whitelist)&&(this.whitelist=this.whitelist.map(t=>new Operation(t))),Array.isArray(this.blacklist)&&(this.blacklist=this.blacklist.map(t=>new Operation(t)))}onSpanStarted(t,e,s,a,r){return!1}onSpanInitialized(t,e,s,a,r){if(!this.isExternalOperation(t))return!1;const i=Array.isArray(this.whitelist);if(Array.isArray(this.blacklist))for(const e of this.blacklist)if(e.matches(t))return this.handleSecurityIssue(t),!1;if(i){for(const e of this.whitelist)if(e.matches(t))return!1;this.handleSecurityIssue(t)}return!1}onSpanFinished(t,e,s,a,r){return!1}failOnError(){return!0}isExternalOperation(t){return!0===t.getTag(SpanTags.TOPOLOGY_VERTEX)}handleSecurityIssue(t){if(this.block){const e=new SecurityError("Operation was blocked due to security configuration");throw t.setErrorTag(e),t.setTag(SecurityTags.BLOCKED,!0),t.setTag(SecurityTags.VIOLATED,!0),InvocationSupport.setAgentTag(SecurityTags.BLOCKED,!0),InvocationSupport.setAgentTag(SecurityTags.VIOLATED,!0),e}t.setTag(SecurityTags.VIOLATED,!0),InvocationSupport.setAgentTag(SecurityTags.VIOLATED,!0)}}class SecurityError extends ThundraChaosError{constructor(t){super(t),this.name="SecurityError"}}class Operation{constructor(t={}){this.className=get$9(t,"className"),this.tags=get$9(t,"tags")}matches(t){let e=!0;if(this.className&&(e="*"===this.className||this.className===t.className),e&&this.tags)for(const s of Object.keys(this.tags)){const a=get$9(this.tags,s,[]);if(Array.isArray(a)){if(a.includes("*"))continue;if(!a.includes(t.getTag(s))){e=!1;break}}else if(!Array.isArray(a)){if("*"===a)continue;if(t.getTag(s)!==a){e=!1;break}}}return e}}const{version:version}=require("../package.json"),envVariableKeys={THUNDRA_LAMBDA_WARMUP_AWARE:"thundra_agent_lambda_warmup_warmupAware",THUNDRA_APIKEY:"thundra_apiKey",THUNDRA_DISABLE:"thundra_agent_lambda_disable",THUNDRA_APPLICATION_STAGE:"thundra_agent_lambda_application_stage",THUNDRA_APPLICATION_DOMAIN_NAME:"thundra_agent_lambda_application_domainName",THUNDRA_APPLICATION_CLASS_NAME:"thundra_agent_lambda_application_className",THUNDRA_APPLICATION_VERSION:"thundra_agent_lambda_application_version",THUNDRA_LAMBDA_TIMEOUT_MARGIN:"thundra_agent_lambda_timeout_margin",THUNDRA_LAMBDA_REPORT_REST_BASEURL:"thundra_agent_lambda_report_rest_baseUrl",THUNDRA_LAMBDA_REPORT_REST_COMPOSITE_ENABLED:"thundra_agent_lambda_report_rest_composite_enabled",THUNDRA_LAMBDA_REPORT_CLOUDWATCH_ENABLE:"thundra_agent_lambda_report_cloudwatch_enable",THUNDRA_DISABLE_TRACE:"thundra_agent_lambda_trace_disable",THUNDRA_DISABLE_METRIC:"thundra_agent_lambda_metric_disable",THUNDRA_DISABLE_LOG:"thundra_agent_lambda_log_disable",THUNDRA_DISABLE_XRAY:"thundra_agent_lambda_xray_disable",_X_AMZN_TRACE_ID:"_X_AMZN_TRACE_ID",THUNDRA_LAMBDA_TRACE_REQUEST_SKIP:"thundra_agent_lambda_trace_request_skip",THUNDRA_LAMBDA_TRACE_RESPONSE_SKIP:"thundra_agent_lambda_trace_response_skip",THUNDRA_LAMBDA_TRACE_INSTRUMENT_DISABLE:"thundra_agent_lambda_trace_instrument_disable",THUNDRA_LAMBDA_TRACE_INSTRUMENT_CONFIG:"thundra_agent_lambda_trace_instrument_traceableConfig",THUNDRA_LAMBDA_TRACE_INSTRUMENT_FILE_PREFIX:"thundra_agent_lambda_trace_instrument_file_prefix",THUNDRA_LAMBDA_TRACE_INTEGRATIONS_DISABLE:"thundra_agent_lambda_trace_instrument_integrations_disable",THUNDRA_LAMBDA_LOG_CONSOLE_DISABLE:"thundra_agent_lambda_log_console_disable",THUNDRA_LAMBDA_LOG_LOGLEVEL:"thundra_agent_lambda_log_loglevel",THUNDRA_AGENT_LAMBDA_AGENT_DEBUG_ENABLE:"thundra_agent_lambda_debug_enable",THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_HTTP_URL_DEPTH:"thundra_agent_lambda_trace_integrations_http_url_depth",THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_ELASTICSEARCH_URL_DEPTH:"thundra_agent_lambda_trace_integrations_elasticsearch_path_depth",DISABLE_SPAN_CONTEXT_INJECTION:"thundra_agent_trace_instrument_integrations_spanContext_disable",THUNDRA_LAMBDA_TRACE_USE_PROPAGATED_TRANSACTION_ID:"thundra_agent_lambda_trace_use_propagated_transaction_id",SLS_LOCAL:"IS_LOCAL",AWS_SAM_LOCAL:"AWS_SAM_LOCAL",AWS_LAMBDA_APPLICATION_ID:"AWS_LAMBDA_APPLICATION_ID",AWS_LAMBDA_LOG_STREAM_NAME:"AWS_LAMBDA_LOG_STREAM_NAME",AWS_LAMBDA_FUNCTION_VERSION:"AWS_LAMBDA_FUNCTION_VERSION",AWS_REGION:"AWS_REGION",AWS_LAMBDA_FUNCTION_MEMORY_SIZE:"AWS_LAMBDA_FUNCTION_MEMORY_SIZE",AWS_LAMBDA_FUNCTION_NAME:"AWS_LAMBDA_FUNCTION_NAME",THUNDRA_APPLICATION_TAG_PROP_NAME_PREFIX:"thundra_agent_lambda_application_tag_",THUNDRA_APPLICATION_ID:"thundra_agent_lambda_application_id",THUNDRA_APPLICATION_NAME:"thundra_agent_lambda_application_name",THUNDRA_AGENT_LAMBDA_SPAN_LISTENER_DEF:"thundra_agent_lambda_trace_span_listenerConfig",THUNDRA_AGENT_LAMBDA_SAMPLE_TIMED_OUT_INVOCATIONS:"thundra_agent_lambda_sample_timed_out_invocations",THUNDRA_MASK_REDIS_STATEMENT:"thundra_agent_lambda_trace_integrations_redis_command_mask",THUNDRA_MASK_RDB_STATEMENT:"thundra_agent_lambda_trace_integrations_rdb_statement_mask",THUNDRA_MASK_DYNAMODB_STATEMENT:"thundra_agent_lambda_trace_integrations_aws_dynamodb_statement_mask",THUNDRA_MASK_ELASTIC_STATEMENT:"thundra_agent_lambda_trace_integrations_elastic_statement_mask",THUNDRA_MASK_MONGODB_COMMAND:"thundra_agent_lambda_trace_integrations_mongodb_command_mask",THUNDRA_MASK_ATHENA_STATEMENT:"thundra_agent_lambda_trace_integrations_aws_athena_statement_mask",ENABLE_DYNAMODB_TRACE_INJECTION:"thundra_agent_trace_integrations_dynamodb_trace_injection_enable",THUNDRA_LAMBDA_TRACE_KINESIS_REQUEST_ENABLE:"thundra_agent_lambda_trace_kinesis_request_enable",THUNDRA_LAMBDA_TRACE_FIREHOSE_REQUEST_ENABLE:"thundra_agent_lambda_trace_firehose_request_enable",THUNDRA_LAMBDA_TRACE_CLOUDWATCHLOG_REQUEST_ENABLE:"thundra_agent_lambda_trace_cloudwatchlog_request_enable",THUNDRA_MASK_SNS_MESSAGE:"thundra_agent_lambda_trace_integrations_aws_sns_message_mask",THUNDRA_MASK_SQS_MESSAGE:"thundra_agent_lambda_trace_integrations_aws_sqs_message_mask",THUNDRA_MASK_LAMBDA_PAYLOAD:"thundra_agent_lambda_trace_integrations_aws_lambda_payload_mask",THUNDRA_MASK_HTTP_BODY:"thundra_agent_lambda_trace_integrations_http_body_mask",THUNDRA_MASK_ERROR_STACK_TRACE:"thundra_agent_lambda_error_stacktrace_mask",THUNDRA_AGENT_TIME_AWARE_SAMPLER_TIME_FREQ:"thundra_agent_lambda_sampler_timeAware_timeFreq",THUNDRA_AGENT_COUNT_AWARE_SAMPLER_COUNT_FREQ:"thundra_agent_lambda_sampler_countAware_countFreq",THUNDRA_AWS_INSTRUMENT_ON_LOAD:"thundra_agent_lambda_trace_integrations_aws_instrument_onLoad",THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_4XX:"thundra_agent_trace_integrations_http_set_error_on_4xx_response_code_disable",THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_5XX:"thundra_agent_trace_integrations_http_set_error_on_5xx_response_code_disable",THUNDRA_AGENT_LAMBDA_DEBUGGER_ENABLE:"thundra_agent_lambda_debugger_enable",THUNDRA_AGENT_LAMBDA_DEBUGGER_PORT:"thundra_agent_lambda_debugger_port",THUNDRA_AGENT_LAMBDA_DEBUGGER_WAIT_MAX:"thundra_agent_lambda_debugger_wait_max",THUNDRA_AGENT_LAMBDA_DEBUGGER_BROKER_PORT:"thundra_agent_lambda_debugger_broker_port",THUNDRA_AGENT_LAMBDA_DEBUGGER_BROKER_HOST:"thundra_agent_lambda_debugger_broker_host"};function getTimeoutMargin(t){if(t){if("us-west-2"===t)return 200;if(t.startsWith("us-west-"))return 400;if(t.startsWith("us-"))return 600;if(t.startsWith("ca-"))return 600;if(t.startsWith("sa-"))return 800;if(t.startsWith("cn-"))return 1e3;if(t.startsWith("eu-"))return 1e3;if(t.startsWith("ap-"))return 1e3}return 1e3}const AGENT_VERSION=version,DATA_MODEL_VERSION="2.0",TIMEOUT_MARGIN=getTimeoutMargin(process.env[envVariableKeys.AWS_REGION]),LAMBDA_APPLICATION_DOMAIN_NAME="API",LAMBDA_APPLICATION_CLASS_NAME="AWS-Lambda",LAMBDA_FUNCTION_PLATFORM="AWS Lambda",URL=url.parse(process.env[envVariableKeys.THUNDRA_LAMBDA_REPORT_REST_BASEURL]?process.env[envVariableKeys.THUNDRA_LAMBDA_REPORT_REST_BASEURL]:"https://"+getAPIEndpoint(process.env[envVariableKeys.AWS_REGION])+"/v1");function getAPIEndpoint(t){if(t){if(t.startsWith("us-west-"))return"api.thundra.io";if(t.startsWith("us-east-")||t.startsWith("sa-")||t.startsWith("ca-"))return"api-us-east-1.thundra.io";if("eu-west-1"===t)return"api-eu-west-1.thundra.io";if(t.startsWith("eu-"))return"api-eu-west-2.thundra.io";if(t.startsWith("ap-"))return"api-ap-northeast-1.thundra.io"}return"api.thundra.io"}const MONITORING_DATA_PATH="/monitoring-data",COMPOSITE_MONITORING_DATA_PATH="/composite-monitoring-data",PROC_STAT_PATH="/proc/self/stat",PROC_IO_PATH="/proc/self/io",ARGS_TAG_NAME="method.args",RETURN_VALUE_TAG_NAME="method.return_value",logLevels={0:0,1:1,2:2,3:3,4:4,5:5,6:6,trace:0,debug:1,info:2,warn:3,error:4,fatal:5,none:6,TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,FATAL:5,NONE:6},DomainNames={AWS:"AWS",DB:"DB",MESSAGING:"Messaging",STREAM:"Stream",STORAGE:"Storage",API:"API",CACHE:"Cache",SCHEDULE:"Schedule",CDN:"CDN"},ClassNames={AWSSERVICE:"AWSService",DYNAMODB:"AWS-DynamoDB",SQS:"AWS-SQS",SNS:"AWS-SNS",KINESIS:"AWS-Kinesis",FIREHOSE:"AWS-Firehose",S3:"AWS-S3",LAMBDA:"AWS-Lambda",RDB:"RDB",REDIS:"Redis",HTTP:"HTTP",CLOUDWATCH:"AWS-CloudWatch-Schedule",CLOUDFRONT:"AWS-CloudFront",APIGATEWAY:"AWS-APIGateway",ATHENA:"AWS-Athena",MONGODB:"MONGODB",ELASTICSEARCH:"ELASTICSEARCH",MYSQL:"MYSQL"},AWS_SERVICE_REQUEST="AWSServiceRequest",DBTags={DB_STATEMENT:"db.statement",DB_STATEMENT_TYPE:"db.statement.type",DB_INSTANCE:"db.instance",DB_TYPE:"db.type",DB_HOST:"db.host",DB_PORT:"db.port",DB_USER:"db.user"},SecurityTags={BLOCKED:"security.blocked",VIOLATED:"security.violated"},MongoDBTags={MONGODB_COMMAND:"mongodb.command",MONGODB_COMMAND_NAME:"mongodb.command.name",MONGODB_COLLECTION:"mongodb.collection.name"},MongoDBCommandTypes={AGGREGATE:"READ",COUNT:"READ",DISTINCT:"READ",GROUP:"READ",MAPREDUCE:"READ",GEONEAR:"READ",GEOSEARCH:"READ",DELETE:"DELETE",EVAL:"EXECUTE",FIND:"READ",FINDANDMODIFY:"WRITE",GETLASTERROR:"READ",GETMORE:"READ",GETPREVERROR:"READ",INSERT:"WRITE",PARALLELCOLLECTIONSCAN:"READ",RESETERROR:"WRITE",UPDATE:"WRITE",PLANCACHECLEAR:"DELETE",PLANCACHECLEARFILTERS:"DELETE",PLANCACHELISTFILTERS:"READ",PLANCACHELISTPLANS:"READ",PLANCACHELISTQUERYSHAPES:"READ",PLANCACHESETFILTER:"WRITE",AUTHENTICATE:"EXECUTE",LOGOUT:"EXECUTE",CREATEUSER:"WRITE",DROPALLUSERSFROMDATABASE:"DELETE",DROPUSER:"DELETE",GRANROLESTOUSER:"WRITE",REVOKEROLESFROMUSER:"WRITE",UPDATEUSER:"WRITE",USERSINFO:"READ",CREATEROLE:"WRITE",DROPROLE:"DELETE",DROPALLROLESFROMDATABASE:"DELETE",GRANTPRIVILEGESTOROLE:"WRITE",GRANTROLESTOROLE:"WRITE",INVALIDATEUSERCACHE:"DELETE",REVOKEPRIVILEGESFROMROLE:"WRITE",REVOKEROLESFROMROLE:"WRITE",ROLESINFO:"READ",UPDATEROLE:"WRITE",ISMASTER:"READ",REPLSETABORTPRIMARYCATCHUP:"EXECUTE",REPLSETFREEZE:"EXECUTE",REPLSETGETCONFIG:"READ",REPLSETGETSTATUS:"READ",REPLSETINITIATE:"EXECUTE",REPLSETMAINTENANCE:"EXECUTE",REPLSETRECONFIG:"EXECUTE",REPLSETRESIZEOPLOG:"EXECUTE",REPLSETSTEPDOWN:"EXECUTE",REPLSETSYNCFROM:"EXECUTE",ADDSHARD:"EXECUTE",ADDSHARDTOZONE:"EXECUTE",BALANCERSTART:"EXECUTE",BALANCERSTATUS:"READ",BALANCERSTOP:"EXECUTE",CLEANUPORPHANED:"EXECUTE",ENABLESHARDING:"EXECUTE",FLUSHROUTERCONFIG:"EXECUTE",ISDBGRID:"READ",LISTSHARDS:"READ",MOVEPRIMARY:"EXECUTE",MERGECHUNKS:"EXECUTE",REMOVESHARD:"EXECUTE",REMOVESHARDFROMZONE:"EXECUTE",SHARDCOLLECTION:"EXECUTE",SHARDINGSTATE:"READ",SPLIT:"EXECUTE",UPDATEZONEKEYRANGE:"EXECUTE",ABORTTRANSACTION:"EXECUTE",COMMITTRANSACTION:"EXECUTE",ENDSESSIONS:"EXECUTE",KILLALLSESSIONS:"EXECUTE",KILLALLSESSIONSBYPATTERN:"EXECUTE",KILLSESSIONS:"EXECUTE",REFRESHSESSIONS:"EXECUTE",STARTSESSION:"EXECUTE",CLONE:"EXECUTE",CLONECOLLECTION:"EXECUTE",CLONECOLLECTIONASCAPPED:"EXECUTE",COLLMOD:"WRITE",COMPACT:"EXECUTE",CONVERTTOCAPPED:"EXECUTE",COPYDB:"EXECUTE",CREATE:"WRITE",CREATEINDEXES:"WRITE",CURRENTOP:"READ",DROP:"DELETE",DROPDATABASE:"DELETE",DROPINDEXES:"DELETE",FILEMD5:"READ",FSYNC:"EXECUTE",FSYNCUNLOCK:"EXECUTE",GETPARAMETER:"READ",KILLCURSORS:"EXECUTE",KILLOP:"EXECUTE",LISTCOLLECTIONS:"READ",LISTDATABASES:"READ",LISTINDEXES:"READ",LOGROTATE:"EXECUTE",REINDEX:"WRITE",RENAMECOLLECTION:"WRITE",REPAIRDATABASE:"EXECUTE",SETFEATURECOMPATIBILITYVERSION:"WRITE",SETPARAMETER:"WRITE",SHUTDOWN:"EXECUTE",TOUCH:"EXECUTE",BUILDINFO:"READ",COLLSTATS:"READ",CONNPOOLSTATS:"READ",CONNECTIONSTATUS:"READ",CURSORINFO:"READ",DBHASH:"READ",DBSTATS:"READ",DIAGLOGGING:"READ",EXPLAIN:"READ",FEATURES:"READ",GETCMDLINEOPTS:"READ",GETLOG:"READ",HOSTINFO:"READ",LISTCOMMANDS:"READ",PROFILE:"READ",SERVERSTATUS:"READ",SHARDCONNPOOLSTATS:"READ",TOP:"READ",SETFREEMONITORING:"EXECUTE",LOGAPPLICATIONMESSAGE:"EXECUTE"},DBTypes={DYNAMODB:"aws-dynamodb",REDIS:"redis",PG:"postgresql",MYSQL:"mysql",ELASTICSEARCH:"elasticsearch",MONGODB:"mongodb"},HttpTags={HTTP_METHOD:"http.method",HTTP_URL:"http.url",HTTP_PATH:"http.path",HTTP_HOST:"http.host",HTTP_STATUS:"http.status_code",QUERY_PARAMS:"http.query_params",BODY:"http.body"},RedisTags={REDIS_HOST:"redis.host",REDIS_PORT:"redis.port",REDIS_COMMAND:"redis.command",REDIS_COMMANDS:"redis.commands",REDIS_COMMAND_TYPE:"redis.command.type",REDIS_COMMAND_ARGS:"redis.command.args"},ESTags={ES_URI:"elasticsearch.uri",ES_NORMALIZED_URI:"elasticsearch.normalized_uri",ES_METHOD:"elasticsearch.method",ES_PARAMS:"elasticsearch.params",ES_BODY:"elasticsearch.body"},AwsSDKTags={SERVICE_NAME:"aws.service.name",REQUEST_NAME:"aws.request.name",HOST:"host"},AwsDynamoTags={TABLE_NAME:"aws.dynamodb.table.name",REQUEST_THROTTLED:"aws.dynamodb.request.throttled"},AwsFirehoseTags={STREAM_NAME:"aws.firehose.stream.name"},AwsKinesisTags={STREAM_NAME:"aws.kinesis.stream.name"},AwsAthenaTags={S3_OUTPUT_LOCATION:"aws.athena.s3.outputLocation",REQUEST_QUERY_EXECUTION_IDS:"aws.athena.request.query.executionIds",RESPONSE_QUERY_EXECUTION_IDS:"aws.athena.response.query.executionIds",REQUEST_NAMED_QUERY_IDS:"aws.athena.request.namedQuery.ids",RESPONSE_NAMED_QUERY_IDS:"aws.athena.response.namedQuery.ids"},AwsLambdaTags={FUNCTION_NAME:"aws.lambda.name",FUNCTION_QUALIFIER:"aws.lambda.qualifier",INVOCATION_TYPE:"aws.lambda.invocation.type",INVOCATION_PAYLOAD:"aws.lambda.invocation.payload"},AwsS3Tags={BUCKET_NAME:"aws.s3.bucket.name",OBJECT_NAME:"aws.s3.object.name"},AwsSNSTags={TOPIC_NAME:"aws.sns.topic.name",TARGET_NAME:"aws.sns.target.name",SMS_PHONE_NUMBER:"aws.sns.sms.phone_number",MESSAGE:"aws.sns.message"},AwsSQSTags={QUEUE_NAME:"aws.sqs.queue.name",MESSAGE:"aws.sqs.message",MESSAGES:"aws.sqs.messages"},SpanTags={SPAN_TYPE:"span.type",OPERATION_TYPE:"operation.type",TRIGGER_DOMAIN_NAME:"trigger.domainName",TRIGGER_CLASS_NAME:"trigger.className",TRIGGER_OPERATION_NAMES:"trigger.operationNames",TOPOLOGY_VERTEX:"topology.vertex",TRACE_LINKS:"trace.links"},TriggerHeaderTags={RESOURCE_NAME:"x-thundra-resource-name"},SpanTypes={REDIS:"Redis",ELASTIC:"Elastic",RDB:"RDB",HTTP:"HTTP",AWS_DYNAMO:"AWS-DynamoDB",AWS_SQS:"AWS-SQS",AWS_SNS:"AWS-SNS",AWS_KINESIS:"AWS-Kinesis",AWS_FIREHOSE:"AWS-Firehose",AWS_S3:"AWS-S3",AWS_LAMBDA:"AWS-Lambda",AWS_ATHENA:"AWS-Athena"},INTEGRATIONS={http:HttpIntegration,pg:PostgreIntegration,mysql2:MySQL2Integration,mysql:MySQLIntegration,redis:RedisIntegration,ioredis:IORedisIntegration,aws:AWSIntegration,es:ESIntegration,mongodb:MongoDBIntegration},LISTENERS={FilteringSpanListener:FilteringSpanListener,ErrorInjectorSpanListener:ErrorInjectorSpanListener,LatencyInjectorSpanListener:LatencyInjectorSpanListener,TagInjectorSpanListener:TagInjectorSpanListener,SecurityAwareSpanListener:SecurityAwareSpanListener},RedisCommandTypes={APPEND:"WRITE",BGREWRITEAOF:"WRITE",BGSAVE:"WRITE",BITCOUNT:"READ",BITFIELD:"WRITE",BITOP:"WRITE",BITPOS:"READ",BLPOP:"DELETE",BRPOP:"DELETE",BRPOPLPUSH:"WRITE",BZPOPMIN:"DELETE",BZPOPMAX:"DELETE",DBSIZE:"READ",DECR:"WRITE",DECRBY:"WRITE",DEL:"DELETE",EVAL:"EXECUTE",EVALSHA:"EXECUTE",EXISTS:"READ",EXPIRE:"WRITE",EXPIREAT:"WRITE",FLUSHALL:"DELETE",FLUSHDB:"DELETE",GEOADD:"WRITE",GEOHASH:"READ",GEOPOS:"READ",GEODIST:"READ",GEORADIUS:"READ",GEORADIUSBYMEMBER:"READ",GET:"READ",GETBIT:"READ",GETRANGE:"READ",GETSET:"WRITE",HDEL:"DELETE",HEXISTS:"READ",HGET:"READ",HGETALL:"READ",HINCRBY:"WRITE",HINCRBYFLOAT:"WRITE",HEYS:"READ",HLEN:"READ",HMGET:"READ",HMSET:"WRITE",HSET:"WRITE",HSETNX:"WRITE",HSTRLEN:"READ",HVALS:"READ",INCR:"WRITE",INCRBY:"WRITE",INCRBYFLOAT:"WRITE",KEYS:"READ",LINDEX:"READ",LINSERT:"WRITE",LLEN:"READ",LPOP:"DELETE",LPUSH:"WRITE",LPUSHX:"WRITE",LRANGE:"READ",LREM:"DELETE",LSET:"WRITE",LTRIM:"DELETE",MGET:"READ",MSET:"WRITE",MSETNX:"WRITE",PERSIST:"WRITE",PEXPIRE:"WRITE",PEXPIREAT:"WRITE",PFADD:"WRITE",PFCOUNT:"READ",PFMERGE:"WRITE",PSETEX:"WRITE",PUBLISH:"WRITE",RPOP:"DELETE",RPOPLPUSH:"WRITE",RPUSH:"WRITE",RPUSHX:"WRITE",SADD:"WRITE",SCARD:"READ",SDIFFSTORE:"WRITE",SET:"WRITE",SETBIT:"WRITE",SETEX:"WRITE",SETNX:"WRITE",SETRANGE:"WRITE",SINTER:"READ",SINTERSTORE:"WRITE",SISMEMBER:"READ",SMEMBERS:"READ",SMOVE:"WRITE",SORT:"WRITE",SPOP:"DELETE",SRANDMEMBER:"READ",SREM:"DELETE",STRLEN:"READ",SUNION:"READ",SUNIONSTORE:"WRITE",ZADD:"WRITE",ZCARD:"READ",ZCOUNT:"READ",ZINCRBY:"WRITE",ZINTERSTORE:"WRITE",ZLEXCOUNT:"READ",ZPOPMAX:"DELETE",ZPOPMIN:"DELETE",ZRANGE:"READ",ZRANGEBYLEX:"READ",ZREVRANGEBYLEX:"READ",ZRANGEBYSCORE:"READ",ZRANK:"READ",ZREM:"DELETE",ZREMRANGEBYLEX:"DELETE",ZREMRANGEBYRANK:"DELETE",ZREMRANGEBYSCORE:"DELETE",ZREVRANGE:"READ",ZREVRANGEBYSCORE:"READ",ZREVRANK:"READ",ZSCORE:"READ",ZUNIONSTORE:"WRITE",SCAN:"READ",SSCAN:"READ",HSCAN:"READ",ZSCAN:"READ",XADD:"WRITE",XRANGE:"READ",XREVRANGE:"READ",XLEN:"READ",XREAD:"READ",XREADGROUP:"READ",XPENDING:"READ"},AwsXrayConstants={DEFAULT_OPERATION_NAME:"AWS X-Ray",XRAY_SUBSEGMENTED_TAG_NAME:"THUNDRA::XRAY_SUBSEGMENTED"},SQLQueryOperationTypes={SELECT:"READ",INSERT:"WRITE",UPDATE:"WRITE",DELETE:"WRITE"},ConsoleShimmedMethods=["log","debug","info","warn","error"],StdOutLogContext="STDOUT",StdErrorLogContext="STDERR",DefaultMongoCommandSizeLimit=131072,DEFAULT_THUNDRA_AGENT_LAMBDA_DEBUGGER_PORT=1111,DEFAULT_THUNDRA_AGENT_LAMBDA_DEBUGGER_HOST="debug.thundra.io";class BasePluginConfig{constructor(t){this.enabled=t}}var concatMap=function(t,e){for(var s=[],a=0;a<t.length;a++){var r=e(t[a],a);isArray(r)?s.push.apply(s,r):s.push(r)}return s},isArray=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},balancedMatch=balanced;function balanced(t,e,s){t instanceof RegExp&&(t=maybeMatch(t,s)),e instanceof RegExp&&(e=maybeMatch(e,s));var a=range(t,e,s);return a&&{start:a[0],end:a[1],pre:s.slice(0,a[0]),body:s.slice(a[0]+t.length,a[1]),post:s.slice(a[1]+e.length)}}function maybeMatch(t,e){var s=e.match(t);return s?s[0]:null}function range(t,e,s){var a,r,i,n,o,p=s.indexOf(t),c=s.indexOf(e,p+1),h=p;if(p>=0&&c>0){for(a=[],i=s.length;h>=0&&!o;)h==p?(a.push(h),p=s.indexOf(t,h+1)):1==a.length?o=[a.pop(),c]:((r=a.pop())<i&&(i=r,n=c),c=s.indexOf(e,h+1)),h=p<c&&p>=0?p:c;a.length&&(o=[i,n])}return o}balanced.range=range;var braceExpansion=expandTop,escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0";function numeric(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function escapeBraces(t){return t.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod)}function unescapeBraces(t){return t.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".")}function parseCommaParts(t){if(!t)return[""];var e=[],s=balancedMatch("{","}",t);if(!s)return t.split(",");var a=s.pre,r=s.body,i=s.post,n=a.split(",");n[n.length-1]+="{"+r+"}";var o=parseCommaParts(i);return i.length&&(n[n.length-1]+=o.shift(),n.push.apply(n,o)),e.push.apply(e,n),e}function expandTop(t){return t?("{}"===t.substr(0,2)&&(t="\\{\\}"+t.substr(2)),expand(escapeBraces(t),!0).map(unescapeBraces)):[]}function embrace(t){return"{"+t+"}"}function isPadded(t){return/^-?0\d/.test(t)}function lte(t,e){return t<=e}function gte(t,e){return t>=e}function expand(t,e){var s=[],a=balancedMatch("{","}",t);if(!a||/\$$/.test(a.pre))return[t];var r,i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body),n=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body),o=i||n,p=a.body.indexOf(",")>=0;if(!o&&!p)return a.post.match(/,.*\}/)?expand(t=a.pre+"{"+a.body+escClose+a.post):[t];if(o)r=a.body.split(/\.\./);else if(1===(r=parseCommaParts(a.body)).length&&1===(r=expand(r[0],!1).map(embrace)).length)return(l=a.post.length?expand(a.post,!1):[""]).map(function(t){return a.pre+r[0]+t});var c,h=a.pre,l=a.post.length?expand(a.post,!1):[""];if(o){var u=numeric(r[0]),g=numeric(r[1]),d=Math.max(r[0].length,r[1].length),T=3==r.length?Math.abs(numeric(r[2])):1,E=lte;g<u&&(T*=-1,E=gte);var m=r.some(isPadded);c=[];for(var A=u;E(A,g);A+=T){var f;if(n)"\\"===(f=String.fromCharCode(A))&&(f="");else if(f=String(A),m){var _=d-f.length;if(_>0){var S=new Array(_+1).join("0");f=A<0?"-"+S+f.slice(1):S+f}}c.push(f)}}else c=concatMap(r,function(t){return expand(t,!1)});for(var I=0;I<c.length;I++)for(var y=0;y<l.length;y++){var R=h+c[I]+l[y];(!e||o||R)&&s.push(R)}return s}var minimatch_1=minimatch;minimatch.Minimatch=Minimatch;var path$2={sep:"/"};try{path$2=path$4}catch(t){}var GLOBSTAR=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={},plTypes={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},qmark="[^/]",star=qmark+"*?",twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?",reSpecials=charSet("().*{}+?[]^$\\!");function charSet(t){return t.split("").reduce(function(t,e){return t[e]=!0,t},{})}var slashSplit=/\/+/;function filter(t,e){return e=e||{},function(s,a,r){return minimatch(s,t,e)}}function ext(t,e){t=t||{},e=e||{};var s={};return Object.keys(e).forEach(function(t){s[t]=e[t]}),Object.keys(t).forEach(function(e){s[e]=t[e]}),s}function minimatch(t,e,s){if("string"!=typeof e)throw new TypeError("glob pattern string required");return s||(s={}),!(!s.nocomment&&"#"===e.charAt(0))&&(""===e.trim()?""===t:new Minimatch(e,s).match(t))}function Minimatch(t,e){if(!(this instanceof Minimatch))return new Minimatch(t,e);if("string"!=typeof t)throw new TypeError("glob pattern string required");e||(e={}),t=t.trim(),"/"!==path$2.sep&&(t=t.split(path$2.sep).join("/")),this.options=e,this.set=[],this.pattern=t,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}function make(){if(!this._made){var t=this.pattern,e=this.options;if(e.nocomment||"#"!==t.charAt(0))if(t){this.parseNegate();var s=this.globSet=this.braceExpand();e.debug&&(this.debug=console.error),this.debug(this.pattern,s),s=this.globParts=s.map(function(t){return t.split(slashSplit)}),this.debug(this.pattern,s),s=s.map(function(t,e,s){return t.map(this.parse,this)},this),this.debug(this.pattern,s),s=s.filter(function(t){return-1===t.indexOf(!1)}),this.debug(this.pattern,s),this.set=s}else this.empty=!0;else this.comment=!0}}function parseNegate(){var t=this.pattern,e=!1,s=0;if(!this.options.nonegate){for(var a=0,r=t.length;a<r&&"!"===t.charAt(a);a++)e=!e,s++;s&&(this.pattern=t.substr(s)),this.negate=e}}function braceExpand(t,e){if(e||(e=this instanceof Minimatch?this.options:{}),void 0===(t=void 0===t?this.pattern:t))throw new TypeError("undefined pattern");return e.nobrace||!t.match(/\{.*\}/)?[t]:braceExpansion(t)}minimatch.filter=filter,minimatch.defaults=function(t){if(!t||!Object.keys(t).length)return minimatch;var e=minimatch,s=function(s,a,r){return e.minimatch(s,a,ext(t,r))};return s.Minimatch=function(s,a){return new e.Minimatch(s,ext(t,a))},s},Minimatch.defaults=function(t){return t&&Object.keys(t).length?minimatch.defaults(t).Minimatch:Minimatch},Minimatch.prototype.debug=function(){},Minimatch.prototype.make=make,Minimatch.prototype.parseNegate=parseNegate,minimatch.braceExpand=function(t,e){return braceExpand(t,e)},Minimatch.prototype.braceExpand=braceExpand,Minimatch.prototype.parse=parse$1;var SUBPARSE={};function parse$1(t,e){if(t.length>65536)throw new TypeError("pattern is too long");var s=this.options;if(!s.noglobstar&&"**"===t)return GLOBSTAR;if(""===t)return"";var a,r="",i=!!s.nocase,n=!1,o=[],p=[],c=!1,h=-1,l=-1,u="."===t.charAt(0)?"":s.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",g=this;function clearStateChar(){if(a){switch(a){case"*":r+=star,i=!0;break;case"?":r+=qmark,i=!0;break;default:r+="\\"+a}g.debug("clearStateChar %j %j",a,r),a=!1}}for(var d,T=0,E=t.length;T<E&&(d=t.charAt(T));T++)if(this.debug("%s\t%s %s %j",t,T,r,d),n&&reSpecials[d])r+="\\"+d,n=!1;else switch(d){case"/":return!1;case"\\":clearStateChar(),n=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s\t%s %s %j <-- stateChar",t,T,r,d),c){this.debug(" in class"),"!"===d&&T===l+1&&(d="^"),r+=d;continue}g.debug("call clearStateChar %j",a),clearStateChar(),a=d,s.noext&&clearStateChar();continue;case"(":if(c){r+="(";continue}if(!a){r+="\\(";continue}o.push({type:a,start:T-1,reStart:r.length,open:plTypes[a].open,close:plTypes[a].close}),r+="!"===a?"(?:(?!(?:":"(?:",this.debug("plType %j %j",a,r),a=!1;continue;case")":if(c||!o.length){r+="\\)";continue}clearStateChar(),i=!0;var m=o.pop();r+=m.close,"!"===m.type&&p.push(m),m.reEnd=r.length;continue;case"|":if(c||!o.length||n){r+="\\|",n=!1;continue}clearStateChar(),r+="|";continue;case"[":if(clearStateChar(),c){r+="\\"+d;continue}c=!0,l=T,h=r.length,r+=d;continue;case"]":if(T===l+1||!c){r+="\\"+d,n=!1;continue}if(c){var A=t.substring(l+1,T);try{RegExp("["+A+"]")}catch(t){var f=this.parse(A,SUBPARSE);r=r.substr(0,h)+"\\["+f[0]+"\\]",i=i||f[1],c=!1;continue}}i=!0,c=!1,r+=d;continue;default:clearStateChar(),n?n=!1:!reSpecials[d]||"^"===d&&c||(r+="\\"),r+=d}for(c&&(A=t.substr(l+1),f=this.parse(A,SUBPARSE),r=r.substr(0,h)+"\\["+f[0],i=i||f[1]),m=o.pop();m;m=o.pop()){var _=r.slice(m.reStart+m.open.length);this.debug("setting tail",r,m),_=_.replace(/((?:\\{2}){0,64})(\\?)\|/g,function(t,e,s){return s||(s="\\"),e+e+s+"|"}),this.debug("tail=%j\n %s",_,_,m,r);var S="*"===m.type?star:"?"===m.type?qmark:"\\"+m.type;i=!0,r=r.slice(0,m.reStart)+S+"\\("+_}clearStateChar(),n&&(r+="\\\\");var I=!1;switch(r.charAt(0)){case".":case"[":case"(":I=!0}for(var y=p.length-1;y>-1;y--){var R=p[y],N=r.slice(0,R.reStart),C=r.slice(R.reStart,R.reEnd-8),b=r.slice(R.reEnd-8,R.reEnd),v=r.slice(R.reEnd);b+=v;var D=N.split("(").length-1,L=v;for(T=0;T<D;T++)L=L.replace(/\)[+*?]?/,"");var O="";""===(v=L)&&e!==SUBPARSE&&(O="$"),r=N+C+v+O+b}if(""!==r&&i&&(r="(?=.)"+r),I&&(r=u+r),e===SUBPARSE)return[r,i];if(!i)return globUnescape(t);var x=s.nocase?"i":"";try{var P=new RegExp("^"+r+"$",x)}catch(t){return new RegExp("$.")}return P._glob=t,P._src=r,P}function makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;var t=this.set;if(!t.length)return this.regexp=!1,this.regexp;var e=this.options,s=e.noglobstar?star:e.dot?twoStarDot:twoStarNoDot,a=e.nocase?"i":"",r=t.map(function(t){return t.map(function(t){return t===GLOBSTAR?s:"string"==typeof t?regExpEscape(t):t._src}).join("\\/")}).join("|");r="^(?:"+r+")$",this.negate&&(r="^(?!"+r+").*$");try{this.regexp=new RegExp(r,a)}catch(t){this.regexp=!1}return this.regexp}function match(t,e){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return""===t;if("/"===t&&e)return!0;var s=this.options;"/"!==path$2.sep&&(t=t.split(path$2.sep).join("/")),t=t.split(slashSplit),this.debug(this.pattern,"split",t);var a,r,i=this.set;for(this.debug(this.pattern,"set",i),r=t.length-1;r>=0&&!(a=t[r]);r--);for(r=0;r<i.length;r++){var n=i[r],o=t;if(s.matchBase&&1===n.length&&(o=[a]),this.matchOne(o,n,e))return!!s.flipNegate||!this.negate}return!s.flipNegate&&this.negate}function globUnescape(t){return t.replace(/\\(.)/g,"$1")}function regExpEscape(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}minimatch.makeRe=function(t,e){return new Minimatch(t,e||{}).makeRe()},Minimatch.prototype.makeRe=makeRe,minimatch.match=function(t,e,s){var a=new Minimatch(e,s=s||{});return t=t.filter(function(t){return a.match(t)}),a.options.nonull&&!t.length&&t.push(e),t},Minimatch.prototype.match=match,Minimatch.prototype.matchOne=function(t,e,s){var a=this.options;this.debug("matchOne",{this:this,file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var r=0,i=0,n=t.length,o=e.length;r<n&&i<o;r++,i++){this.debug("matchOne loop");var p,c=e[i],h=t[r];if(this.debug(e,c,h),!1===c)return!1;if(c===GLOBSTAR){this.debug("GLOBSTAR",[e,c,h]);var l=r,u=i+1;if(u===o){for(this.debug("** at the end");r<n;r++)if("."===t[r]||".."===t[r]||!a.dot&&"."===t[r].charAt(0))return!1;return!0}for(;l<n;){var g=t[l];if(this.debug("\nglobstar while",t,l,e,u,g),this.matchOne(t.slice(l),e.slice(u),s))return this.debug("globstar found match!",l,n,g),!0;if("."===g||".."===g||!a.dot&&"."===g.charAt(0)){this.debug("dot detected!",t,l,e,u);break}this.debug("globstar swallow a segment, and continue"),l++}return!(!s||(this.debug("\n>>> no match, partial?",t,l,e,u),l!==n))}if("string"==typeof c?(p=a.nocase?h.toLowerCase()===c.toLowerCase():h===c,this.debug("string match",c,h,p)):(p=h.match(c),this.debug("pattern match",c,h,p)),!p)return!1}if(r===n&&i===o)return!0;if(r===n)return s;if(i===o)return r===n-1&&""===t[r];throw new Error("wtf?")};var TraceableConfig_1=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});class s{constructor(t){if(this.$pattern=null,!t)throw Error("please pass a valid trace definition pattern to TraceableConfig constructor.");this.$pattern=t,this.$traceArgs=!1,this.$traceReturnValue=!1,this.$traceError=!0,this.$traceLineByLine=!1,this.$regExpFunction=new minimatch_1.Minimatch(t);const e=t.split(".");this.$regExpFile=new minimatch_1.Minimatch(e.slice(0,e.length-1).join(".")+".*")}static fromString(t){const e=t.indexOf("["),a=t.indexOf("]"),r=t.substring(e+1,a).split(","),i=e<0?t:t.substring(0,e),n=new s(i);for(const t of r){const e=t.split("=");n.setProperty(e[0],e[1])}return n}get pattern(){return this.$pattern}set pattern(t){this.$pattern=t}get traceArgs(){return this.$traceArgs}set traceArgs(t){this.$traceArgs=t}get traceReturnValue(){return this.$traceReturnValue}set traceReturnValue(t){this.$traceReturnValue=t}get traceError(){return this.$traceError}set traceError(t){this.$traceError=t}get traceLineByLine(){return this.$traceLineByLine}set traceLineByLine(t){this.$traceLineByLine=t}setProperty(t,e){switch(t){case"traceArgs":this.$traceArgs="true"===e;break;case"traceReturnValue":this.$traceReturnValue="true"===e;break;case"traceError":this.$traceError="true"===e;break;case"traceLineByLine":this.$traceLineByLine="true"===e}}shouldTraceFunction(t){return this.$regExpFunction.match(t)}shouldTraceFile(t){return this.$regExpFile.match(t)}setPropertyFromConfig(t){this.$pattern=t.pattern,this.$traceArgs=t.traceArgs,this.$traceReturnValue=t.traceReturnValue,this.$traceError=t.traceError,this.$traceLineByLine=t.traceLineByLine}}!function(t){t[t.FILE=0]="FILE",t[t.FUNCTION=1]="FUNCTION"}(e.TraceableConfigCheckLevel||(e.TraceableConfigCheckLevel={})),e.default=s});unwrapExports(TraceableConfig_1);var TraceableConfig_2=TraceableConfig_1.TraceableConfigCheckLevel,NodePointer_1=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.RETURN_POINTER_TYPE=1,e.LINE_POINTER_TYPE=2;e.default=class{constructor(t,e){this.type=t,this.pointer=e}}});unwrapExports(NodePointer_1);var NodePointer_2=NodePointer_1.RETURN_POINTER_TYPE,NodePointer_3=NodePointer_1.LINE_POINTER_TYPE,reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",keywords={5:ecma5AndLessKeywords,6:ecma5AndLessKeywords+" const class extends export import super"},keywordRelationalOperator=/^in(stanceof)?$/,nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄮㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿪ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",nonASCIIidentifierChars="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]"),nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");nonASCIIidentifierStartChars=nonASCIIidentifierChars=null;var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,55,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,698,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,1,31,6124,20,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541],astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,19719,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239];function isInAstralSet(t,e){for(var s=65536,a=0;a<e.length;a+=2){if((s+=e[a])>t)return!1;if((s+=e[a+1])>=t)return!0}}function isIdentifierStart(t,e){return t<65?36===t:t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&nonASCIIidentifierStart.test(String.fromCharCode(t)):!1!==e&&isInAstralSet(t,astralIdentifierStartCodes)))}function isIdentifierChar(t,e){return t<48?36===t:t<58||!(t<65)&&(t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&nonASCIIidentifier.test(String.fromCharCode(t)):!1!==e&&(isInAstralSet(t,astralIdentifierStartCodes)||isInAstralSet(t,astralIdentifierCodes)))))}var TokenType=function(t,e){void 0===e&&(e={}),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop||null,this.updateContext=null};function binop(t,e){return new TokenType(t,{beforeExpr:!0,binop:e})}var beforeExpr={beforeExpr:!0},startsExpr={startsExpr:!0},keywords$1={};function kw(t,e){return void 0===e&&(e={}),e.keyword=t,keywords$1[t]=new TokenType(t,e)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:!0,startsExpr:!0}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:!0,startsExpr:!0}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:!0,startsExpr:!0}),eq:new TokenType("=",{beforeExpr:!0,isAssign:!0}),assign:new TokenType("_=",{beforeExpr:!0,isAssign:!0}),incDec:new TokenType("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new TokenType("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("</>/<=/>=",7),bitShift:binop("<</>>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:!0}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:!0,beforeExpr:!0}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:!0}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:!0}),_with:kw("with"),_new:kw("new",{beforeExpr:!0,startsExpr:!0}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import"),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:!0,binop:7}),_instanceof:kw("instanceof",{beforeExpr:!0,binop:7}),_typeof:kw("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:kw("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:kw("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},lineBreak=/\r\n?|\n|\u2028|\u2029/,lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(t){return 10===t||13===t||8232===t||8233===t}var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,ref=Object.prototype,hasOwnProperty=ref.hasOwnProperty,toString=ref.toString;function has$8(t,e){return hasOwnProperty.call(t,e)}var isArray$1=Array.isArray||function(t){return"[object Array]"===toString.call(t)},Position=function(t,e){this.line=t,this.column=e};Position.prototype.offset=function(t){return new Position(this.line,this.column+t)};var SourceLocation=function(t,e,s){this.start=e,this.end=s,null!==t.sourceFile&&(this.source=t.sourceFile)};function getLineInfo(t,e){for(var s=1,a=0;;){lineBreakG.lastIndex=a;var r=lineBreakG.exec(t);if(!(r&&r.index<e))return new Position(s,e-a);++s,a=r.index+r[0].length}}var defaultOptions={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{}};function getOptions(t){var e={};for(var s in defaultOptions)e[s]=t&&has$8(t,s)?t[s]:defaultOptions[s];if(e.ecmaVersion>=2015&&(e.ecmaVersion-=2009),null==e.allowReserved&&(e.allowReserved=e.ecmaVersion<5),isArray$1(e.onToken)){var a=e.onToken;e.onToken=function(t){return a.push(t)}}return isArray$1(e.onComment)&&(e.onComment=pushComment(e,e.onComment)),e}function pushComment(t,e){return function(s,a,r,i,n,o){var p={type:s?"Block":"Line",value:a,start:r,end:i};t.locations&&(p.loc=new SourceLocation(this,n,o)),t.ranges&&(p.range=[r,i]),e.push(p)}}var plugins={};function keywordRegexp(t){return new RegExp("^(?:"+t.replace(/ /g,"|")+")$")}var Parser=function(t,e,s){this.options=t=getOptions(t),this.sourceFile=t.sourceFile,this.keywords=keywordRegexp(keywords[t.ecmaVersion>=6?6:5]);var a="";if(!t.allowReserved){for(var r=t.ecmaVersion;!(a=reservedWords[r]);r--);"module"==t.sourceType&&(a+=" await")}this.reservedWords=keywordRegexp(a);var i=(a?a+" ":"")+reservedWords.strict;this.reservedWordsStrict=keywordRegexp(i),this.reservedWordsStrictBind=keywordRegexp(i+" "+reservedWords.strictBind),this.input=String(e),this.containsEsc=!1,this.loadPlugins(t.plugins),s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=types.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===t.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.inFunction=this.inGenerator=this.inAsync=!1,this.yieldPos=this.awaitPos=0,this.labels=[],0===this.pos&&t.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterFunctionScope(),this.regexpState=null};Parser.prototype.isKeyword=function(t){return this.keywords.test(t)},Parser.prototype.isReservedWord=function(t){return this.reservedWords.test(t)},Parser.prototype.extend=function(t,e){this[t]=e(this[t])},Parser.prototype.loadPlugins=function(t){for(var e in t){var s=plugins[e];if(!s)throw new Error("Plugin '"+e+"' not found");s(this,t[e])}},Parser.prototype.parse=function(){var t=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(t)};var pp=Parser.prototype,literal=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}pp.strictDirective=function(t){for(;;){skipWhiteSpace.lastIndex=t,t+=skipWhiteSpace.exec(this.input)[0].length;var e=literal.exec(this.input.slice(t));if(!e)return!1;if("use strict"==(e[1]||e[2]))return!0;t+=e[0].length}},pp.eat=function(t){return this.type===t&&(this.next(),!0)},pp.isContextual=function(t){return this.type===types.name&&this.value===t&&!this.containsEsc},pp.eatContextual=function(t){return!!this.isContextual(t)&&(this.next(),!0)},pp.expectContextual=function(t){this.eatContextual(t)||this.unexpected()},pp.canInsertSemicolon=function(){return this.type===types.eof||this.type===types.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))},pp.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},pp.semicolon=function(){this.eat(types.semi)||this.insertSemicolon()||this.unexpected()},pp.afterTrailingComma=function(t,e){if(this.type==t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0},pp.expect=function(t){this.eat(t)||this.unexpected()},pp.unexpected=function(t){this.raise(null!=t?t:this.start,"Unexpected token")},pp.checkPatternErrors=function(t,e){if(t){t.trailingComma>-1&&this.raiseRecoverable(t.trailingComma,"Comma is not permitted after the rest element");var s=e?t.parenthesizedAssign:t.parenthesizedBind;s>-1&&this.raiseRecoverable(s,"Parenthesized pattern")}},pp.checkExpressionErrors=function(t,e){if(!t)return!1;var s=t.shorthandAssign,a=t.doubleProto;if(!e)return s>=0||a>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),a>=0&&this.raiseRecoverable(a,"Redefinition of __proto__ property")},pp.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")},pp.isSimpleAssignTarget=function(t){return"ParenthesizedExpression"===t.type?this.isSimpleAssignTarget(t.expression):"Identifier"===t.type||"MemberExpression"===t.type};var pp$1=Parser.prototype;pp$1.parseTopLevel=function(t){var e={};for(t.body||(t.body=[]);this.type!==types.eof;){var s=this.parseStatement(!0,!0,e);t.body.push(s)}return this.adaptDirectivePrologue(t.body),this.next(),this.options.ecmaVersion>=6&&(t.sourceType=this.options.sourceType),this.finishNode(t,"Program")};var loopLabel={kind:"loop"},switchLabel={kind:"switch"};pp$1.isLet=function(){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;skipWhiteSpace.lastIndex=this.pos;var t=skipWhiteSpace.exec(this.input),e=this.pos+t[0].length,s=this.input.charCodeAt(e);if(91===s||123==s)return!0;if(isIdentifierStart(s,!0)){for(var a=e+1;isIdentifierChar(this.input.charCodeAt(a),!0);)++a;var r=this.input.slice(e,a);if(!keywordRelationalOperator.test(r))return!0}return!1},pp$1.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;skipWhiteSpace.lastIndex=this.pos;var t=skipWhiteSpace.exec(this.input),e=this.pos+t[0].length;return!(lineBreak.test(this.input.slice(this.pos,e))||"function"!==this.input.slice(e,e+8)||e+8!=this.input.length&&isIdentifierChar(this.input.charAt(e+8)))},pp$1.parseStatement=function(t,e,s){var a,r=this.type,i=this.startNode();switch(this.isLet()&&(r=types._var,a="let"),r){case types._break:case types._continue:return this.parseBreakContinueStatement(i,r.keyword);case types._debugger:return this.parseDebuggerStatement(i);case types._do:return this.parseDoStatement(i);case types._for:return this.parseForStatement(i);case types._function:return!t&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1);case types._class:return t||this.unexpected(),this.parseClass(i,!0);case types._if:return this.parseIfStatement(i);case types._return:return this.parseReturnStatement(i);case types._switch:return this.parseSwitchStatement(i);case types._throw:return this.parseThrowStatement(i);case types._try:return this.parseTryStatement(i);case types._const:case types._var:return a=a||this.value,t||"var"==a||this.unexpected(),this.parseVarStatement(i,a);case types._while:return this.parseWhileStatement(i);case types._with:return this.parseWithStatement(i);case types.braceL:return this.parseBlock();case types.semi:return this.parseEmptyStatement(i);case types._export:case types._import:return this.options.allowImportExportEverywhere||(e||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),r===types._import?this.parseImport(i):this.parseExport(i,s);default:if(this.isAsyncFunction())return t||this.unexpected(),this.next(),this.parseFunctionStatement(i,!0);var n=this.value,o=this.parseExpression();return r===types.name&&"Identifier"===o.type&&this.eat(types.colon)?this.parseLabeledStatement(i,n,o):this.parseExpressionStatement(i,o)}},pp$1.parseBreakContinueStatement=function(t,e){var s="break"==e;this.next(),this.eat(types.semi)||this.insertSemicolon()?t.label=null:this.type!==types.name?this.unexpected():(t.label=this.parseIdent(),this.semicolon());for(var a=0;a<this.labels.length;++a){var r=this.labels[a];if(null==t.label||r.name===t.label.name){if(null!=r.kind&&(s||"loop"===r.kind))break;if(t.label&&s)break}}return a===this.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")},pp$1.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")},pp$1.parseDoStatement=function(t){return this.next(),this.labels.push(loopLabel),t.body=this.parseStatement(!1),this.labels.pop(),this.expect(types._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(types.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")},pp$1.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.inAsync&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(loopLabel),this.enterLexicalScope(),this.expect(types.parenL),this.type===types.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var s=this.isLet();if(this.type===types._var||this.type===types._const||s){var a=this.startNode(),r=s?"let":this.value;return this.next(),this.parseVar(a,!0,r),this.finishNode(a,"VariableDeclaration"),!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==a.declarations.length||"var"!==r&&a.declarations[0].init?(e>-1&&this.unexpected(e),this.parseFor(t,a)):(this.options.ecmaVersion>=9&&(this.type===types._in?e>-1&&this.unexpected(e):t.await=e>-1),this.parseForIn(t,a))}var i=new DestructuringErrors,n=this.parseExpression(!0,i);return this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.options.ecmaVersion>=9&&(this.type===types._in?e>-1&&this.unexpected(e):t.await=e>-1),this.toAssignable(n,!1,i),this.checkLVal(n),this.parseForIn(t,n)):(this.checkExpressionErrors(i,!0),e>-1&&this.unexpected(e),this.parseFor(t,n))},pp$1.parseFunctionStatement=function(t,e){return this.next(),this.parseFunction(t,!0,!1,e)},pp$1.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement(!this.strict&&this.type==types._function),t.alternate=this.eat(types._else)?this.parseStatement(!this.strict&&this.type==types._function):null,this.finishNode(t,"IfStatement")},pp$1.parseReturnStatement=function(t){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(types.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")},pp$1.parseSwitchStatement=function(t){var e;this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(types.braceL),this.labels.push(switchLabel),this.enterLexicalScope();for(var s=!1;this.type!=types.braceR;)if(this.type===types._case||this.type===types._default){var a=this.type===types._case;e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),a?e.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(types.colon)}else e||this.unexpected(),e.consequent.push(this.parseStatement(!0));return this.exitLexicalScope(),e&&this.finishNode(e,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(t,"SwitchStatement")},pp$1.parseThrowStatement=function(t){return this.next(),lineBreak.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===types._catch){var e=this.startNode();this.next(),this.expect(types.parenL),e.param=this.parseBindingAtom(),this.enterLexicalScope(),this.checkLVal(e.param,"let"),this.expect(types.parenR),e.body=this.parseBlock(!1),this.exitLexicalScope(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(types._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")},pp$1.parseVarStatement=function(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")},pp$1.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(loopLabel),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,"WhileStatement")},pp$1.parseWithStatement=function(t){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement(!1),this.finishNode(t,"WithStatement")},pp$1.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")},pp$1.parseLabeledStatement=function(t,e,s){for(var a=0,r=this.labels;a<r.length;a+=1){r[a].name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var i=this.type.isLoop?"loop":this.type===types._switch?"switch":null,n=this.labels.length-1;n>=0;n--){var o=this.labels[n];if(o.statementStart!=t.start)break;o.statementStart=this.start,o.kind=i}return this.labels.push({name:e,kind:i,statementStart:this.start}),t.body=this.parseStatement(!0),("ClassDeclaration"==t.body.type||"VariableDeclaration"==t.body.type&&"var"!=t.body.kind||"FunctionDeclaration"==t.body.type&&(this.strict||t.body.generator))&&this.raiseRecoverable(t.body.start,"Invalid labeled declaration"),this.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")},pp$1.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")},pp$1.parseBlock=function(t){void 0===t&&(t=!0);var e=this.startNode();for(e.body=[],this.expect(types.braceL),t&&this.enterLexicalScope();!this.eat(types.braceR);){var s=this.parseStatement(!0);e.body.push(s)}return t&&this.exitLexicalScope(),this.finishNode(e,"BlockStatement")},pp$1.parseFor=function(t,e){return t.init=e,this.expect(types.semi),t.test=this.type===types.semi?null:this.parseExpression(),this.expect(types.semi),t.update=this.type===types.parenR?null:this.parseExpression(),this.expect(types.parenR),this.exitLexicalScope(),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,"ForStatement")},pp$1.parseForIn=function(t,e){var s=this.type===types._in?"ForInStatement":"ForOfStatement";return this.next(),"ForInStatement"==s&&("AssignmentPattern"===e.type||"VariableDeclaration"===e.type&&null!=e.declarations[0].init&&(this.strict||"Identifier"!==e.declarations[0].id.type))&&this.raise(e.start,"Invalid assignment in for-in loop head"),t.left=e,t.right="ForInStatement"==s?this.parseExpression():this.parseMaybeAssign(),this.expect(types.parenR),this.exitLexicalScope(),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,s)},pp$1.parseVar=function(t,e,s){for(t.declarations=[],t.kind=s;;){var a=this.startNode();if(this.parseVarId(a,s),this.eat(types.eq)?a.init=this.parseMaybeAssign(e):"const"!==s||this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")?"Identifier"==a.id.type||e&&(this.type===types._in||this.isContextual("of"))?a.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),t.declarations.push(this.finishNode(a,"VariableDeclarator")),!this.eat(types.comma))break}return t},pp$1.parseVarId=function(t,e){t.id=this.parseBindingAtom(e),this.checkLVal(t.id,e,!1)},pp$1.parseFunction=function(t,e,s,a){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!a)&&(t.generator=this.eat(types.star)),this.options.ecmaVersion>=8&&(t.async=!!a),e&&(t.id="nullableID"===e&&this.type!=types.name?null:this.parseIdent(),t.id&&this.checkLVal(t.id,"var"));var r=this.inGenerator,i=this.inAsync,n=this.yieldPos,o=this.awaitPos,p=this.inFunction;return this.inGenerator=t.generator,this.inAsync=t.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),e||(t.id=this.type==types.name?this.parseIdent():null),this.parseFunctionParams(t),this.parseFunctionBody(t,s),this.inGenerator=r,this.inAsync=i,this.yieldPos=n,this.awaitPos=o,this.inFunction=p,this.finishNode(t,e?"FunctionDeclaration":"FunctionExpression")},pp$1.parseFunctionParams=function(t){this.expect(types.parenL),t.params=this.parseBindingList(types.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},pp$1.parseClass=function(t,e){this.next(),this.parseClassId(t,e),this.parseClassSuper(t);var s=this.startNode(),a=!1;for(s.body=[],this.expect(types.braceL);!this.eat(types.braceR);){var r=this.parseClassMember(s);r&&"MethodDefinition"===r.type&&"constructor"===r.kind&&(a&&this.raise(r.start,"Duplicate constructor in the same class"),a=!0)}return t.body=this.finishNode(s,"ClassBody"),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")},pp$1.parseClassMember=function(t){var e=this;if(this.eat(types.semi))return null;var s=this.startNode(),a=function(t,a){void 0===a&&(a=!1);var r=e.start,i=e.startLoc;return!!e.eatContextual(t)&&(!(e.type===types.parenL||a&&e.canInsertSemicolon())||(s.key&&e.unexpected(),s.computed=!1,s.key=e.startNodeAt(r,i),s.key.name=t,e.finishNode(s.key,"Identifier"),!1))};s.kind="method",s.static=a("static");var r=this.eat(types.star),i=!1;r||(this.options.ecmaVersion>=8&&a("async",!0)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(types.star)):a("get")?s.kind="get":a("set")&&(s.kind="set")),s.key||this.parsePropertyName(s);var n=s.key;return s.computed||s.static||!("Identifier"===n.type&&"constructor"===n.name||"Literal"===n.type&&"constructor"===n.value)?s.static&&"Identifier"===n.type&&"prototype"===n.name&&this.raise(n.start,"Classes may not have a static property named prototype"):("method"!==s.kind&&this.raise(n.start,"Constructor can't have get/set modifier"),r&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method"),s.kind="constructor"),this.parseClassMethod(t,s,r,i),"get"===s.kind&&0!==s.value.params.length&&this.raiseRecoverable(s.value.start,"getter should have no params"),"set"===s.kind&&1!==s.value.params.length&&this.raiseRecoverable(s.value.start,"setter should have exactly one param"),"set"===s.kind&&"RestElement"===s.value.params[0].type&&this.raiseRecoverable(s.value.params[0].start,"Setter cannot use rest params"),s},pp$1.parseClassMethod=function(t,e,s,a){e.value=this.parseMethod(s,a),t.body.push(this.finishNode(e,"MethodDefinition"))},pp$1.parseClassId=function(t,e){t.id=this.type===types.name?this.parseIdent():!0===e?this.unexpected():null},pp$1.parseClassSuper=function(t){t.superClass=this.eat(types._extends)?this.parseExprSubscripts():null},pp$1.parseExport=function(t,e){if(this.next(),this.eat(types.star))return this.expectContextual("from"),this.type!==types.string&&this.unexpected(),t.source=this.parseExprAtom(),this.semicolon(),this.finishNode(t,"ExportAllDeclaration");if(this.eat(types._default)){var s;if(this.checkExport(e,"default",this.lastTokStart),this.type===types._function||(s=this.isAsyncFunction())){var a=this.startNode();this.next(),s&&this.next(),t.declaration=this.parseFunction(a,"nullableID",!1,s)}else if(this.type===types._class){var r=this.startNode();t.declaration=this.parseClass(r,"nullableID")}else t.declaration=this.parseMaybeAssign(),this.semicolon();return this.finishNode(t,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement())t.declaration=this.parseStatement(!0),"VariableDeclaration"===t.declaration.type?this.checkVariableExport(e,t.declaration.declarations):this.checkExport(e,t.declaration.id.name,t.declaration.id.start),t.specifiers=[],t.source=null;else{if(t.declaration=null,t.specifiers=this.parseExportSpecifiers(e),this.eatContextual("from"))this.type!==types.string&&this.unexpected(),t.source=this.parseExprAtom();else{for(var i=0,n=t.specifiers;i<n.length;i+=1){var o=n[i];this.checkUnreserved(o.local)}t.source=null}this.semicolon()}return this.finishNode(t,"ExportNamedDeclaration")},pp$1.checkExport=function(t,e,s){t&&(has$8(t,e)&&this.raiseRecoverable(s,"Duplicate export '"+e+"'"),t[e]=!0)},pp$1.checkPatternExport=function(t,e){var s=e.type;if("Identifier"==s)this.checkExport(t,e.name,e.start);else if("ObjectPattern"==s)for(var a=0,r=e.properties;a<r.length;a+=1){var i=r[a];this.checkPatternExport(t,i)}else if("ArrayPattern"==s)for(var n=0,o=e.elements;n<o.length;n+=1){var p=o[n];p&&this.checkPatternExport(t,p)}else"Property"==s?this.checkPatternExport(t,e.value):"AssignmentPattern"==s?this.checkPatternExport(t,e.left):"RestElement"==s?this.checkPatternExport(t,e.argument):"ParenthesizedExpression"==s&&this.checkPatternExport(t,e.expression)},pp$1.checkVariableExport=function(t,e){if(t)for(var s=0,a=e;s<a.length;s+=1){var r=a[s];this.checkPatternExport(t,r.id)}},pp$1.shouldParseExportStatement=function(){return"var"===this.type.keyword||"const"===this.type.keyword||"class"===this.type.keyword||"function"===this.type.keyword||this.isLet()||this.isAsyncFunction()},pp$1.parseExportSpecifiers=function(t){var e=[],s=!0;for(this.expect(types.braceL);!this.eat(types.braceR);){if(s)s=!1;else if(this.expect(types.comma),this.afterTrailingComma(types.braceR))break;var a=this.startNode();a.local=this.parseIdent(!0),a.exported=this.eatContextual("as")?this.parseIdent(!0):a.local,this.checkExport(t,a.exported.name,a.exported.start),e.push(this.finishNode(a,"ExportSpecifier"))}return e},pp$1.parseImport=function(t){return this.next(),this.type===types.string?(t.specifiers=empty,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===types.string?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(t,"ImportDeclaration")},pp$1.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===types.name){var s=this.startNode();if(s.local=this.parseIdent(),this.checkLVal(s.local,"let"),t.push(this.finishNode(s,"ImportDefaultSpecifier")),!this.eat(types.comma))return t}if(this.type===types.star){var a=this.startNode();return this.next(),this.expectContextual("as"),a.local=this.parseIdent(),this.checkLVal(a.local,"let"),t.push(this.finishNode(a,"ImportNamespaceSpecifier")),t}for(this.expect(types.braceL);!this.eat(types.braceR);){if(e)e=!1;else if(this.expect(types.comma),this.afterTrailingComma(types.braceR))break;var r=this.startNode();r.imported=this.parseIdent(!0),this.eatContextual("as")?r.local=this.parseIdent():(this.checkUnreserved(r.imported),r.local=r.imported),this.checkLVal(r.local,"let"),t.push(this.finishNode(r,"ImportSpecifier"))}return t},pp$1.adaptDirectivePrologue=function(t){for(var e=0;e<t.length&&this.isDirectiveCandidate(t[e]);++e)t[e].directive=t[e].expression.raw.slice(1,-1)},pp$1.isDirectiveCandidate=function(t){return"ExpressionStatement"===t.type&&"Literal"===t.expression.type&&"string"==typeof t.expression.value&&('"'===this.input[t.start]||"'"===this.input[t.start])};var pp$2=Parser.prototype;pp$2.toAssignable=function(t,e,s){if(this.options.ecmaVersion>=6&&t)switch(t.type){case"Identifier":this.inAsync&&"await"===t.name&&this.raise(t.start,"Can not use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var a=0,r=t.properties;a<r.length;a+=1){var i=r[a];this.toAssignable(i,e),"RestElement"!==i.type||"ArrayPattern"!==i.argument.type&&"ObjectPattern"!==i.argument.type||this.raise(i.argument.start,"Unexpected token")}break;case"Property":"init"!==t.kind&&this.raise(t.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(t.value,e);break;case"ArrayExpression":t.type="ArrayPattern",s&&this.checkPatternErrors(s,!0),this.toAssignableList(t.elements,e);break;case"SpreadElement":t.type="RestElement",this.toAssignable(t.argument,e),"AssignmentPattern"===t.argument.type&&this.raise(t.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":"="!==t.operator&&this.raise(t.left.end,"Only '=' operator can be used for specifying default value."),t.type="AssignmentPattern",delete t.operator,this.toAssignable(t.left,e);case"AssignmentPattern":break;case"ParenthesizedExpression":this.toAssignable(t.expression,e);break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}else s&&this.checkPatternErrors(s,!0);return t},pp$2.toAssignableList=function(t,e){for(var s=t.length,a=0;a<s;a++){var r=t[a];r&&this.toAssignable(r,e)}if(s){var i=t[s-1];6===this.options.ecmaVersion&&e&&i&&"RestElement"===i.type&&"Identifier"!==i.argument.type&&this.unexpected(i.argument.start)}return t},pp$2.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")},pp$2.parseRestBinding=function(){var t=this.startNode();return this.next(),6===this.options.ecmaVersion&&this.type!==types.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")},pp$2.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case types.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(types.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case types.braceL:return this.parseObj(!0)}return this.parseIdent()},pp$2.parseBindingList=function(t,e,s){for(var a=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(types.comma),e&&this.type===types.comma)a.push(null);else{if(s&&this.afterTrailingComma(t))break;if(this.type===types.ellipsis){var i=this.parseRestBinding();this.parseBindingListItem(i),a.push(i),this.type===types.comma&&this.raise(this.start,"Comma is not permitted after the rest element"),this.expect(t);break}var n=this.parseMaybeDefault(this.start,this.startLoc);this.parseBindingListItem(n),a.push(n)}return a},pp$2.parseBindingListItem=function(t){return t},pp$2.parseMaybeDefault=function(t,e,s){if(s=s||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(types.eq))return s;var a=this.startNodeAt(t,e);return a.left=s,a.right=this.parseMaybeAssign(),this.finishNode(a,"AssignmentPattern")},pp$2.checkLVal=function(t,e,s){switch(t.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(t.name)&&this.raiseRecoverable(t.start,(e?"Binding ":"Assigning to ")+t.name+" in strict mode"),s&&(has$8(s,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),s[t.name]=!0),e&&"none"!==e&&(("var"===e&&!this.canDeclareVarName(t.name)||"var"!==e&&!this.canDeclareLexicalName(t.name))&&this.raiseRecoverable(t.start,"Identifier '"+t.name+"' has already been declared"),"var"===e?this.declareVarName(t.name):this.declareLexicalName(t.name));break;case"MemberExpression":e&&this.raiseRecoverable(t.start,"Binding member expression");break;case"ObjectPattern":for(var a=0,r=t.properties;a<r.length;a+=1){var i=r[a];this.checkLVal(i,e,s)}break;case"Property":this.checkLVal(t.value,e,s);break;case"ArrayPattern":for(var n=0,o=t.elements;n<o.length;n+=1){var p=o[n];p&&this.checkLVal(p,e,s)}break;case"AssignmentPattern":this.checkLVal(t.left,e,s);break;case"RestElement":this.checkLVal(t.argument,e,s);break;case"ParenthesizedExpression":this.checkLVal(t.expression,e,s);break;default:this.raise(t.start,(e?"Binding":"Assigning to")+" rvalue")}};var pp$3=Parser.prototype;pp$3.checkPropClash=function(t,e,s){if(!(this.options.ecmaVersion>=9&&"SpreadElement"===t.type||this.options.ecmaVersion>=6&&(t.computed||t.method||t.shorthand))){var a,r=t.key;switch(r.type){case"Identifier":a=r.name;break;case"Literal":a=String(r.value);break;default:return}var i=t.kind;if(this.options.ecmaVersion>=6)"__proto__"===a&&"init"===i&&(e.proto&&(s&&s.doubleProto<0?s.doubleProto=r.start:this.raiseRecoverable(r.start,"Redefinition of __proto__ property")),e.proto=!0);else{var n=e[a="$"+a];if(n)("init"===i?this.strict&&n.init||n.get||n.set:n.init||n[i])&&this.raiseRecoverable(r.start,"Redefinition of property");else n=e[a]={init:!1,get:!1,set:!1};n[i]=!0}}},pp$3.parseExpression=function(t,e){var s=this.start,a=this.startLoc,r=this.parseMaybeAssign(t,e);if(this.type===types.comma){var i=this.startNodeAt(s,a);for(i.expressions=[r];this.eat(types.comma);)i.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(i,"SequenceExpression")}return r},pp$3.parseMaybeAssign=function(t,e,s){if(this.inGenerator&&this.isContextual("yield"))return this.parseYield();var a=!1,r=-1,i=-1;e?(r=e.parenthesizedAssign,i=e.trailingComma,e.parenthesizedAssign=e.trailingComma=-1):(e=new DestructuringErrors,a=!0);var n=this.start,o=this.startLoc;this.type!=types.parenL&&this.type!=types.name||(this.potentialArrowAt=this.start);var p=this.parseMaybeConditional(t,e);if(s&&(p=s.call(this,p,n,o)),this.type.isAssign){var c=this.startNodeAt(n,o);return c.operator=this.value,c.left=this.type===types.eq?this.toAssignable(p,!1,e):p,a||DestructuringErrors.call(e),e.shorthandAssign=-1,this.checkLVal(p),this.next(),c.right=this.parseMaybeAssign(t),this.finishNode(c,"AssignmentExpression")}return a&&this.checkExpressionErrors(e,!0),r>-1&&(e.parenthesizedAssign=r),i>-1&&(e.trailingComma=i),p},pp$3.parseMaybeConditional=function(t,e){var s=this.start,a=this.startLoc,r=this.parseExprOps(t,e);if(this.checkExpressionErrors(e))return r;if(this.eat(types.question)){var i=this.startNodeAt(s,a);return i.test=r,i.consequent=this.parseMaybeAssign(),this.expect(types.colon),i.alternate=this.parseMaybeAssign(t),this.finishNode(i,"ConditionalExpression")}return r},pp$3.parseExprOps=function(t,e){var s=this.start,a=this.startLoc,r=this.parseMaybeUnary(e,!1);return this.checkExpressionErrors(e)?r:r.start==s&&"ArrowFunctionExpression"===r.type?r:this.parseExprOp(r,s,a,-1,t)},pp$3.parseExprOp=function(t,e,s,a,r){var i=this.type.binop;if(null!=i&&(!r||this.type!==types._in)&&i>a){var n=this.type===types.logicalOR||this.type===types.logicalAND,o=this.value;this.next();var p=this.start,c=this.startLoc,h=this.parseExprOp(this.parseMaybeUnary(null,!1),p,c,i,r),l=this.buildBinary(e,s,t,h,o,n);return this.parseExprOp(l,e,s,a,r)}return t},pp$3.buildBinary=function(t,e,s,a,r,i){var n=this.startNodeAt(t,e);return n.left=s,n.operator=r,n.right=a,this.finishNode(n,i?"LogicalExpression":"BinaryExpression")},pp$3.parseMaybeUnary=function(t,e){var s,a=this.start,r=this.startLoc;if(this.inAsync&&this.isContextual("await"))s=this.parseAwait(),e=!0;else if(this.type.prefix){var i=this.startNode(),n=this.type===types.incDec;i.operator=this.value,i.prefix=!0,this.next(),i.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),n?this.checkLVal(i.argument):this.strict&&"delete"===i.operator&&"Identifier"===i.argument.type?this.raiseRecoverable(i.start,"Deleting local variable in strict mode"):e=!0,s=this.finishNode(i,n?"UpdateExpression":"UnaryExpression")}else{if(s=this.parseExprSubscripts(t),this.checkExpressionErrors(t))return s;for(;this.type.postfix&&!this.canInsertSemicolon();){var o=this.startNodeAt(a,r);o.operator=this.value,o.prefix=!1,o.argument=s,this.checkLVal(s),this.next(),s=this.finishNode(o,"UpdateExpression")}}return!e&&this.eat(types.starstar)?this.buildBinary(a,r,s,this.parseMaybeUnary(null,!1),"**",!1):s},pp$3.parseExprSubscripts=function(t){var e=this.start,s=this.startLoc,a=this.parseExprAtom(t),r="ArrowFunctionExpression"===a.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd);if(this.checkExpressionErrors(t)||r)return a;var i=this.parseSubscripts(a,e,s);return t&&"MemberExpression"===i.type&&(t.parenthesizedAssign>=i.start&&(t.parenthesizedAssign=-1),t.parenthesizedBind>=i.start&&(t.parenthesizedBind=-1)),i},pp$3.parseSubscripts=function(t,e,s,a){for(var r=this.options.ecmaVersion>=8&&"Identifier"===t.type&&"async"===t.name&&this.lastTokEnd==t.end&&!this.canInsertSemicolon()&&"async"===this.input.slice(t.start,t.end),i=void 0;;)if((i=this.eat(types.bracketL))||this.eat(types.dot)){var n=this.startNodeAt(e,s);n.object=t,n.property=i?this.parseExpression():this.parseIdent(!0),n.computed=!!i,i&&this.expect(types.bracketR),t=this.finishNode(n,"MemberExpression")}else if(!a&&this.eat(types.parenL)){var o=new DestructuringErrors,p=this.yieldPos,c=this.awaitPos;this.yieldPos=0,this.awaitPos=0;var h=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,!1,o);if(r&&!this.canInsertSemicolon()&&this.eat(types.arrow))return this.checkPatternErrors(o,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=p,this.awaitPos=c,this.parseArrowExpression(this.startNodeAt(e,s),h,!0);this.checkExpressionErrors(o,!0),this.yieldPos=p||this.yieldPos,this.awaitPos=c||this.awaitPos;var l=this.startNodeAt(e,s);l.callee=t,l.arguments=h,t=this.finishNode(l,"CallExpression")}else{if(this.type!==types.backQuote)return t;var u=this.startNodeAt(e,s);u.tag=t,u.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(u,"TaggedTemplateExpression")}},pp$3.parseExprAtom=function(t){var e,s=this.potentialArrowAt==this.start;switch(this.type){case types._super:return this.inFunction||this.raise(this.start,"'super' outside of function or class"),e=this.startNode(),this.next(),this.type!==types.dot&&this.type!==types.bracketL&&this.type!==types.parenL&&this.unexpected(),this.finishNode(e,"Super");case types._this:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case types.name:var a=this.start,r=this.startLoc,i=this.containsEsc,n=this.parseIdent(this.type!==types.name);if(this.options.ecmaVersion>=8&&!i&&"async"===n.name&&!this.canInsertSemicolon()&&this.eat(types._function))return this.parseFunction(this.startNodeAt(a,r),!1,!1,!0);if(s&&!this.canInsertSemicolon()){if(this.eat(types.arrow))return this.parseArrowExpression(this.startNodeAt(a,r),[n],!1);if(this.options.ecmaVersion>=8&&"async"===n.name&&this.type===types.name&&!i)return n=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(types.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,r),[n],!0)}return n;case types.regexp:var o=this.value;return(e=this.parseLiteral(o.value)).regex={pattern:o.pattern,flags:o.flags},e;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:return(e=this.startNode()).value=this.type===types._null?null:this.type===types._true,e.raw=this.type.keyword,this.next(),this.finishNode(e,"Literal");case types.parenL:var p=this.start,c=this.parseParenAndDistinguishExpression(s);return t&&(t.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(t.parenthesizedAssign=p),t.parenthesizedBind<0&&(t.parenthesizedBind=p)),c;case types.bracketL:return e=this.startNode(),this.next(),e.elements=this.parseExprList(types.bracketR,!0,!0,t),this.finishNode(e,"ArrayExpression");case types.braceL:return this.parseObj(!1,t);case types._function:return e=this.startNode(),this.next(),this.parseFunction(e,!1);case types._class:return this.parseClass(this.startNode(),!1);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();default:this.unexpected()}},pp$3.parseLiteral=function(t){var e=this.startNode();return e.value=t,e.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(e,"Literal")},pp$3.parseParenExpression=function(){this.expect(types.parenL);var t=this.parseExpression();return this.expect(types.parenR),t},pp$3.parseParenAndDistinguishExpression=function(t){var e,s=this.start,a=this.startLoc,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var i,n=this.start,o=this.startLoc,p=[],c=!0,h=!1,l=new DestructuringErrors,u=this.yieldPos,g=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==types.parenR;){if(c?c=!1:this.expect(types.comma),r&&this.afterTrailingComma(types.parenR,!0)){h=!0;break}if(this.type===types.ellipsis){i=this.start,p.push(this.parseParenItem(this.parseRestBinding())),this.type===types.comma&&this.raise(this.start,"Comma is not permitted after the rest element");break}p.push(this.parseMaybeAssign(!1,l,this.parseParenItem))}var d=this.start,T=this.startLoc;if(this.expect(types.parenR),t&&!this.canInsertSemicolon()&&this.eat(types.arrow))return this.checkPatternErrors(l,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=g,this.parseParenArrowList(s,a,p);p.length&&!h||this.unexpected(this.lastTokStart),i&&this.unexpected(i),this.checkExpressionErrors(l,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=g||this.awaitPos,p.length>1?((e=this.startNodeAt(n,o)).expressions=p,this.finishNodeAt(e,"SequenceExpression",d,T)):e=p[0]}else e=this.parseParenExpression();if(this.options.preserveParens){var E=this.startNodeAt(s,a);return E.expression=e,this.finishNode(E,"ParenthesizedExpression")}return e},pp$3.parseParenItem=function(t){return t},pp$3.parseParenArrowList=function(t,e,s){return this.parseArrowExpression(this.startNodeAt(t,e),s)};var empty$1=[];pp$3.parseNew=function(){var t=this.startNode(),e=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){t.meta=e;var s=this.containsEsc;return t.property=this.parseIdent(!0),("target"!==t.property.name||s)&&this.raiseRecoverable(t.property.start,"The only valid meta property for new is new.target"),this.inFunction||this.raiseRecoverable(t.start,"new.target can only be used in functions"),this.finishNode(t,"MetaProperty")}var a=this.start,r=this.startLoc;return t.callee=this.parseSubscripts(this.parseExprAtom(),a,r,!0),this.eat(types.parenL)?t.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,!1):t.arguments=empty$1,this.finishNode(t,"NewExpression")},pp$3.parseTemplateElement=function(t){var e=t.isTagged,s=this.startNode();return this.type===types.invalidTemplate?(e||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value,cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===types.backQuote,this.finishNode(s,"TemplateElement")},pp$3.parseTemplate=function(t){void 0===t&&(t={});var e=t.isTagged;void 0===e&&(e=!1);var s=this.startNode();this.next(),s.expressions=[];var a=this.parseTemplateElement({isTagged:e});for(s.quasis=[a];!a.tail;)this.expect(types.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(types.braceR),s.quasis.push(a=this.parseTemplateElement({isTagged:e}));return this.next(),this.finishNode(s,"TemplateLiteral")},pp$3.isAsyncProp=function(t){return!t.computed&&"Identifier"===t.key.type&&"async"===t.key.name&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))},pp$3.parseObj=function(t,e){var s=this.startNode(),a=!0,r={};for(s.properties=[],this.next();!this.eat(types.braceR);){if(a)a=!1;else if(this.expect(types.comma),this.afterTrailingComma(types.braceR))break;var i=this.parseProperty(t,e);t||this.checkPropClash(i,r,e),s.properties.push(i)}return this.finishNode(s,t?"ObjectPattern":"ObjectExpression")},pp$3.parseProperty=function(t,e){var s,a,r,i,n=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis))return t?(n.argument=this.parseIdent(!1),this.type===types.comma&&this.raise(this.start,"Comma is not permitted after the rest element"),this.finishNode(n,"RestElement")):(this.type===types.parenL&&e&&(e.parenthesizedAssign<0&&(e.parenthesizedAssign=this.start),e.parenthesizedBind<0&&(e.parenthesizedBind=this.start)),n.argument=this.parseMaybeAssign(!1,e),this.type===types.comma&&e&&e.trailingComma<0&&(e.trailingComma=this.start),this.finishNode(n,"SpreadElement"));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(t||e)&&(r=this.start,i=this.startLoc),t||(s=this.eat(types.star)));var o=this.containsEsc;return this.parsePropertyName(n),!t&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(n)?(a=!0,s=this.options.ecmaVersion>=9&&this.eat(types.star),this.parsePropertyName(n,e)):a=!1,this.parsePropertyValue(n,t,s,a,r,i,e,o),this.finishNode(n,"Property")},pp$3.parsePropertyValue=function(t,e,s,a,r,i,n,o){if((s||a)&&this.type===types.colon&&this.unexpected(),this.eat(types.colon))t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,n),t.kind="init";else if(this.options.ecmaVersion>=6&&this.type===types.parenL)e&&this.unexpected(),t.kind="init",t.method=!0,t.value=this.parseMethod(s,a);else if(e||o||!(this.options.ecmaVersion>=5)||t.computed||"Identifier"!==t.key.type||"get"!==t.key.name&&"set"!==t.key.name||this.type==types.comma||this.type==types.braceR)this.options.ecmaVersion>=6&&!t.computed&&"Identifier"===t.key.type?(this.checkUnreserved(t.key),t.kind="init",e?t.value=this.parseMaybeDefault(r,i,t.key):this.type===types.eq&&n?(n.shorthandAssign<0&&(n.shorthandAssign=this.start),t.value=this.parseMaybeDefault(r,i,t.key)):t.value=t.key,t.shorthand=!0):this.unexpected();else{(s||a)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t),t.value=this.parseMethod(!1);var p="get"===t.kind?0:1;if(t.value.params.length!==p){var c=t.value.start;"get"===t.kind?this.raiseRecoverable(c,"getter should have no params"):this.raiseRecoverable(c,"setter should have exactly one param")}else"set"===t.kind&&"RestElement"===t.value.params[0].type&&this.raiseRecoverable(t.value.params[0].start,"Setter cannot use rest params")}},pp$3.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(types.bracketR),t.key;t.computed=!1}return t.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(!0)},pp$3.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=!1,t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)},pp$3.parseMethod=function(t,e){var s=this.startNode(),a=this.inGenerator,r=this.inAsync,i=this.yieldPos,n=this.awaitPos,o=this.inFunction;return this.initFunction(s),this.options.ecmaVersion>=6&&(s.generator=t),this.options.ecmaVersion>=8&&(s.async=!!e),this.inGenerator=s.generator,this.inAsync=s.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),this.expect(types.parenL),s.params=this.parseBindingList(types.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(s,!1),this.inGenerator=a,this.inAsync=r,this.yieldPos=i,this.awaitPos=n,this.inFunction=o,this.finishNode(s,"FunctionExpression")},pp$3.parseArrowExpression=function(t,e,s){var a=this.inGenerator,r=this.inAsync,i=this.yieldPos,n=this.awaitPos,o=this.inFunction;return this.enterFunctionScope(),this.initFunction(t),this.options.ecmaVersion>=8&&(t.async=!!s),this.inGenerator=!1,this.inAsync=t.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0),this.inGenerator=a,this.inAsync=r,this.yieldPos=i,this.awaitPos=n,this.inFunction=o,this.finishNode(t,"ArrowFunctionExpression")},pp$3.parseFunctionBody=function(t,e){var s=e&&this.type!==types.braceL,a=this.strict,r=!1;if(s)t.body=this.parseMaybeAssign(),t.expression=!0,this.checkParams(t,!1);else{var i=this.options.ecmaVersion>=7&&!this.isSimpleParamList(t.params);a&&!i||(r=this.strictDirective(this.end))&&i&&this.raiseRecoverable(t.start,"Illegal 'use strict' directive in function with non-simple parameter list");var n=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(t,!a&&!r&&!e&&this.isSimpleParamList(t.params)),t.body=this.parseBlock(!1),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=n}this.exitFunctionScope(),this.strict&&t.id&&this.checkLVal(t.id,"none"),this.strict=a},pp$3.isSimpleParamList=function(t){for(var e=0,s=t;e<s.length;e+=1){if("Identifier"!==s[e].type)return!1}return!0},pp$3.checkParams=function(t,e){for(var s={},a=0,r=t.params;a<r.length;a+=1){var i=r[a];this.checkLVal(i,"var",e?null:s)}},pp$3.parseExprList=function(t,e,s,a){for(var r=[],i=!0;!this.eat(t);){if(i)i=!1;else if(this.expect(types.comma),e&&this.afterTrailingComma(t))break;var n=void 0;s&&this.type===types.comma?n=null:this.type===types.ellipsis?(n=this.parseSpread(a),a&&this.type===types.comma&&a.trailingComma<0&&(a.trailingComma=this.start)):n=this.parseMaybeAssign(!1,a),r.push(n)}return r},pp$3.checkUnreserved=function(t){var e=t.start,s=t.end,a=t.name;(this.inGenerator&&"yield"===a&&this.raiseRecoverable(e,"Can not use 'yield' as identifier inside a generator"),this.inAsync&&"await"===a&&this.raiseRecoverable(e,"Can not use 'await' as identifier inside an async function"),this.isKeyword(a)&&this.raise(e,"Unexpected keyword '"+a+"'"),this.options.ecmaVersion<6&&-1!=this.input.slice(e,s).indexOf("\\"))||(this.strict?this.reservedWordsStrict:this.reservedWords).test(a)&&(this.inAsync||"await"!==a||this.raiseRecoverable(e,"Can not use keyword 'await' outside an async function"),this.raiseRecoverable(e,"The keyword '"+a+"' is reserved"))},pp$3.parseIdent=function(t,e){var s=this.startNode();return t&&"never"==this.options.allowReserved&&(t=!1),this.type===types.name?s.name=this.value:this.type.keyword?(s.name=this.type.keyword,"class"!==s.name&&"function"!==s.name||this.lastTokEnd===this.lastTokStart+1&&46===this.input.charCodeAt(this.lastTokStart)||this.context.pop()):this.unexpected(),this.next(),this.finishNode(s,"Identifier"),t||this.checkUnreserved(s),s},pp$3.parseYield=function(){this.yieldPos||(this.yieldPos=this.start);var t=this.startNode();return this.next(),this.type==types.semi||this.canInsertSemicolon()||this.type!=types.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(types.star),t.argument=this.parseMaybeAssign()),this.finishNode(t,"YieldExpression")},pp$3.parseAwait=function(){this.awaitPos||(this.awaitPos=this.start);var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0),this.finishNode(t,"AwaitExpression")};var pp$4=Parser.prototype;pp$4.raise=function(t,e){var s=getLineInfo(this.input,t);e+=" ("+s.line+":"+s.column+")";var a=new SyntaxError(e);throw a.pos=t,a.loc=s,a.raisedAt=this.pos,a},pp$4.raiseRecoverable=pp$4.raise,pp$4.curPosition=function(){if(this.options.locations)return new Position(this.curLine,this.pos-this.lineStart)};var pp$5=Parser.prototype,assign=Object.assign||function(t){for(var e=[],s=arguments.length-1;s-- >0;)e[s]=arguments[s+1];for(var a=0,r=e;a<r.length;a+=1){var i=r[a];for(var n in i)has$8(i,n)&&(t[n]=i[n])}return t};pp$5.enterFunctionScope=function(){this.scopeStack.push({var:{},lexical:{},childVar:{},parentLexical:{}})},pp$5.exitFunctionScope=function(){this.scopeStack.pop()},pp$5.enterLexicalScope=function(){var t=this.scopeStack[this.scopeStack.length-1],e={var:{},lexical:{},childVar:{},parentLexical:{}};this.scopeStack.push(e),assign(e.parentLexical,t.lexical,t.parentLexical)},pp$5.exitLexicalScope=function(){var t=this.scopeStack.pop(),e=this.scopeStack[this.scopeStack.length-1];assign(e.childVar,t.var,t.childVar)},pp$5.canDeclareVarName=function(t){var e=this.scopeStack[this.scopeStack.length-1];return!has$8(e.lexical,t)&&!has$8(e.parentLexical,t)},pp$5.canDeclareLexicalName=function(t){var e=this.scopeStack[this.scopeStack.length-1];return!has$8(e.lexical,t)&&!has$8(e.var,t)&&!has$8(e.childVar,t)},pp$5.declareVarName=function(t){this.scopeStack[this.scopeStack.length-1].var[t]=!0},pp$5.declareLexicalName=function(t){this.scopeStack[this.scopeStack.length-1].lexical[t]=!0};var Node=function(t,e,s){this.type="",this.start=e,this.end=0,t.options.locations&&(this.loc=new SourceLocation(t,s)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[e,0])},pp$6=Parser.prototype;function finishNodeAt(t,e,s,a){return t.type=e,t.end=s,this.options.locations&&(t.loc.end=a),this.options.ranges&&(t.range[1]=s),t}pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)},pp$6.startNodeAt=function(t,e){return new Node(this,t,e)},pp$6.finishNode=function(t,e){return finishNodeAt.call(this,t,e,this.lastTokEnd,this.lastTokEndLoc)},pp$6.finishNodeAt=function(t,e,s,a){return finishNodeAt.call(this,t,e,s,a)};var TokContext=function(t,e,s,a,r){this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=a,this.generator=!!r},types$1={b_stat:new TokContext("{",!1),b_expr:new TokContext("{",!0),b_tmpl:new TokContext("${",!1),p_stat:new TokContext("(",!1),p_expr:new TokContext("(",!0),q_tmpl:new TokContext("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new TokContext("function",!1),f_expr:new TokContext("function",!0),f_expr_gen:new TokContext("function",!0,!1,null,!0),f_gen:new TokContext("function",!1,!1,null,!0)},pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]},pp$7.braceIsBlock=function(t){var e=this.curContext();return e===types$1.f_expr||e===types$1.f_stat||(t!==types.colon||e!==types$1.b_stat&&e!==types$1.b_expr?t===types._return||t==types.name&&this.exprAllowed?lineBreak.test(this.input.slice(this.lastTokEnd,this.start)):t===types._else||t===types.semi||t===types.eof||t===types.parenR||t==types.arrow||(t==types.braceL?e===types$1.b_stat:t!=types._var&&t!=types.name&&!this.exprAllowed):!e.isExpr)},pp$7.inGeneratorContext=function(){for(var t=this.context.length-1;t>=1;t--){var e=this.context[t];if("function"===e.token)return e.generator}return!1},pp$7.updateContext=function(t){var e,s=this.type;s.keyword&&t==types.dot?this.exprAllowed=!1:(e=s.updateContext)?e.call(this,t):this.exprAllowed=s.beforeExpr},types.parenR.updateContext=types.braceR.updateContext=function(){if(1!=this.context.length){var t=this.context.pop();t===types$1.b_stat&&"function"===this.curContext().token&&(t=this.context.pop()),this.exprAllowed=!t.isExpr}else this.exprAllowed=!0},types.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?types$1.b_stat:types$1.b_expr),this.exprAllowed=!0},types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl),this.exprAllowed=!0},types.parenL.updateContext=function(t){var e=t===types._if||t===types._for||t===types._with||t===types._while;this.context.push(e?types$1.p_stat:types$1.p_expr),this.exprAllowed=!0},types.incDec.updateContext=function(){},types._function.updateContext=types._class.updateContext=function(t){t.beforeExpr&&t!==types.semi&&t!==types._else&&(t!==types.colon&&t!==types.braceL||this.curContext()!==types$1.b_stat)?this.context.push(types$1.f_expr):this.context.push(types$1.f_stat),this.exprAllowed=!1},types.backQuote.updateContext=function(){this.curContext()===types$1.q_tmpl?this.context.pop():this.context.push(types$1.q_tmpl),this.exprAllowed=!1},types.star.updateContext=function(t){if(t==types._function){var e=this.context.length-1;this.context[e]===types$1.f_expr?this.context[e]=types$1.f_expr_gen:this.context[e]=types$1.f_gen}this.exprAllowed=!0},types.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&("of"==this.value&&!this.exprAllowed||"yield"==this.value&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var data={$LONE:["ASCII","ASCII_Hex_Digit","AHex","Alphabetic","Alpha","Any","Assigned","Bidi_Control","Bidi_C","Bidi_Mirrored","Bidi_M","Case_Ignorable","CI","Cased","Changes_When_Casefolded","CWCF","Changes_When_Casemapped","CWCM","Changes_When_Lowercased","CWL","Changes_When_NFKC_Casefolded","CWKCF","Changes_When_Titlecased","CWT","Changes_When_Uppercased","CWU","Dash","Default_Ignorable_Code_Point","DI","Deprecated","Dep","Diacritic","Dia","Emoji","Emoji_Component","Emoji_Modifier","Emoji_Modifier_Base","Emoji_Presentation","Extender","Ext","Grapheme_Base","Gr_Base","Grapheme_Extend","Gr_Ext","Hex_Digit","Hex","IDS_Binary_Operator","IDSB","IDS_Trinary_Operator","IDST","ID_Continue","IDC","ID_Start","IDS","Ideographic","Ideo","Join_Control","Join_C","Logical_Order_Exception","LOE","Lowercase","Lower","Math","Noncharacter_Code_Point","NChar","Pattern_Syntax","Pat_Syn","Pattern_White_Space","Pat_WS","Quotation_Mark","QMark","Radical","Regional_Indicator","RI","Sentence_Terminal","STerm","Soft_Dotted","SD","Terminal_Punctuation","Term","Unified_Ideograph","UIdeo","Uppercase","Upper","Variation_Selector","VS","White_Space","space","XID_Continue","XIDC","XID_Start","XIDS"],General_Category:["Cased_Letter","LC","Close_Punctuation","Pe","Connector_Punctuation","Pc","Control","Cc","cntrl","Currency_Symbol","Sc","Dash_Punctuation","Pd","Decimal_Number","Nd","digit","Enclosing_Mark","Me","Final_Punctuation","Pf","Format","Cf","Initial_Punctuation","Pi","Letter","L","Letter_Number","Nl","Line_Separator","Zl","Lowercase_Letter","Ll","Mark","M","Combining_Mark","Math_Symbol","Sm","Modifier_Letter","Lm","Modifier_Symbol","Sk","Nonspacing_Mark","Mn","Number","N","Open_Punctuation","Ps","Other","C","Other_Letter","Lo","Other_Number","No","Other_Punctuation","Po","Other_Symbol","So","Paragraph_Separator","Zp","Private_Use","Co","Punctuation","P","punct","Separator","Z","Space_Separator","Zs","Spacing_Mark","Mc","Surrogate","Cs","Symbol","S","Titlecase_Letter","Lt","Unassigned","Cn","Uppercase_Letter","Lu"],Script:["Adlam","Adlm","Ahom","Anatolian_Hieroglyphs","Hluw","Arabic","Arab","Armenian","Armn","Avestan","Avst","Balinese","Bali","Bamum","Bamu","Bassa_Vah","Bass","Batak","Batk","Bengali","Beng","Bhaiksuki","Bhks","Bopomofo","Bopo","Brahmi","Brah","Braille","Brai","Buginese","Bugi","Buhid","Buhd","Canadian_Aboriginal","Cans","Carian","Cari","Caucasian_Albanian","Aghb","Chakma","Cakm","Cham","Cherokee","Cher","Common","Zyyy","Coptic","Copt","Qaac","Cuneiform","Xsux","Cypriot","Cprt","Cyrillic","Cyrl","Deseret","Dsrt","Devanagari","Deva","Duployan","Dupl","Egyptian_Hieroglyphs","Egyp","Elbasan","Elba","Ethiopic","Ethi","Georgian","Geor","Glagolitic","Glag","Gothic","Goth","Grantha","Gran","Greek","Grek","Gujarati","Gujr","Gurmukhi","Guru","Han","Hani","Hangul","Hang","Hanunoo","Hano","Hatran","Hatr","Hebrew","Hebr","Hiragana","Hira","Imperial_Aramaic","Armi","Inherited","Zinh","Qaai","Inscriptional_Pahlavi","Phli","Inscriptional_Parthian","Prti","Javanese","Java","Kaithi","Kthi","Kannada","Knda","Katakana","Kana","Kayah_Li","Kali","Kharoshthi","Khar","Khmer","Khmr","Khojki","Khoj","Khudawadi","Sind","Lao","Laoo","Latin","Latn","Lepcha","Lepc","Limbu","Limb","Linear_A","Lina","Linear_B","Linb","Lisu","Lycian","Lyci","Lydian","Lydi","Mahajani","Mahj","Malayalam","Mlym","Mandaic","Mand","Manichaean","Mani","Marchen","Marc","Masaram_Gondi","Gonm","Meetei_Mayek","Mtei","Mende_Kikakui","Mend","Meroitic_Cursive","Merc","Meroitic_Hieroglyphs","Mero","Miao","Plrd","Modi","Mongolian","Mong","Mro","Mroo","Multani","Mult","Myanmar","Mymr","Nabataean","Nbat","New_Tai_Lue","Talu","Newa","Nko","Nkoo","Nushu","Nshu","Ogham","Ogam","Ol_Chiki","Olck","Old_Hungarian","Hung","Old_Italic","Ital","Old_North_Arabian","Narb","Old_Permic","Perm","Old_Persian","Xpeo","Old_South_Arabian","Sarb","Old_Turkic","Orkh","Oriya","Orya","Osage","Osge","Osmanya","Osma","Pahawh_Hmong","Hmng","Palmyrene","Palm","Pau_Cin_Hau","Pauc","Phags_Pa","Phag","Phoenician","Phnx","Psalter_Pahlavi","Phlp","Rejang","Rjng","Runic","Runr","Samaritan","Samr","Saurashtra","Saur","Sharada","Shrd","Shavian","Shaw","Siddham","Sidd","SignWriting","Sgnw","Sinhala","Sinh","Sora_Sompeng","Sora","Soyombo","Soyo","Sundanese","Sund","Syloti_Nagri","Sylo","Syriac","Syrc","Tagalog","Tglg","Tagbanwa","Tagb","Tai_Le","Tale","Tai_Tham","Lana","Tai_Viet","Tavt","Takri","Takr","Tamil","Taml","Tangut","Tang","Telugu","Telu","Thaana","Thaa","Thai","Tibetan","Tibt","Tifinagh","Tfng","Tirhuta","Tirh","Ugaritic","Ugar","Vai","Vaii","Warang_Citi","Wara","Yi","Yiii","Zanabazar_Square","Zanb"]};Array.prototype.push.apply(data.$LONE,data.General_Category),data.gc=data.General_Category,data.sc=data.Script_Extensions=data.scx=data.Script;var pp$9=Parser.prototype,RegExpValidationState=function(t){this.parser=t,this.validFlags="gim"+(t.options.ecmaVersion>=6?"uy":"")+(t.options.ecmaVersion>=9?"s":""),this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=[],this.backReferenceNames=[]};function codePointToString$1(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t)))}function isSyntaxCharacter(t){return 36===t||t>=40&&t<=43||46===t||63===t||t>=91&&t<=94||t>=123&&t<=125}function isRegExpIdentifierStart(t){return isIdentifierStart(t,!0)||36===t||95===t}function isRegExpIdentifierPart(t){return isIdentifierChar(t,!0)||36===t||95===t||8204===t||8205===t}function isControlLetter(t){return t>=65&&t<=90||t>=97&&t<=122}function isValidUnicode(t){return t>=0&&t<=1114111}function isCharacterClassEscape(t){return 100===t||68===t||115===t||83===t||119===t||87===t}function isUnicodePropertyNameCharacter(t){return isControlLetter(t)||95===t}function isUnicodePropertyValueCharacter(t){return isUnicodePropertyNameCharacter(t)||isDecimalDigit(t)}function isDecimalDigit(t){return t>=48&&t<=57}function isHexDigit(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function hexToInt(t){return t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:t-48}function isOctalDigit(t){return t>=48&&t<=55}RegExpValidationState.prototype.reset=function(t,e,s){var a=-1!==s.indexOf("u");this.start=0|t,this.source=e+"",this.flags=s,this.switchU=a&&this.parser.options.ecmaVersion>=6,this.switchN=a&&this.parser.options.ecmaVersion>=9},RegExpValidationState.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)},RegExpValidationState.prototype.at=function(t){var e=this.source,s=e.length;if(t>=s)return-1;var a=e.charCodeAt(t);return!this.switchU||a<=55295||a>=57344||t+1>=s?a:(a<<10)+e.charCodeAt(t+1)-56613888},RegExpValidationState.prototype.nextIndex=function(t){var e=this.source,s=e.length;if(t>=s)return s;var a=e.charCodeAt(t);return!this.switchU||a<=55295||a>=57344||t+1>=s?t+1:t+2},RegExpValidationState.prototype.current=function(){return this.at(this.pos)},RegExpValidationState.prototype.lookahead=function(){return this.at(this.nextIndex(this.pos))},RegExpValidationState.prototype.advance=function(){this.pos=this.nextIndex(this.pos)},RegExpValidationState.prototype.eat=function(t){return this.current()===t&&(this.advance(),!0)},pp$9.validateRegExpFlags=function(t){for(var e=t.validFlags,s=t.flags,a=0;a<s.length;a++){var r=s.charAt(a);-1==e.indexOf(r)&&this.raise(t.start,"Invalid regular expression flag"),s.indexOf(r,a+1)>-1&&this.raise(t.start,"Duplicate regular expression flag")}},pp$9.validateRegExpPattern=function(t){this.regexp_pattern(t),!t.switchN&&this.options.ecmaVersion>=9&&t.groupNames.length>0&&(t.switchN=!0,this.regexp_pattern(t))},pp$9.regexp_pattern=function(t){t.pos=0,t.lastIntValue=0,t.lastStringValue="",t.lastAssertionIsQuantifiable=!1,t.numCapturingParens=0,t.maxBackReference=0,t.groupNames.length=0,t.backReferenceNames.length=0,this.regexp_disjunction(t),t.pos!==t.source.length&&(t.eat(41)&&t.raise("Unmatched ')'"),(t.eat(93)||t.eat(125))&&t.raise("Lone quantifier brackets")),t.maxBackReference>t.numCapturingParens&&t.raise("Invalid escape");for(var e=0,s=t.backReferenceNames;e<s.length;e+=1){var a=s[e];-1===t.groupNames.indexOf(a)&&t.raise("Invalid named capture referenced")}},pp$9.regexp_disjunction=function(t){for(this.regexp_alternative(t);t.eat(124);)this.regexp_alternative(t);this.regexp_eatQuantifier(t,!0)&&t.raise("Nothing to repeat"),t.eat(123)&&t.raise("Lone quantifier brackets")},pp$9.regexp_alternative=function(t){for(;t.pos<t.source.length&&this.regexp_eatTerm(t););},pp$9.regexp_eatTerm=function(t){return this.regexp_eatAssertion(t)?(t.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(t)&&t.switchU&&t.raise("Invalid quantifier"),!0):!(t.switchU?!this.regexp_eatAtom(t):!this.regexp_eatExtendedAtom(t))&&(this.regexp_eatQuantifier(t),!0)},pp$9.regexp_eatAssertion=function(t){var e=t.pos;if(t.lastAssertionIsQuantifiable=!1,t.eat(94)||t.eat(36))return!0;if(t.eat(92)){if(t.eat(66)||t.eat(98))return!0;t.pos=e}if(t.eat(40)&&t.eat(63)){var s=!1;if(this.options.ecmaVersion>=9&&(s=t.eat(60)),t.eat(61)||t.eat(33))return this.regexp_disjunction(t),t.eat(41)||t.raise("Unterminated group"),t.lastAssertionIsQuantifiable=!s,!0}return t.pos=e,!1},pp$9.regexp_eatQuantifier=function(t,e){return void 0===e&&(e=!1),!!this.regexp_eatQuantifierPrefix(t,e)&&(t.eat(63),!0)},pp$9.regexp_eatQuantifierPrefix=function(t,e){return t.eat(42)||t.eat(43)||t.eat(63)||this.regexp_eatBracedQuantifier(t,e)},pp$9.regexp_eatBracedQuantifier=function(t,e){var s=t.pos;if(t.eat(123)){var a=0,r=-1;if(this.regexp_eatDecimalDigits(t)&&(a=t.lastIntValue,t.eat(44)&&this.regexp_eatDecimalDigits(t)&&(r=t.lastIntValue),t.eat(125)))return-1!==r&&r<a&&!e&&t.raise("numbers out of order in {} quantifier"),!0;t.switchU&&!e&&t.raise("Incomplete quantifier"),t.pos=s}return!1},pp$9.regexp_eatAtom=function(t){return this.regexp_eatPatternCharacters(t)||t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)},pp$9.regexp_eatReverseSolidusAtomEscape=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatAtomEscape(t))return!0;t.pos=e}return!1},pp$9.regexp_eatUncapturingGroup=function(t){var e=t.pos;if(t.eat(40)){if(t.eat(63)&&t.eat(58)){if(this.regexp_disjunction(t),t.eat(41))return!0;t.raise("Unterminated group")}t.pos=e}return!1},pp$9.regexp_eatCapturingGroup=function(t){if(t.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(t):63===t.current()&&t.raise("Invalid group"),this.regexp_disjunction(t),t.eat(41))return t.numCapturingParens+=1,!0;t.raise("Unterminated group")}return!1},pp$9.regexp_eatExtendedAtom=function(t){return t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)||this.regexp_eatInvalidBracedQuantifier(t)||this.regexp_eatExtendedPatternCharacter(t)},pp$9.regexp_eatInvalidBracedQuantifier=function(t){return this.regexp_eatBracedQuantifier(t,!0)&&t.raise("Nothing to repeat"),!1},pp$9.regexp_eatSyntaxCharacter=function(t){var e=t.current();return!!isSyntaxCharacter(e)&&(t.lastIntValue=e,t.advance(),!0)},pp$9.regexp_eatPatternCharacters=function(t){for(var e=t.pos,s=0;-1!==(s=t.current())&&!isSyntaxCharacter(s);)t.advance();return t.pos!==e},pp$9.regexp_eatExtendedPatternCharacter=function(t){var e=t.current();return!(-1===e||36===e||e>=40&&e<=43||46===e||63===e||91===e||94===e||124===e)&&(t.advance(),!0)},pp$9.regexp_groupSpecifier=function(t){if(t.eat(63)){if(this.regexp_eatGroupName(t))return-1!==t.groupNames.indexOf(t.lastStringValue)&&t.raise("Duplicate capture group name"),void t.groupNames.push(t.lastStringValue);t.raise("Invalid group")}},pp$9.regexp_eatGroupName=function(t){if(t.lastStringValue="",t.eat(60)){if(this.regexp_eatRegExpIdentifierName(t)&&t.eat(62))return!0;t.raise("Invalid capture group name")}return!1},pp$9.regexp_eatRegExpIdentifierName=function(t){if(t.lastStringValue="",this.regexp_eatRegExpIdentifierStart(t)){for(t.lastStringValue+=codePointToString$1(t.lastIntValue);this.regexp_eatRegExpIdentifierPart(t);)t.lastStringValue+=codePointToString$1(t.lastIntValue);return!0}return!1},pp$9.regexp_eatRegExpIdentifierStart=function(t){var e=t.pos,s=t.current();return t.advance(),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(t)&&(s=t.lastIntValue),isRegExpIdentifierStart(s)?(t.lastIntValue=s,!0):(t.pos=e,!1)},pp$9.regexp_eatRegExpIdentifierPart=function(t){var e=t.pos,s=t.current();return t.advance(),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(t)&&(s=t.lastIntValue),isRegExpIdentifierPart(s)?(t.lastIntValue=s,!0):(t.pos=e,!1)},pp$9.regexp_eatAtomEscape=function(t){return!!(this.regexp_eatBackReference(t)||this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)||t.switchN&&this.regexp_eatKGroupName(t))||(t.switchU&&(99===t.current()&&t.raise("Invalid unicode escape"),t.raise("Invalid escape")),!1)},pp$9.regexp_eatBackReference=function(t){var e=t.pos;if(this.regexp_eatDecimalEscape(t)){var s=t.lastIntValue;if(t.switchU)return s>t.maxBackReference&&(t.maxBackReference=s),!0;if(s<=t.numCapturingParens)return!0;t.pos=e}return!1},pp$9.regexp_eatKGroupName=function(t){if(t.eat(107)){if(this.regexp_eatGroupName(t))return t.backReferenceNames.push(t.lastStringValue),!0;t.raise("Invalid named reference")}return!1},pp$9.regexp_eatCharacterEscape=function(t){return this.regexp_eatControlEscape(t)||this.regexp_eatCControlLetter(t)||this.regexp_eatZero(t)||this.regexp_eatHexEscapeSequence(t)||this.regexp_eatRegExpUnicodeEscapeSequence(t)||!t.switchU&&this.regexp_eatLegacyOctalEscapeSequence(t)||this.regexp_eatIdentityEscape(t)},pp$9.regexp_eatCControlLetter=function(t){var e=t.pos;if(t.eat(99)){if(this.regexp_eatControlLetter(t))return!0;t.pos=e}return!1},pp$9.regexp_eatZero=function(t){return 48===t.current()&&!isDecimalDigit(t.lookahead())&&(t.lastIntValue=0,t.advance(),!0)},pp$9.regexp_eatControlEscape=function(t){var e=t.current();return 116===e?(t.lastIntValue=9,t.advance(),!0):110===e?(t.lastIntValue=10,t.advance(),!0):118===e?(t.lastIntValue=11,t.advance(),!0):102===e?(t.lastIntValue=12,t.advance(),!0):114===e&&(t.lastIntValue=13,t.advance(),!0)},pp$9.regexp_eatControlLetter=function(t){var e=t.current();return!!isControlLetter(e)&&(t.lastIntValue=e%32,t.advance(),!0)},pp$9.regexp_eatRegExpUnicodeEscapeSequence=function(t){var e=t.pos;if(t.eat(117)){if(this.regexp_eatFixedHexDigits(t,4)){var s=t.lastIntValue;if(t.switchU&&s>=55296&&s<=56319){var a=t.pos;if(t.eat(92)&&t.eat(117)&&this.regexp_eatFixedHexDigits(t,4)){var r=t.lastIntValue;if(r>=56320&&r<=57343)return t.lastIntValue=1024*(s-55296)+(r-56320)+65536,!0}t.pos=a,t.lastIntValue=s}return!0}if(t.switchU&&t.eat(123)&&this.regexp_eatHexDigits(t)&&t.eat(125)&&isValidUnicode(t.lastIntValue))return!0;t.switchU&&t.raise("Invalid unicode escape"),t.pos=e}return!1},pp$9.regexp_eatIdentityEscape=function(t){if(t.switchU)return!!this.regexp_eatSyntaxCharacter(t)||!!t.eat(47)&&(t.lastIntValue=47,!0);var e=t.current();return!(99===e||t.switchN&&107===e)&&(t.lastIntValue=e,t.advance(),!0)},pp$9.regexp_eatDecimalEscape=function(t){t.lastIntValue=0;var e=t.current();if(e>=49&&e<=57){do{t.lastIntValue=10*t.lastIntValue+(e-48),t.advance()}while((e=t.current())>=48&&e<=57);return!0}return!1},pp$9.regexp_eatCharacterClassEscape=function(t){var e=t.current();if(isCharacterClassEscape(e))return t.lastIntValue=-1,t.advance(),!0;if(t.switchU&&this.options.ecmaVersion>=9&&(80===e||112===e)){if(t.lastIntValue=-1,t.advance(),t.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(t)&&t.eat(125))return!0;t.raise("Invalid property name")}return!1},pp$9.regexp_eatUnicodePropertyValueExpression=function(t){var e=t.pos;if(this.regexp_eatUnicodePropertyName(t)&&t.eat(61)){var s=t.lastStringValue;if(this.regexp_eatUnicodePropertyValue(t)){var a=t.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(t,s,a),!0}}if(t.pos=e,this.regexp_eatLoneUnicodePropertyNameOrValue(t)){var r=t.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(t,r),!0}return!1},pp$9.regexp_validateUnicodePropertyNameAndValue=function(t,e,s){data.hasOwnProperty(e)&&-1!==data[e].indexOf(s)||t.raise("Invalid property name")},pp$9.regexp_validateUnicodePropertyNameOrValue=function(t,e){-1===data.$LONE.indexOf(e)&&t.raise("Invalid property name")},pp$9.regexp_eatUnicodePropertyName=function(t){var e=0;for(t.lastStringValue="";isUnicodePropertyNameCharacter(e=t.current());)t.lastStringValue+=codePointToString$1(e),t.advance();return""!==t.lastStringValue},pp$9.regexp_eatUnicodePropertyValue=function(t){var e=0;for(t.lastStringValue="";isUnicodePropertyValueCharacter(e=t.current());)t.lastStringValue+=codePointToString$1(e),t.advance();return""!==t.lastStringValue},pp$9.regexp_eatLoneUnicodePropertyNameOrValue=function(t){return this.regexp_eatUnicodePropertyValue(t)},pp$9.regexp_eatCharacterClass=function(t){if(t.eat(91)){if(t.eat(94),this.regexp_classRanges(t),t.eat(93))return!0;t.raise("Unterminated character class")}return!1},pp$9.regexp_classRanges=function(t){for(;this.regexp_eatClassAtom(t);){var e=t.lastIntValue;if(t.eat(45)&&this.regexp_eatClassAtom(t)){var s=t.lastIntValue;!t.switchU||-1!==e&&-1!==s||t.raise("Invalid character class"),-1!==e&&-1!==s&&e>s&&t.raise("Range out of order in character class")}}},pp$9.regexp_eatClassAtom=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatClassEscape(t))return!0;if(t.switchU){var s=t.current();(99===s||isOctalDigit(s))&&t.raise("Invalid class escape"),t.raise("Invalid escape")}t.pos=e}var a=t.current();return 93!==a&&(t.lastIntValue=a,t.advance(),!0)},pp$9.regexp_eatClassEscape=function(t){var e=t.pos;if(t.eat(98))return t.lastIntValue=8,!0;if(t.switchU&&t.eat(45))return t.lastIntValue=45,!0;if(!t.switchU&&t.eat(99)){if(this.regexp_eatClassControlLetter(t))return!0;t.pos=e}return this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)},pp$9.regexp_eatClassControlLetter=function(t){var e=t.current();return!(!isDecimalDigit(e)&&95!==e)&&(t.lastIntValue=e%32,t.advance(),!0)},pp$9.regexp_eatHexEscapeSequence=function(t){var e=t.pos;if(t.eat(120)){if(this.regexp_eatFixedHexDigits(t,2))return!0;t.switchU&&t.raise("Invalid escape"),t.pos=e}return!1},pp$9.regexp_eatDecimalDigits=function(t){var e=t.pos,s=0;for(t.lastIntValue=0;isDecimalDigit(s=t.current());)t.lastIntValue=10*t.lastIntValue+(s-48),t.advance();return t.pos!==e},pp$9.regexp_eatHexDigits=function(t){var e=t.pos,s=0;for(t.lastIntValue=0;isHexDigit(s=t.current());)t.lastIntValue=16*t.lastIntValue+hexToInt(s),t.advance();return t.pos!==e},pp$9.regexp_eatLegacyOctalEscapeSequence=function(t){if(this.regexp_eatOctalDigit(t)){var e=t.lastIntValue;if(this.regexp_eatOctalDigit(t)){var s=t.lastIntValue;e<=3&&this.regexp_eatOctalDigit(t)?t.lastIntValue=64*e+8*s+t.lastIntValue:t.lastIntValue=8*e+s}else t.lastIntValue=e;return!0}return!1},pp$9.regexp_eatOctalDigit=function(t){var e=t.current();return isOctalDigit(e)?(t.lastIntValue=e-48,t.advance(),!0):(t.lastIntValue=0,!1)},pp$9.regexp_eatFixedHexDigits=function(t,e){var s=t.pos;t.lastIntValue=0;for(var a=0;a<e;++a){var r=t.current();if(!isHexDigit(r))return t.pos=s,!1;t.lastIntValue=16*t.lastIntValue+hexToInt(r),t.advance()}return!0};var Token=function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,t.options.locations&&(this.loc=new SourceLocation(t,t.startLoc,t.endLoc)),t.options.ranges&&(this.range=[t.start,t.end])},pp$8=Parser.prototype;function codePointToString(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t)))}pp$8.next=function(){this.options.onToken&&this.options.onToken(new Token(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},pp$8.getToken=function(){return this.next(),new Token(this)},"undefined"!=typeof Symbol&&(pp$8[Symbol.iterator]=function(){var t=this;return{next:function(){var e=t.getToken();return{done:e.type===types.eof,value:e}}}}),pp$8.curContext=function(){return this.context[this.context.length-1]},pp$8.nextToken=function(){var t=this.curContext();return t&&t.preserveSpace||this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length?this.finishToken(types.eof):t.override?t.override(this):void this.readToken(this.fullCharCodeAtPos())},pp$8.readToken=function(t){return isIdentifierStart(t,this.options.ecmaVersion>=6)||92===t?this.readWord():this.getTokenFromCode(t)},pp$8.fullCharCodeAtPos=function(){var t=this.input.charCodeAt(this.pos);return t<=55295||t>=57344?t:(t<<10)+this.input.charCodeAt(this.pos+1)-56613888},pp$8.skipBlockComment=function(){var t,e=this.options.onComment&&this.curPosition(),s=this.pos,a=this.input.indexOf("*/",this.pos+=2);if(-1===a&&this.raise(this.pos-2,"Unterminated comment"),this.pos=a+2,this.options.locations)for(lineBreakG.lastIndex=s;(t=lineBreakG.exec(this.input))&&t.index<this.pos;)++this.curLine,this.lineStart=t.index+t[0].length;this.options.onComment&&this.options.onComment(!0,this.input.slice(s+2,a),s,this.pos,e,this.curPosition())},pp$8.skipLineComment=function(t){for(var e=this.pos,s=this.options.onComment&&this.curPosition(),a=this.input.charCodeAt(this.pos+=t);this.pos<this.input.length&&!isNewLine(a);)a=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(e+t,this.pos),e,this.pos,s,this.curPosition())},pp$8.skipSpace=function(){t:for(;this.pos<this.input.length;){var t=this.input.charCodeAt(this.pos);switch(t){case 32:case 160:++this.pos;break;case 13:10===this.input.charCodeAt(this.pos+1)&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break t}break;default:if(!(t>8&&t<14||t>=5760&&nonASCIIwhitespace.test(String.fromCharCode(t))))break t;++this.pos}}},pp$8.finishToken=function(t,e){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=t,this.value=e,this.updateContext(s)},pp$8.readToken_dot=function(){var t=this.input.charCodeAt(this.pos+1);if(t>=48&&t<=57)return this.readNumber(!0);var e=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===t&&46===e?(this.pos+=3,this.finishToken(types.ellipsis)):(++this.pos,this.finishToken(types.dot))},pp$8.readToken_slash=function(){var t=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===t?this.finishOp(types.assign,2):this.finishOp(types.slash,1)},pp$8.readToken_mult_modulo_exp=function(t){var e=this.input.charCodeAt(this.pos+1),s=1,a=42===t?types.star:types.modulo;return this.options.ecmaVersion>=7&&42==t&&42===e&&(++s,a=types.starstar,e=this.input.charCodeAt(this.pos+2)),61===e?this.finishOp(types.assign,s+1):this.finishOp(a,s)},pp$8.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.pos+1);return e===t?this.finishOp(124===t?types.logicalOR:types.logicalAND,2):61===e?this.finishOp(types.assign,2):this.finishOp(124===t?types.bitwiseOR:types.bitwiseAND,1)},pp$8.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(types.assign,2):this.finishOp(types.bitwiseXOR,1)},pp$8.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.pos+1);return e===t?45!=e||this.inModule||62!=this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(types.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===e?this.finishOp(types.assign,2):this.finishOp(types.plusMin,1)},pp$8.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.pos+1),s=1;return e===t?(s=62===t&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(types.assign,s+1):this.finishOp(types.bitShift,s)):33!=e||60!=t||this.inModule||45!=this.input.charCodeAt(this.pos+2)||45!=this.input.charCodeAt(this.pos+3)?(61===e&&(s=2),this.finishOp(types.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},pp$8.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.pos+1);return 61===e?this.finishOp(types.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===t&&62===e&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(types.arrow)):this.finishOp(61===t?types.eq:types.prefix,1)},pp$8.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(types.parenL);case 41:return++this.pos,this.finishToken(types.parenR);case 59:return++this.pos,this.finishToken(types.semi);case 44:return++this.pos,this.finishToken(types.comma);case 91:return++this.pos,this.finishToken(types.bracketL);case 93:return++this.pos,this.finishToken(types.bracketR);case 123:return++this.pos,this.finishToken(types.braceL);case 125:return++this.pos,this.finishToken(types.braceR);case 58:return++this.pos,this.finishToken(types.colon);case 63:return++this.pos,this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(types.backQuote);case 48:var e=this.input.charCodeAt(this.pos+1);if(120===e||88===e)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===e||79===e)return this.readRadixNumber(8);if(98===e||66===e)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(t);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(t);case 124:case 38:return this.readToken_pipe_amp(t);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(t);case 60:case 62:return this.readToken_lt_gt(t);case 61:case 33:return this.readToken_eq_excl(t);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString(t)+"'")},pp$8.finishOp=function(t,e){var s=this.input.slice(this.pos,this.pos+e);return this.pos+=e,this.finishToken(t,s)},pp$8.readRegexp=function(){for(var t,e,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var a=this.input.charAt(this.pos);if(lineBreak.test(a)&&this.raise(s,"Unterminated regular expression"),t)t=!1;else{if("["===a)e=!0;else if("]"===a&&e)e=!1;else if("/"===a&&!e)break;t="\\"===a}++this.pos}var r=this.input.slice(s,this.pos);++this.pos;var i=this.pos,n=this.readWord1();this.containsEsc&&this.unexpected(i);var o=this.regexpState||(this.regexpState=new RegExpValidationState(this));o.reset(s,r,n),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var p=null;try{p=new RegExp(r,n)}catch(t){}return this.finishToken(types.regexp,{pattern:r,flags:n,value:p})},pp$8.readInt=function(t,e){for(var s=this.pos,a=0,r=0,i=null==e?1/0:e;r<i;++r){var n=this.input.charCodeAt(this.pos),o=void 0;if((o=n>=97?n-97+10:n>=65?n-65+10:n>=48&&n<=57?n-48:1/0)>=t)break;++this.pos,a=a*t+o}return this.pos===s||null!=e&&this.pos-s!==e?null:a},pp$8.readRadixNumber=function(t){this.pos+=2;var e=this.readInt(t);return null==e&&this.raise(this.start+2,"Expected number in radix "+t),isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(types.num,e)},pp$8.readNumber=function(t){var e=this.pos;t||null!==this.readInt(10)||this.raise(e,"Invalid number");var s=this.pos-e>=2&&48===this.input.charCodeAt(e);s&&this.strict&&this.raise(e,"Invalid number"),s&&/[89]/.test(this.input.slice(e,this.pos))&&(s=!1);var a=this.input.charCodeAt(this.pos);46!==a||s||(++this.pos,this.readInt(10),a=this.input.charCodeAt(this.pos)),69!==a&&101!==a||s||(43!==(a=this.input.charCodeAt(++this.pos))&&45!==a||++this.pos,null===this.readInt(10)&&this.raise(e,"Invalid number")),isIdentifierStart(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var r=this.input.slice(e,this.pos),i=s?parseInt(r,8):parseFloat(r);return this.finishToken(types.num,i)},pp$8.readCodePoint=function(){var t;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var e=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(e,"Code point out of bounds")}else t=this.readHexChar(4);return t},pp$8.readString=function(t){for(var e="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var a=this.input.charCodeAt(this.pos);if(a===t)break;92===a?(e+=this.input.slice(s,this.pos),e+=this.readEscapedChar(!1),s=this.pos):(isNewLine(a)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return e+=this.input.slice(s,this.pos++),this.finishToken(types.string,e)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$8.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(t){if(t!==INVALID_TEMPLATE_ESCAPE_ERROR)throw t;this.readInvalidTemplateToken()}this.inTemplateElement=!1},pp$8.invalidStringToken=function(t,e){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw INVALID_TEMPLATE_ESCAPE_ERROR;this.raise(t,e)},pp$8.readTmplToken=function(){for(var t="",e=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==types.template&&this.type!==types.invalidTemplate?(t+=this.input.slice(e,this.pos),this.finishToken(types.template,t)):36===s?(this.pos+=2,this.finishToken(types.dollarBraceL)):(++this.pos,this.finishToken(types.backQuote));if(92===s)t+=this.input.slice(e,this.pos),t+=this.readEscapedChar(!0),e=this.pos;else if(isNewLine(s)){switch(t+=this.input.slice(e,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),e=this.pos}else++this.pos}},pp$8.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if("{"!==this.input[this.pos+1])break;case"`":return this.finishToken(types.invalidTemplate,this.input.slice(this.start,this.pos))}this.raise(this.start,"Unterminated template")},pp$8.readEscapedChar=function(t){var e=this.input.charCodeAt(++this.pos);switch(++this.pos,e){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return codePointToString(this.readCodePoint());case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";default:if(e>=48&&e<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],a=parseInt(s,8);return a>255&&(s=s.slice(0,-1),a=parseInt(s,8)),this.pos+=s.length-1,e=this.input.charCodeAt(this.pos),"0"===s&&56!=e&&57!=e||!this.strict&&!t||this.invalidStringToken(this.pos-1-s.length,t?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(a)}return String.fromCharCode(e)}},pp$8.readHexChar=function(t){var e=this.pos,s=this.readInt(16,t);return null===s&&this.invalidStringToken(e,"Bad character escape sequence"),s},pp$8.readWord1=function(){this.containsEsc=!1;for(var t="",e=!0,s=this.pos,a=this.options.ecmaVersion>=6;this.pos<this.input.length;){var r=this.fullCharCodeAtPos();if(isIdentifierChar(r,a))this.pos+=r<=65535?1:2;else{if(92!==r)break;this.containsEsc=!0,t+=this.input.slice(s,this.pos);var i=this.pos;117!=this.input.charCodeAt(++this.pos)&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var n=this.readCodePoint();(e?isIdentifierStart:isIdentifierChar)(n,a)||this.invalidStringToken(i,"Invalid Unicode escape"),t+=codePointToString(n),s=this.pos}e=!1}return t+this.input.slice(s,this.pos)},pp$8.readWord=function(){var t=this.readWord1(),e=types.name;return this.keywords.test(t)&&(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+t),e=keywords$1[t]),this.finishToken(e,t)};var parse_dammit,LooseParser,pluginsLoose,version$1="5.5.3";function parse$2(t,e){return new Parser(e,t).parse()}function parseExpressionAt(t,e,s){var a=new Parser(s,t,e);return a.nextToken(),a.parseExpression()}function tokenizer(t,e){return new Parser(e,t)}function addLooseExports(t,e,s){parse_dammit=t,LooseParser=e,pluginsLoose=s}var acorn_es=Object.freeze({version:version$1,parse:parse$2,parseExpressionAt:parseExpressionAt,tokenizer:tokenizer,get parse_dammit(){return parse_dammit},get LooseParser(){return LooseParser},get pluginsLoose(){return pluginsLoose},addLooseExports:addLooseExports,Parser:Parser,plugins:plugins,defaultOptions:defaultOptions,Position:Position,SourceLocation:SourceLocation,getLineInfo:getLineInfo,Node:Node,TokenType:TokenType,tokTypes:types,keywordTypes:keywords$1,TokContext:TokContext,tokContexts:types$1,isIdentifierChar:isIdentifierChar,isIdentifierStart:isIdentifierStart,Token:Token,isNewLine:isNewLine,lineBreak:lineBreak,lineBreakG:lineBreakG,nonASCIIwhitespace:nonASCIIwhitespace}),isarray=Array.isArray||function(t){return"[object Array]"==Object.prototype.toString.call(t)},toStr=Object.prototype.toString,isArguments=function(t){var e=toStr.call(t),s="[object Arguments]"===e;return s||(s="[object Array]"!==e&&null!==t&&"object"==typeof t&&"number"==typeof t.length&&t.length>=0&&"[object Function]"===toStr.call(t.callee)),s},has$9=Object.prototype.hasOwnProperty,toStr$1=Object.prototype.toString,slice=Array.prototype.slice,isEnumerable=Object.prototype.propertyIsEnumerable,hasDontEnumBug=!isEnumerable.call({toString:null},"toString"),hasProtoEnumBug=isEnumerable.call(function(){},"prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],equalsConstructorPrototype=function(t){var e=t.constructor;return e&&e.prototype===t},excludedKeys={$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},hasAutomationEqualityBug=function(){if("undefined"==typeof window)return!1;for(var t in window)try{if(!excludedKeys["$"+t]&&has$9.call(window,t)&&null!==window[t]&&"object"==typeof window[t])try{equalsConstructorPrototype(window[t])}catch(t){return!0}}catch(t){return!0}return!1}(),equalsConstructorPrototypeIfNotBuggy=function(t){if("undefined"==typeof window||!hasAutomationEqualityBug)return equalsConstructorPrototype(t);try{return equalsConstructorPrototype(t)}catch(t){return!1}},keysShim=function(t){var e=null!==t&&"object"==typeof t,s="[object Function]"===toStr$1.call(t),a=isArguments(t),r=e&&"[object String]"===toStr$1.call(t),i=[];if(!e&&!s&&!a)throw new TypeError("Object.keys called on a non-object");var n=hasProtoEnumBug&&s;if(r&&t.length>0&&!has$9.call(t,0))for(var o=0;o<t.length;++o)i.push(String(o));if(a&&t.length>0)for(var p=0;p<t.length;++p)i.push(String(p));else for(var c in t)n&&"prototype"===c||!has$9.call(t,c)||i.push(String(c));if(hasDontEnumBug)for(var h=equalsConstructorPrototypeIfNotBuggy(t),l=0;l<dontEnums.length;++l)h&&"constructor"===dontEnums[l]||!has$9.call(t,dontEnums[l])||i.push(dontEnums[l]);return i};keysShim.shim=function(){if(Object.keys){if(!function(){return 2===(Object.keys(arguments)||"").length}(1,2)){var t=Object.keys;Object.keys=function(e){return isArguments(e)?t(slice.call(e)):t(e)}}}else Object.keys=keysShim;return Object.keys||keysShim};var objectKeys=keysShim,hasOwn=Object.prototype.hasOwnProperty,toString$1=Object.prototype.toString,foreach=function(t,e,s){if("[object Function]"!==toString$1.call(e))throw new TypeError("iterator must be a function");var a=t.length;if(a===+a)for(var r=0;r<a;r++)e.call(s,t[r],r,t);else for(var i in t)hasOwn.call(t,i)&&e.call(s,t[i],i,t)},parse$3=acorn_es.parse,falafel=function(t,e,s){"function"==typeof e&&(s=e,e={}),t&&"object"==typeof t&&"Buffer"===t.constructor.name?t=t.toString():t&&"object"==typeof t&&(t=(e=t).source,delete e.source),"string"!=typeof(t=void 0===t?e.source:t)&&(t=String(t)),e.parser&&(parse$3=e.parser.parse);var a=parse$3(t,e),r={chunks:t.split(""),toString:function(){return r.chunks.join("")},inspect:function(){return r.toString()}};return function walk(t,e){insertHelpers(t,e,r.chunks),foreach(objectKeys(t),function(e){if("parent"!==e){var s=t[e];isarray(s)?foreach(s,function(e){e&&"string"==typeof e.type&&walk(e,t)}):s&&"string"==typeof s.type&&walk(s,t)}}),s(t)}(a,void 0),r};function insertHelpers(t,e,s){if(t.parent=e,t.source=function(){return s.slice(t.start,t.end).join("")},t.update&&"object"==typeof t.update){var a=t.update;foreach(objectKeys(a),function(t){update[t]=a[t]}),t.update=update}else t.update=update;function update(e){s[t.start]=e;for(var a=t.start+1;a<t.end;a++)s[a]=""}}var ThundraSourceCodeInstrumenter_1=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const s="var __thundraEntryData__ = __thundraTraceEntry__({name: %s, path: %s, args: %s, argNames: %s});",a="if (typeof __thundraEntryData__ !== 'undefined') __thundraTraceLine__({ entryData: __thundraEntryData__, line: %d, source: %s, localVarNames: %s, localVarValues: %s, argNames: %s, argValues: %s });",r="__thundraTraceExit__({entryData: __thundraEntryData__, exception: %s, returnValue: %s, exceptionValue: %s});",i="/* ___%thundraArgNames%___ */",n="/* ___%thundraArgValues%___ */",o=new RegExp(i.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"g"),p=new RegExp(n.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"g"),c=["ExpressionStatement","BreakStatement","ContinueStatement","VariableDeclaration","ReturnStatement","ThrowStatement","TryStatement","FunctionDeclaration","IfStatement","WhileStatement","DoWhileStatement","ForStatement","ForInStatement","SwitchStatement","WithStatement"],h=" ",l=!1,u={FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",ArrowFunctionExpression:"ArrowFunctionExpression",AssignmentExpression:"AssignmentExpression",VariableDeclarator:"VariableDeclarator",CallExpression:"CallExpression",CatchClause:"CatchClause",ReturnStatement:"ReturnStatement",BlockStatement:"BlockStatement",VariableDeclaration:"VariableDeclaration"};e.default=class{constructor(t,e){this.updates=new Map,this.traceableConfigs=t,this.traceableConfigPrefix=e}shouldTraceFile(t){return null!==this.getThundraTraceableConfig(t+".*",TraceableConfig_1.TraceableConfigCheckLevel.FILE)}isFunctionNode(t){return(t.type===u.FunctionDeclaration||t.type===u.FunctionExpression||t.type===u.ArrowFunctionExpression)&&t.range}getFunctionName(t){if(!this.isFunctionNode(t))return;if(t.id)return t.id.name;if(t.type===u.FunctionDeclaration)return"";const e=t.parent;switch(e.type){case u.AssignmentExpression:if(e.left.range)return e.left.source().replace(/"/g,'\\"');break;case u.VariableDeclarator:return e.id.name;case u.CallExpression:return e.callee.id?e.callee.id.name:"[Anonymous]";default:if("number"==typeof e.length)return e.id?e.id.name:"[Anonymous]";if(e.key&&"Identifier"===e.key.type&&e.value===t&&e.key.name)return e.key.name}return"[Anonymous]"}addTraceHooks(t,e,a){const i=this;i.updates.clear();try{const n=t.split("\n"),c=new Set,g=new Map,d=falafel(t,{ranges:!0,locations:!0,ecmaVersion:8},function(t){const l=a?t.loc.start.line-1:t.loc.start.line;let d=i.getFunctionName(t);d&&d.startsWith("module.exports.")&&(d=d.substring("module.exports.".length));const T=d?i.getThundraTraceableConfig(e+"."+d,TraceableConfig_1.TraceableConfigCheckLevel.FUNCTION):null;if(d&&t.body.type===u.BlockStatement){if(null===T)return;const n=t.source().slice(0,t.body.range[0]-t.range[0]);let c=t.body.source();if(c=c.slice(1,c.length-1),a&&1===t.loc.start.line)return;const l=t.params.map(t=>"'"+t.name+"'").join(","),u=t.params.map(t=>t.name).join(",");let g="null",E="null";T.traceArgs&&(g="["+u+"]",E="["+l+"]");const m=util__default.format(s,JSON.stringify(d),JSON.stringify(e),g,E),A=util__default.format(r,"false","null","null"),f=h+m+h+c+h+A+h,_=util__default.format(r,"true","null",T.traceError?"__thundraEX__":"null");let S=n+"{"+h+"try {"+f+"} catch(__thundraEX__) {"+h+_+h+"throw __thundraEX__;"+h+"}"+h+"}";for(const t of i.updates.entries()){const e=t[0],s=e.type,a=e.pointer,r=t[1];s===NodePointer_1.LINE_POINTER_TYPE&&T.traceLineByLine&&S.includes(a)&&(S=S.replace(a,r),i.updates.delete(e)),s===NodePointer_1.RETURN_POINTER_TYPE&&T.traceReturnValue&&S.includes(a)&&(S=S.replace(a,r),i.updates.delete(e))}S=(S=S.replace(o,l)).replace(p,u),t.update(S)}else if(t.type===u.ReturnStatement){const e=i.checkTraceLine(t,c,g,a,n),s=Math.floor(1e4*Math.random()),o="/* ___%thundraLine@"+(a?t.loc.start.line-1:t.loc.start.line)+"%___ */",p="/* __%thundraReturn@"+s+"%__ */";if(t.argument){const a="__thundraTmp"+s+"__",n=util__default.format(r,"false",a,"null"),c="{"+h+"var "+a+" = "+t.argument.source()+";"+h+p+h+"return "+a+";"+h+"}";e?(t.update(o+" "+c),i.updates.set(new NodePointer_1.default(NodePointer_1.LINE_POINTER_TYPE,o),e),i.updates.set(new NodePointer_1.default(NodePointer_1.RETURN_POINTER_TYPE,p),n)):(t.update(c),i.updates.set(new NodePointer_1.default(NodePointer_1.RETURN_POINTER_TYPE,p),c))}else{const s="{"+util__default.format(r,"false",l,"null")+" "+t.source()+"}";e?(t.update(o+" "+p),i.updates.set(new NodePointer_1.default(NodePointer_1.LINE_POINTER_TYPE,o),e),i.updates.set(new NodePointer_1.default(NodePointer_1.RETURN_POINTER_TYPE,p),s)):(t.update(p),i.updates.set(new NodePointer_1.default(NodePointer_1.RETURN_POINTER_TYPE,p),s))}}else{const e=i.checkTraceLine(t,c,g,a,n);if(e){const s="/* ___%thundraLine@"+(a?t.loc.start.line-1:t.loc.start.line)+"%___ */";t.update(s+" "+t.source()),i.updates.set(new NodePointer_1.default(NodePointer_1.LINE_POINTER_TYPE,s),e)}}}).toString();return l&&(console.log("=================================================="),console.log("File: "+e),console.log("Original code: "+t),console.log("Instrumented code: "+d),console.log("==================================================")),d}catch(t){console.log(t)}finally{i.updates.clear()}}getThundraTraceableConfig(t,e){try{if(t.includes("node_modules")||!this.traceableConfigs)return null;if(this.traceableConfigPrefix&&TraceableConfig_1.TraceableConfigCheckLevel.FILE){const t=this.traceableConfigPrefix.split(",");for(const e of t)if(this.traceableConfigPrefix.startsWith(e))return new TraceableConfig_1.default(this.traceableConfigPrefix)}for(const s of this.traceableConfigs)if(e===TraceableConfig_1.TraceableConfigCheckLevel.FILE){if(s.shouldTraceFile(t))return s}else if(s.shouldTraceFunction(t))return s}catch(t){return null}return null}checkTraceLine(t,e,s,r,o){if(t.type===u.BlockStatement){for(const e of s.entries()){const a=e[0],r=e[1];r>=t.start&&r<=t.end&&s.delete(a)}return null}{let p=null;if(t.loc&&t.loc.start){const h=r?t.loc.start.line-1:t.loc.start.line;if(c.indexOf(t.type)>-1&&t.parent.type===u.BlockStatement&&!e.has(h)){const c=o[h].trim();let l="[",u="[",g=!1;for(const e of s.entries()){const s=e[0],a=e[1];this.shouldTraceLocalVariable(a,t,r)&&(g&&(l+=", ",u+=", "),l+="typeof "+s+" !== 'undefined' ? "+s+" : undefined",u+="'"+s+"'",g=!0)}l+="]",u+="]",p=util__default.format(a,h,JSON.stringify(c),u,l,"["+i+"]","["+n+"]"),e.add(h)}if(t.type===u.VariableDeclaration&&t.declarations)for(const e of t.declarations)(!e.init||e.init.type!==u.FunctionExpression&&e.init.type!==u.ArrowFunctionExpression)&&e.id&&e.id.name&&s.set(e.id.name,t.start)}return p}}shouldTraceLocalVariable(t,e,s){if(t<e.start){let a=this.getParentBlock(e),r=this.getParentBlock(a);for(;a&&(!s||r);){if(t>=a.start&&t<=a.end)return!0;a=this.getParentBlock(a),r=this.getParentBlock(a)}}return!1}getParentBlock(t){let e=t.parent;for(;e;){if(e&&e.type===u.BlockStatement)return e;e=e.parent}return null}}});unwrapExports(ThundraSourceCodeInstrumenter_1);var dist=createCommonjsModule(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.TraceableConfig=TraceableConfig_1.default,e.TraceableConfigCheckLevel=TraceableConfig_1.TraceableConfigCheckLevel,e.ThundraSourceCodeInstrumenter=ThundraSourceCodeInstrumenter_1.default});unwrapExports(dist);var dist_1=dist.TraceableConfig,dist_2=dist.TraceableConfigCheckLevel,dist_3=dist.ThundraSourceCodeInstrumenter;const get$a=require("lodash.get");class IntegrationConfig extends BasePluginConfig{constructor(t,e){super(get$a(e,"enabled",!0)),this.name=t,this.options=e}}const get$b=require("lodash.get");class TraceConfig extends BasePluginConfig{constructor(t){super(get$b(t=t||{},"enabled",!0)),this.disableRequest=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_REQUEST_SKIP)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_REQUEST_SKIP):t.disableRequest,this.disableResponse=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_RESPONSE_SKIP)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_RESPONSE_SKIP):t.disableResponse,this.maskRequest=t.maskRequest,this.maskResponse=t.maskResponse,this.disabledIntegrations=[],this.tracerConfig=get$b(t,"tracerConfig",{}),this.traceableConfigs=[],this.disableInstrumentation=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_INSTRUMENT_DISABLE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_INSTRUMENT_DISABLE):t.disableInstrumentation,this.disableHttp4xxError=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_4XX)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_4XX):t.disableHttp4xxError,this.disableHttp5xxError=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_5XX)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_TRACE_INTEGRATION_HTTP_ERROR_ON_5XX):t.disableHttp5xxError,this.maskRedisStatement=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_REDIS_STATEMENT)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_REDIS_STATEMENT):t.maskRedisStatement,this.maskRdbStatement=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_RDB_STATEMENT)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_RDB_STATEMENT):t.maskRdbStatement,this.maskDynamoDBStatement=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_DYNAMODB_STATEMENT)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_DYNAMODB_STATEMENT):t.maskDynamoDBStatement,this.maskElasticSearchStatement=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_ELASTIC_STATEMENT)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_ELASTIC_STATEMENT):t.maskElasticSearchStatement,this.maskMongoDBCommand=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_MONGODB_COMMAND)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_MONGODB_COMMAND):t.maskMongoDBCommand,this.dynamoDBTraceInjectionEnabled=Utils.getConfiguration(envVariableKeys.ENABLE_DYNAMODB_TRACE_INJECTION)?"true"===Utils.getConfiguration(envVariableKeys.ENABLE_DYNAMODB_TRACE_INJECTION):t.dynamoDBTraceInjectionEnabled,this.enableCloudWatchRequest=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_CLOUDWATCHLOG_REQUEST_ENABLE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_CLOUDWATCHLOG_REQUEST_ENABLE):t.enableCloudWatchRequest,this.enableFirehoseRequest=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_FIREHOSE_REQUEST_ENABLE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_FIREHOSE_REQUEST_ENABLE):t.enableFirehoseRequest,this.enableKinesisRequest=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_KINESIS_REQUEST_ENABLE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_KINESIS_REQUEST_ENABLE):t.enableKinesisRequest,this.maskSNSMessage=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_SNS_MESSAGE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_SNS_MESSAGE):t.maskSNSMessage,this.maskSQSMessage=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_SQS_MESSAGE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_SQS_MESSAGE):t.maskSQSMessage,this.maskAthenaStatement=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_ATHENA_STATEMENT)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_ATHENA_STATEMENT):t.maskAthenaStatement,this.maskLambdaPayload=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_LAMBDA_PAYLOAD)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_LAMBDA_PAYLOAD):t.maskLambdaPayload,this.maskHttpBody=Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_HTTP_BODY)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_MASK_HTTP_BODY):t.maskHttpBody,this.instrumentAWSOnLoad=Utils.getConfiguration(envVariableKeys.THUNDRA_AWS_INSTRUMENT_ON_LOAD)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AWS_INSTRUMENT_ON_LOAD):t.instrumentAWSOnLoad,this.httpPathDepth=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_HTTP_URL_DEPTH)?parseInt(Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_HTTP_URL_DEPTH),10):1,this.esPathDepth=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_ELASTICSEARCH_URL_DEPTH)?parseInt(Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_TRACE_INTEGRATIONS_ELASTICSEARCH_URL_DEPTH),10):1,this.runSamplerOnEachSpan=get$b(t,"runCustomSamplerOnEachSpan",!1),this.sampler=t.sampler;for(const t of Object.keys(process.env)){if(t.startsWith(envVariableKeys.THUNDRA_LAMBDA_TRACE_INSTRUMENT_CONFIG))try{this.traceableConfigs.push(dist_1.fromString(process.env[t]))}catch(e){ThundraLogger.getInstance().error(`Cannot parse trace def ${t}`)}if(t.startsWith(envVariableKeys.THUNDRA_LAMBDA_TRACE_INTEGRATIONS_DISABLE))try{this.disabledIntegrations.push(...this.parseIntegrationsEnvVariable(process.env[t]))}catch(e){ThundraLogger.getInstance().error(`Cannot parse trace def ${t}`)}}if(t.traceableConfigs)for(const e of t.traceableConfigs){const t=new dist_1(e.pattern);t.setPropertyFromConfig(e),this.traceableConfigs.push(t)}if(t.disabledIntegrations)for(const e of t.disabledIntegrations)"string"==typeof e?this.disabledIntegrations.push(new IntegrationConfig(e,{})):this.disabledIntegrations.push(new IntegrationConfig(e.name,e.opt));t.tracer&&(this.tracer=t.tracer)}parseIntegrationsEnvVariable(t){const e=t.substring(t.indexOf("[")+1,t.indexOf("]")).split(","),s=[];for(const t of e)s.push(new IntegrationConfig(t,{enabled:!1}));return s}isConfigDisabled(t){let e=!1;for(const s of this.disabledIntegrations)s.name!==t||s.enabled||(e=!0);return e}updateConfig(t){this.maskRequest=get$b(t,"traceConfig.maskRequest",this.maskRequest),this.maskResponse=get$b(t,"traceConfig.maskResponse",this.maskResponse),this.runSamplerOnEachSpan=get$b(t,"traceConfig.runCustomSamplerOnEachSpan",this.runSamplerOnEachSpan),this.sampler=get$b(t,"traceConfig.sampler",this.sampler)}}const koalas=require("koalas");class CountAwareSampler{constructor(t){this.countFreq=koalas(parseInt(Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_COUNT_AWARE_SAMPLER_COUNT_FREQ),10),t,100),this.counter=0}isSampled(){const t=this.counter%this.countFreq==0;return this.counter++,t}}const koalas$1=require("koalas");class TimeAwareSampler{constructor(t){this.timeFreq=koalas$1(parseInt(Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_TIME_AWARE_SAMPLER_TIME_FREQ),10),t,3e5),this.latestTime=0}isSampled(){const t=Date.now();return t>this.latestTime+this.timeFreq&&(this.latestTime=t,!0)}}class CompositeSampler{constructor(t,e){this.samplers=t,this.operator=void 0===e?SamplerCompositionOperator.OR:e}isSampled(t){if(this.operator===SamplerCompositionOperator.AND){let e=!0;for(const s of this.samplers)e=s.isSampled(t)&&e;return e}{let e=!1;for(const s of this.samplers)e=s.isSampled(t)||e;return e}}}var SamplerCompositionOperator;!function(t){t[t.AND=0]="AND",t[t.OR=1]="OR"}(SamplerCompositionOperator||(SamplerCompositionOperator={}));const get$c=require("lodash.get");class MetricConfig extends BasePluginConfig{constructor(t){super(get$c(t=t||{},"enabled",!0));const e=new CountAwareSampler,s=new TimeAwareSampler,a=new Array;a.push(e),a.push(s),this.sampler=t.sampler?t.sampler:new CompositeSampler(a)}updateConfig(t){this.sampler=get$c(t,"metricConfig.sampler",this.sampler),this.enabled=get$c(t,"metricConfig.enabled",this.enabled)}}class InvocationConfig extends BasePluginConfig{constructor(t){super(!0)}}const get$d=require("lodash.get");class LogConfig extends BasePluginConfig{constructor(t){super(get$d(t=t||{},"enabled",!0)),this.sampler=t.sampler}updateConfig(t){this.sampler=get$d(t,"logConfig.sampler",this.sampler),this.enabled=get$d(t,"logConfig.enabled",this.enabled)}}const get$e=require("lodash.get");class AwsXRayConfig extends BasePluginConfig{constructor(t){super(get$e(t=t||{},"enabled",!1))}updateConfig(t){this.enabled=get$e(t,"xrayConfig.enabled",this.enabled)}}const get$f=require("lodash.get"),koalas$2=require("koalas");class ThundraConfig{constructor(t){t=t||{},this.apiKey=Utils.getConfiguration(envVariableKeys.THUNDRA_APIKEY,t.apiKey),this.disableThundra=Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE):t.disableThundra,this.timeoutMargin=koalas$2(parseInt(Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TIMEOUT_MARGIN),10),t.timeoutMargin,TIMEOUT_MARGIN),this.traceConfig=new TraceConfig(t.traceConfig),this.metricConfig=new MetricConfig(t.metricConfig),this.logConfig=new LogConfig(t.logConfig),this.invocationConfig=new InvocationConfig(t.invocationConfig),this.xrayConfig=new AwsXRayConfig(t.xrayConfig),this.trustAllCert=get$f(t,"trustAllCert",!1),this.warmupAware=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_WARMUP_AWARE)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_WARMUP_AWARE):t.warmupAware,this.sampleTimedOutInvocations=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_SAMPLE_TIMED_OUT_INVOCATIONS)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_SAMPLE_TIMED_OUT_INVOCATIONS):t.sampleTimedOutInvocations,this.enableCompositeData=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_REPORT_REST_COMPOSITE_ENABLED)?"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_REPORT_REST_COMPOSITE_ENABLED):t.enableCompositeData}static updateConfig(t){const e=ThundraConfig.configUpdates;ThundraConfig.configUpdates=Object.assign({},e,t)}refreshConfig(){if(0===Object.keys(ThundraConfig.configUpdates).length)return;const t=ThundraConfig.configUpdates;this.traceConfig.updateConfig(t),this.metricConfig.updateConfig(t),this.logConfig.updateConfig(t),this.xrayConfig.updateConfig(t),this.trustAllCert=get$f(t,"trustAllCert",this.trustAllCert),ThundraConfig.configUpdates={}}}ThundraConfig.configUpdates={};const httpAgent=new http.Agent({keepAlive:!0}),httpsAgent=new https.Agent({maxCachedSessions:1,keepAlive:!0});class Reporter{constructor(t,e){this.MAX_MONITOR_DATA_BATCH_SIZE=100,this.reports=[],this.config=t||new ThundraConfig({}),this.useHttps="https:"===(e?e.protocol:URL.protocol),this.requestOptions=this.createRequestOptions(),this.connectionRetryCount=0,this.latestReportingLimitedMinute=-1}createRequestOptions(t){const e=this.config.enableCompositeData?COMPOSITE_MONITORING_DATA_PATH:MONITORING_DATA_PATH;return{method:"POST",hostname:t?t.hostname:URL.hostname,path:(t?t.pathname:URL.pathname)+e,port:parseInt(t?t.port:URL.port,0),headers:{"Content-Type":"application/json",Authorization:"ApiKey "+this.config.apiKey},agent:this.useHttps?httpsAgent:httpAgent,createConnection:(t,e)=>{try{const s=net.createConnection(t.port,t.hostname);return s.setNoDelay(!0),s.setKeepAlive(!0),e(null,s),s}catch(t){throw e(t,null),t}}}}addReport(t){this.reports=[...this.reports,t]}getCompositeBatchedReports(){const t=[],e=this.reports.slice(0),s=Math.ceil(e.length/this.MAX_MONITOR_DATA_BATCH_SIZE),a=this.reports.filter(t=>t.data.type===MonitoringDataType$1.INVOCATION)[0],r=Utils.initCompositeMonitoringData(a.data);for(let a=0;a<s;a++){const s=Utils.initCompositeMonitoringData(r),a=[];for(let t=1;t<this.MAX_MONITOR_DATA_BATCH_SIZE;t++){const t=e.shift();if(!t)break;a.push(Utils.stripCommonFields(t.data))}s.allMonitoringData=a;const i=Utils.generateReport(s,this.config.apiKey);t.push(i)}return t}getBatchedReports(){const t=[],e=this.reports.slice(0),s=Math.ceil(e.length/this.MAX_MONITOR_DATA_BATCH_SIZE);for(let a=0;a<s;a++){const s=[];for(let t=1;t<this.MAX_MONITOR_DATA_BATCH_SIZE;t++){const t=e.shift();if(!t)break;s.push(t)}t.push(s)}return t}sendReports(){return __awaiter(this,void 0,void 0,function*(){let t=[];const e=this.config.enableCompositeData;try{t=e?this.getCompositeBatchedReports():this.getBatchedReports()}catch(t){ThundraLogger.getInstance().error(`Cannot create batch request will send no report. ${t}`)}const s="true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_REPORT_CLOUDWATCH_ENABLE),a=[],r=Math.floor(Date.now()/1e3);t.forEach(t=>{s?a.push(this.writeBatchToCW(t,e)):r>this.latestReportingLimitedMinute?a.push(this.request(t)):ThundraLogger.getInstance().error("Skipped sending monitoring data temporarily as it hits the limit")}),yield Promise.all(a).catch(t=>__awaiter(this,void 0,void 0,function*(){if(0===this.connectionRetryCount&&"ECONNRESET"===t.code)return ThundraLogger.getInstance().debug("Keep Alive connection reset by server. Will send monitoring data again."),this.connectionRetryCount++,yield this.sendReports(),void(this.connectionRetryCount=0);ThundraLogger.getInstance().error(t)})),this.connectionRetryCount=0})}request(t){return new Promise((e,s)=>{let a;const r=t=>{let a="";t.on("data",t=>{a+=t}),t.on("end",()=>(429===t.statusCode&&(this.latestReportingLimitedMinute=Math.floor(Date.now()/1e3)),200!==t.statusCode?(ThundraLogger.getInstance().debug(JSON.stringify(this.reports)),s({status:t.statusCode,data:a})):e({status:t.statusCode,data:a})))};(a=this.useHttps?https.request(this.requestOptions,r):http.request(this.requestOptions,r)).on("error",t=>s(t));try{a.write(JSON.stringify(t)),a.end()}catch(t){ThundraLogger.getInstance().error("Cannot serialize report data. "+t)}})}writeBatchToCW(t,e){return new Promise((s,a)=>{try{if(e){const e="\n"+JSON.stringify(t).replace(/\r?\n|\r/g,"")+"\n";process.stdout.write(e)}else for(const e of t){const t="\n"+JSON.stringify(e).replace(/\r?\n|\r/g,"")+"\n";process.stdout.write(t)}return s()}catch(t){return ThundraLogger.getInstance().error("Cannot write report data to CW. "+t),a(t)}})}}class TimeoutError extends Error{constructor(t){super(),this.message=t,this.name="TimeoutError",Error.captureStackTrace(this,TimeoutError),Object.setPrototypeOf(this,TimeoutError.prototype)}}class ThundraWrapper{constructor(t,e,s,a,r,i,n){this.wrappedCallback=(t,e)=>{this.report(t,e,()=>{this.invokeCallback(t,e)})},this.originalThis=t,this.originalEvent=e,this.originalContext=s,this.originalCallback=a,this.originalFunction=r,this.config=n.config?n.config:new ThundraConfig({}),this.plugins=i,this.pluginContext=n,this.pluginContext.maxMemory=parseInt(s.memoryLimitInMB,10),this.reported=!1,this.reporter=new Reporter(n.config),this.wrappedContext=Object.assign({},s,{done:(t,e)=>{this.report(t,e,()=>{this.originalContext.done(t,e)})},succeed:t=>{this.report(null,t,()=>{this.originalContext.succeed(t)})},fail:t=>{this.report(t,null,()=>{this.originalContext.fail(t)})}});const o=this;this.wrappedContext=Object.assign({set callbackWaitsForEmptyEventLoop(t){o.originalContext.callbackWaitsForEmptyEventLoop=t},get callbackWaitsForEmptyEventLoop(){return o.originalContext.callbackWaitsForEmptyEventLoop}},this.wrappedContext),this.timeout=this.setupTimeoutHandler(this),InvocationSupport.setFunctionName(this.originalContext.functionName),"true"===Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_DEBUGGER_ENABLE)&&this.initDebugger()}invokeCallback(t,e){"function"==typeof this.originalCallback&&this.originalCallback(t,e)}onFinish(t,e){t&&this.reject?this.reject(t):this.resolve&&this.resolve(e),this.finishDebuggerProxyIfAvailable()}initDebugger(){try{if(!fs.existsSync("/opt/socat"))throw new Error('"Socat" is not exist under "/opt/socat". Please be sure that "socat" layer is added or it is available under "/opt/socat"');this.inspector=require("inspector"),this.spawn=require("child_process").spawn;const t=Utils.getNumericConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_DEBUGGER_PORT,DEFAULT_THUNDRA_AGENT_LAMBDA_DEBUGGER_PORT),e=Utils.getConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_DEBUGGER_BROKER_HOST,DEFAULT_THUNDRA_AGENT_LAMBDA_DEBUGGER_HOST),s=Utils.getNumericConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_DEBUGGER_BROKER_PORT,-1),a=Utils.getNumericConfiguration(envVariableKeys.THUNDRA_AGENT_LAMBDA_DEBUGGER_WAIT_MAX,6e4);if(-1===s)throw new Error("For debugging, you must set debug broker port through 'thundra_agent_lambda_debug_broker_port' environment variable");this.debuggerPort=t,this.debuggerMaxWaitTime=a,this.brokerPort=s,this.brokerHost=e}catch(t){this.spawn=null,this.inspector=null}}getDebuggerProxyIOMetrics(){try{const t=fs.readFileSync("/proc/"+this.debuggerProxy.pid+"/io","utf8").split("\n");return{rchar:t[0],wchar:t[1]}}catch(t){return null}}waitForDebugger(){const t=require("system-sleep");let e=0,s=0,a=!1;const r=ThundraLogger.getInstance();r.info("Waiting for debugger to handshake ...");const i=Date.now();for(;Date.now()-i<this.debuggerMaxWaitTime;){try{const i=this.getDebuggerProxyIOMetrics();if(!i){t(1e3);break}if(0!==e&&0!==s&&i.rchar===e&&i.wchar===s){a=!0;break}e=i.rchar,s=i.wchar}catch(t){r.error(t);break}t(1e3)}a?r.info("Completed debugger handshake"):r.error("Couldn't complete debugger handshake in "+this.debuggerMaxWaitTime+" milliseconds.")}startDebuggerProxyIfAvailable(){if(this.debuggerProxy&&this.finishDebuggerProxyIfAvailable(),this.spawn&&this.inspector)try{this.debuggerProxy=this.spawn("/opt/socat",["TCP:"+this.brokerHost+":"+this.brokerPort,"TCP:localhost:"+this.debuggerPort+",forever"],{detached:!0}),this.inspector.open(this.debuggerPort,"localhost",!0),this.waitForDebugger()}catch(t){this.debuggerProxy=null,ThundraLogger.getInstance().error(t)}}finishDebuggerProxyIfAvailable(){try{this.inspector&&this.inspector.close()}catch(t){ThundraLogger.getInstance().error(t)}if(this.debuggerProxy)try{this.debuggerProxy.kill("SIGKILL")}catch(t){ThundraLogger.getInstance().error(t)}finally{this.debuggerProxy=null}}invoke(){this.config.refreshConfig(),this.startDebuggerProxyIfAvailable();const t={originalContext:this.originalContext,originalEvent:this.originalEvent,reporter:this.reporter};return this.resetTime(),InvocationSupport.setErrorenous(!1),this.resolve=void 0,this.reject=void 0,new Promise((e,s)=>{this.resolve=e,this.reject=s,this.executeHook("before-invocation",t,!1).then(()=>{this.pluginContext.requestCount+=1;try{const t=this.originalFunction.call(this.originalThis,this.originalEvent,this.wrappedContext,this.wrappedCallback);t&&void 0!==t.then&&"function"==typeof t.then&&t.then(this.wrappedContext.succeed,this.wrappedContext.fail)}catch(t){this.report(t,null,null)}}).catch(t=>{ThundraLogger.getInstance().debug(t);const s=this.originalFunction.call(this.originalThis,this.originalEvent,this.originalContext,this.originalCallback);e(s)})})}executeHook(t,e,s){return __awaiter(this,void 0,void 0,function*(){this.plugins.sort((t,e)=>t.pluginOrder>e.pluginOrder?1:-1),s&&this.plugins.reverse(),yield Promise.all(this.plugins.map(s=>{if(s.hooks&&s.hooks[t])return s.hooks[t](e)}))})}executeAfteInvocationAndReport(t){return __awaiter(this,void 0,void 0,function*(){t.error?InvocationSupport.setErrorenous(!0):InvocationSupport.setErrorenous(!1),yield this.executeHook("after-invocation",t,!0),this.resetTime(),yield this.reporter.sendReports(),InvocationSupport.setErrorenous(!1)})}resetTime(){this.pluginContext.invocationStartTimestamp=void 0,this.pluginContext.invocationFinishTimestamp=void 0}report(t,e,s){return __awaiter(this,void 0,void 0,function*(){if(!this.reported)try{this.reported=!0;let a={error:t,originalEvent:this.originalEvent,response:e};this.isErrorResponse(e)&&(a={error:new HttpError("Lambda returned with error response."),originalEvent:this.originalEvent,response:e}),this.config.sampleTimedOutInvocations?t instanceof TimeoutError?yield this.executeAfteInvocationAndReport(a):this.plugins.map(t=>{t.destroy&&"function"==typeof t.destroy&&t.destroy()}):yield this.executeAfteInvocationAndReport(a),this.timeout&&clearTimeout(this.timeout),"function"==typeof s&&s()}finally{this.onFinish(t,e)}})}isErrorResponse(t){let e=!1;if(this.isValidResponse(t)&&"string"==typeof t.body){const s=t.statusCode.toString();(s.startsWith("4")||s.startsWith("5"))&&(e=!0)}else this.isValidResponse(t)&&(e=!0);return e}isValidResponse(t){return!!t&&(t.statusCode&&"number"==typeof t.statusCode&&t.body)}setupTimeoutHandler(t){const{originalContext:e,pluginContext:s}=t,{getRemainingTimeInMillis:a=(()=>0)}=e;if(s.timeoutMargin<1||a()<10)return;const r=Math.max(0,a()-s.timeoutMargin),i=Math.min(r,899900);return setTimeout(()=>{t.report(new TimeoutError("Lambda is timed out."),null,null),t.reported=!1},i)}}class ThundraSpan extends lib_5{constructor(t,e){super();const s=(e=e||{}).startTime||Date.now(),a=e.operationName?e.operationName:"",r=e.parent||null,i=e.tags||{};this.parentTracer=t,this.operationName=a,this.tags=Object.assign({},i),this.startTime=s,this.finishTime=0,this.rootTraceId=e.rootTraceId||null,this.transactionId=e.transactionId||null,this.spanContext=this._createContext(r),this.logs=[],this.className=e.className,this.domainName=e.domainName,this.order=e.order}getOperationName(){return this.operationName}getTag(t){return this.tags[t]}setErrorTag(t){if(t instanceof Error){const e=Utils.parseError(t);this.setTag("error",!0),this.setTag("error.kind",e.errorType),this.setTag("error.message",e.errorMessage),e.code&&this.setTag("error.code",e.code),t.stack&&this.setTag("error.stack",e.stack)}}_createContext(t){if(!this.parentTracer)return;let e;return e=new ThundraSpanContext(t?{traceId:t.traceId,spanId:Utils.generateId(),parentId:t.spanId,sampled:t.sampled,baggageItems:Object.assign({},t.baggageItems),transactionId:t.transactionId}:{traceId:this.rootTraceId,spanId:Utils.generateId(),transactionId:this.transactionId,sampled:this.parentTracer._isSampled(this)})}_context(){return this.spanContext}_tracer(){return this.parentTracer}_setDomainName(t){this.domainName=t}_setClassName(t){this.className=t}_setOperationName(t){this.operationName=t}_setBaggageItem(t,e){this.spanContext.baggageItems[t]=e}_getBaggageItem(t){return this.spanContext.baggageItems[t]}_addTags(t){try{Object.keys(t).forEach(e=>{this.tags[e]=t[e]})}catch(t){ThundraLogger.getInstance().debug(t)}}_finish(t=Date.now()){0===this.finishTime?(this.finishTime=t,this.spanContext.sampled&&this.parentTracer._record(this,{disableActiveSpanHandling:!1})):ThundraLogger.getInstance().debug("Span is already finished.")}_initialized(){this.parentTracer._initialized(this)}close(t=Date.now()){0===this.finishTime?(this.finishTime=t,this.spanContext.sampled&&this.parentTracer._record(this,{disableActiveSpanHandling:!0})):ThundraLogger.getInstance().debug("Span is already closed.")}closeWithCallback(t,e,s,a=Date.now()){0===this.finishTime?(this.finishTime=a,this.spanContext.sampled&&this.parentTracer._record(this,{disableActiveSpanHandling:!0,me:t,callback:e,args:s})):ThundraLogger.getInstance().debug("Span is already closed.")}isFinished(){return 0!==this.finishTime}getDuration(){return 0!==this.finishTime?this.finishTime-this.startTime:Date.now()-this.startTime}_log(t,e=Date.now()){(t||"object"==typeof t)&&(t.timestamp=e,this.logs.push(t))}}var SpanEvent;!function(t){t[t.SPAN_START=0]="SPAN_START",t[t.SPAN_INITIALIZE=1]="SPAN_INITIALIZE",t[t.SPAN_FINISH=2]="SPAN_FINISH"}(SpanEvent||(SpanEvent={}));class Stack{constructor(){this.store=[]}push(t){this.store.push(t)}pop(){return this.store.pop()}peek(){return 0===this.store.length?void 0:this.store[this.store.length-1]}clear(){this.store=[]}}class ThundraRecorder{constructor(){this.spanOrder=1,this.listeners=[],this.activeSpanStack=new Stack,this.spanList=[]}record(t,e,s){if(s=s||{},!t)return void ThundraLogger.getInstance().error("Undefined span.");let a=!0;if(e===SpanEvent.SPAN_START){ThundraLogger.getInstance().debug(`Span with name ${t.operationName} started.`),s&&!0===s.disableActiveSpanHandling||this.activeSpanStack.push(t),t.order=this.spanOrder++,this.spanList.push(t);for(const e of this.listeners){const r=e.onSpanStarted(t,s.me,s.callback,s.args,!a);a&&(a=!r)}a&&"function"==typeof s.callback&&s.callback.apply(s.me,s.args)}else if(e===SpanEvent.SPAN_INITIALIZE){ThundraLogger.getInstance().debug(`Span with name ${t.operationName} initialized.`);for(const e of this.listeners){const r=e.onSpanInitialized(t,s.me,s.callback,s.args,!a);a&&(a=!r)}a&&"function"==typeof s.callback&&s.callback.apply(s.me,s.args)}else if(e===SpanEvent.SPAN_FINISH){ThundraLogger.getInstance().debug(`Span with name ${t.operationName} finished.`),s&&!0===s.disableActiveSpanHandling||this.activeSpanStack.pop();for(const e of this.listeners){const r=e.onSpanFinished(t,s.me,s.callback,s.args,!a);a&&(a=!r)}a&&"function"==typeof s.callback&&s.callback.apply(s.me,s.args)}}getSpanList(){return this.spanList}getActiveSpan(){return this.activeSpanStack.peek()}setActiveSpan(t){this.activeSpanStack.push(t)}removeActiveSpan(){return this.activeSpanStack.pop()}destroy(){this.activeSpanStack.clear(),this.spanList=[],this.spanOrder=1}addSpanListener(t){this.listeners.push(t)}}class TextMapPropagator{inject(t,e){t.traceId&&(e[TextMapPropagator.TRACE_ID_KEY]=t.traceId.toString()),t.spanId&&(e[TextMapPropagator.SPAN_ID_KEY]=t.spanId.toString()),t.transactionId&&(e[TextMapPropagator.TRANSACTION_ID_KEY]=t.transactionId.toString()),this._injectBaggageItems(t,e)}extract(t){if(!t[TextMapPropagator.TRACE_ID_KEY]||!t[TextMapPropagator.SPAN_ID_KEY]||!t[TextMapPropagator.TRANSACTION_ID_KEY])return null;const e=new ThundraSpanContext({traceId:t[TextMapPropagator.TRACE_ID_KEY],spanId:t[TextMapPropagator.SPAN_ID_KEY],transactionId:t[TextMapPropagator.TRANSACTION_ID_KEY]});return this._extractBaggageItems(t,e),e}_injectBaggageItems(t,e){t.baggageItems&&Object.keys(t.baggageItems).forEach(s=>{e[TextMapPropagator.BAGGAGE_PREFIX+s]=String(t.baggageItems[s])})}_extractBaggageItems(t,e){Object.keys(t).forEach(s=>{const a=s.match(TextMapPropagator.BAGGAGE_PATTERN);a&&(e.baggageItems[a[1]]=t[s])})}}TextMapPropagator.TRACE_ID_KEY="x-thundra-trace-id",TextMapPropagator.TRANSACTION_ID_KEY="x-thundra-transaction-id",TextMapPropagator.SPAN_ID_KEY="x-thundra-span-id",TextMapPropagator.BAGGAGE_PREFIX="x-thundra-baggage-",TextMapPropagator.BAGGAGE_PATTERN=new RegExp(`^${TextMapPropagator.BAGGAGE_PREFIX}(.+)$`);class HttpPropagator extends TextMapPropagator{}class BinaryPropagator{inject(t,e){}extract(t){return null}}class ThundraTracer extends lib_7{constructor(t={}){super(),this.invokeCallback=!0,this.tags=t.tags,this.recorder=t.recorder?t.recorder:new ThundraRecorder,this.activeSpans=new Map,this.propagators={[void 0]:new TextMapPropagator,[void 0]:new HttpPropagator,[void 0]:new BinaryPropagator}}getActiveSpan(){return this.recorder.getActiveSpan()}setActiveSpan(t){this.recorder.setActiveSpan(t)}removeActiveSpan(){return this.recorder.removeActiveSpan()}finishSpan(){this.getActiveSpan()&&this.getActiveSpan().finish()}getRecorder(){return this.recorder}destroy(){this.recorder.destroy(),this.activeSpans.clear()}addSpanListener(t){if(!t)throw new Error("No listener provided.");if(!this.shouldInvokeCallback())throw new Error("There can be only one Span Listener which is responsible for invoking span callback");this.recorder.addSpanListener(t)}wrapper(t,e){const s=this.getActiveSpan(),a=this.startSpan(t,{childOf:s});return(...t)=>{try{const s=e(...t);return a.finish(),s}catch(t){throw a.finish(),t}}}_startSpan(t,e){const s={};let a;const r=e.rootTraceId?e.rootTraceId:Utils.generateId(),i=e.parentContext?e.parentContext:Utils.getParentContext(e.references);if(!e.propagated&&i&&!this.activeSpans.get(i.spanId))throw new Error("Invalid spanId : "+i.spanId);return a=new ThundraSpan(this,i?{operationName:e.operationName||t,parent:i,tags:Object.assign(s,this.tags,e.tags),startTime:e.startTime,rootTraceId:r,className:e.className,domainName:e.domainName,transactionId:this.transactionId}:{operationName:t,parent:this.getActiveSpan()?this.getActiveSpan().spanContext:null,tags:Object.assign(s,this.tags,e.tags),rootTraceId:r,startTime:Date.now(),className:e.className,domainName:e.domainName,transactionId:this.transactionId}),this.recorder.record(a,SpanEvent.SPAN_START,{disableActiveSpanHandling:!0===e.disableActiveStart,me:e.me,callback:e.callback,args:e.args}),this.activeSpans.set(a.spanContext.spanId,a),a}_record(t,e){this.recorder.record(t,SpanEvent.SPAN_FINISH,e),this.activeSpans.delete(t.spanContext.spanId)}_initialized(t,e){e=e||{},this.recorder.record(t,SpanEvent.SPAN_INITIALIZE,e)}_inject(t,e,s){try{this.propagators[e].inject(t,s)}catch(t){ThundraLogger.getInstance().error(t)}return this}_extract(t,e){try{return this.propagators[t].extract(e)}catch(t){return ThundraLogger.getInstance().error(t),null}}_isSampled(t){return!0}shouldInvokeCallback(){return this.invokeCallback}disableInvokeCallback(){this.invokeCallback=!1}}class Argument{constructor(t,e,s){this.name=t,this.type=e,this.value=s}}class ReturnValue{constructor(t,e){this.type=t,this.value=e}}const Module=require("module"),path$3=require("path"),get$g=require("lodash.get"),TRACE_DEF_SEPERATOR=".";class Instrumenter{constructor(t){const e=get$g(t,"traceableConfigs"),s=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_INSTRUMENT_FILE_PREFIX);this.sourceCodeInstrumenter=new dist_3(e,s),this.tracer=get$g(t,"tracer")}unhookModuleCompile(){Module.prototype._compile=this.origCompile}hookModuleCompile(){this.origCompile=Module.prototype._compile;const t=this;t.setGlobalFunction(),Module.prototype._compile=function(e,s){let a=path$3.relative(process.cwd(),s).replace(/\//g,TRACE_DEF_SEPERATOR);a=a.replace(".js","");const r=t.sourceCodeInstrumenter;if(r.shouldTraceFile(a)){let t=!0;2===Module.wrapper.length?e=Module.wrapper[0]+"\n"+e+Module.wrapper[1]:t=!1;try{e=r.addTraceHooks(e,a,t),2===Module.wrapper.length&&(e=e.substring(Module.wrapper[0].length,e.length-Module.wrapper[1].length))}catch(t){ThundraLogger.getInstance().debug(t)}}t.origCompile.call(this,e,s)}}setGlobalFunction(){const t=this.tracer;global.__thundraTraceEntry__=function(e){try{const s=t.startSpan(e.path+"."+e.name);s.className="Method";const a=[];if(e.args)for(let t=0;t<e.args.length;t++){const s=typeof e.args[t];let r=e.args[t];"function"===s&&(r=r.toString()),a.push(new Argument(e.argNames[t],s,r))}return s.setTag(ARGS_TAG_NAME,a),{span:s}}catch(e){t.finishSpan()}},global.__thundraTraceLine__=function(e){try{const s=e.entryData;s.latestLineSpan&&s.latestLineSpan.finish();const a=e.line,r=e.source,i=new Array,n=new Array,o=new Array,p=e.localVarNames,c=e.localVarValues,h=e.argNames,l=e.argValues;if(h&&n.push(...h),l&&o.push(...l),p&&n.push(...p),c&&o.push(...c),n.length===o.length)for(let t=0;t<n.length;t++){const e=n[t],s=o[t];let a=s?s.toString():null;try{a=JSON.stringify(s);try{a=JSON.parse(a)}catch(t){}}catch(t){}const r={name:e,value:a,type:typeof s};i.push(r)}const u={line:a,source:r,localVars:i},g=t.startSpan("@"+e.line);g.className="Line",g.setTag("method.lines",[u]),s.latestLineSpan=g}catch(e){t.finishSpan()}},global.__thundraTraceExit__=function(e){try{const s=e.entryData;s.latestLineSpan&&(e.exception&&s.latestLineSpan.setErrorTag(e.exceptionValue),s.latestLineSpan.finish());const a=s&&s.span?s.span:t.getActiveSpan();e.exception?a.setErrorTag(e.exceptionValue):e.returnValue&&a.setTag(RETURN_VALUE_TAG_NAME,new ReturnValue(typeof e.returnValue,e.returnValue)),a.finish()}catch(e){t.finishSpan()}}}}const get$h=require("lodash.get");class Trace{constructor(t){this.pluginOrder=1,this.setPluginContext=t=>{this.pluginContext=t,this.apiKey=t.apiKey},this.beforeInvocation=t=>{this.destroy();const{originalContext:e,originalEvent:s,reporter:a}=t;e.awsRequestId&&"id"!==e.awsRequestId||(e.awsRequestId=Utils.generateId());const r=this.extractSpanContext(s,e);r?(this.pluginContext.traceId=r.traceId,this.pluginContext.transactionId="true"===Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_TRACE_USE_PROPAGATED_TRANSACTION_ID)?r.transactionId:Utils.generateId(),this.tracer.transactionId=this.pluginContext.transactionId,this.rootSpan=this.tracer._startSpan(e.functionName,{propagated:!0,parentContext:r,rootTraceId:this.pluginContext.traceId,domainName:DomainNames.API,className:ClassNames.LAMBDA})):(this.pluginContext.traceId=Utils.generateId(),this.pluginContext.transactionId=Utils.generateId(),this.tracer.transactionId=this.pluginContext.transactionId,this.rootSpan=this.tracer._startSpan(e.functionName,{rootTraceId:this.pluginContext.traceId,domainName:DomainNames.API,className:ClassNames.LAMBDA})),this.pluginContext.spanId=this.rootSpan.spanContext.spanId,this.reporter=a,this.startTimestamp=this.pluginContext.invocationStartTimestamp,this.rootSpan.startTime=this.pluginContext.invocationStartTimestamp,this.rootSpan.tags["aws.lambda.memory_limit"]=parseInt(e.memoryLimitInMB,10),this.rootSpan.tags["aws.lambda.arn"]=e.invokedFunctionArn,this.rootSpan.tags["aws.lambda.invocation.coldstart"]=0===this.pluginContext.requestCount,this.rootSpan.tags["aws.region"]=this.pluginContext.applicationRegion,this.rootSpan.tags["aws.lambda.log_group_name"]=e.logGroupName,this.rootSpan.tags["aws.lambda.name"]=e.functionName,this.rootSpan.tags["aws.lambda.log_stream_name"]=e.logStreamName,this.rootSpan.tags["aws.lambda.invocation.request_id"]=e.awsRequestId,this.rootSpan.tags["aws.lambda.invocation.coldstart"]=0===this.pluginContext.requestCount,this.rootSpan.tags["aws.lambda.invocation.request"]=this.getRequest(s),this.triggerClassName=this.injectTriggerTags(this.rootSpan,s,e)},this.afterInvocation=t=>{let e=t.response;const s=t.originalEvent;if(InvocationSupport.hasError()&&(this.rootSpan.tags.error=!0,this.rootSpan.tags["error.message"]=InvocationSupport.error.errorMessage,this.rootSpan.tags["error.kind"]=InvocationSupport.error.errorType,InvocationSupport.error.code&&(this.rootSpan.tags["error.code"]=InvocationSupport.error.code),InvocationSupport.error.stack&&(this.rootSpan.tags["error.stack"]=InvocationSupport.error.stack),InvocationSupport.clearError()),t.error){const s=Utils.parseError(t.error);t.error instanceof HttpError||(e=s),this.rootSpan.tags.error=!0,this.rootSpan.tags["error.message"]=s.errorMessage,this.rootSpan.tags["error.kind"]=s.errorType,s.code&&(this.rootSpan.tags["error.code"]=s.code),s.stack&&(this.rootSpan.tags["error.stack"]=s.stack)}this.triggerClassName===ClassNames.APIGATEWAY&&this.processAPIGWResponse(e,s),this.rootSpan.tags["aws.lambda.invocation.response"]=this.getResponse(e),this.finishTimestamp=this.pluginContext.invocationFinishTimestamp,this.rootSpan.finish(),this.rootSpan.finishTime=this.pluginContext.invocationFinishTimestamp;const a=this.tracer.getRecorder().getSpanList(),r=this.config&&this.config.sampler&&"function"==typeof this.config.sampler.isSampled;if(!r||this.config.sampler.isSampled(this.rootSpan))for(const t of a)if(t){if(r&&this.config.runSamplerOnEachSpan&&this.config.sampler.isSampled(t)){ThundraLogger.getInstance().debug(`Filtering span with name ${t.getOperationName()} due to custom sampling configuration`);continue}const e=this.buildSpanData(t,this.pluginContext),s=Utils.generateReport(e,this.apiKey);this.report(s)}this.destroy()},this.hooks={"before-invocation":this.beforeInvocation,"after-invocation":this.afterInvocation};const e=t?t.tracerConfig:{};this.config=t,this.tracer=new ThundraTracer(e),this.config.tracer=this.tracer,this.initIntegrations(),lib_1(this.tracer),Utils.registerSpanListenersFromConfigurations(this.tracer)}initIntegrations(){if(!this.config.disableInstrumentation||"true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE_TRACE)){this.integrationsMap=new Map;for(const t of Object.keys(INTEGRATIONS)){const e=INTEGRATIONS[t];if(e&&!this.integrationsMap.get(t)&&!this.config.isConfigDisabled(t)){const s=new e(this.config);this.integrationsMap.set(t,s)}}this.instrumenter=new Instrumenter(this.config),this.instrumenter.hookModuleCompile()}}report(t){this.reporter.addReport(t)}processAPIGWResponse(t,e){try{const s=get$h(t,"headers",{});s[TriggerHeaderTags.RESOURCE_NAME]=e.resource,t.headers=s}catch(t){}}buildSpanData(t,e){const s=Utils.initMonitoringData(this.pluginContext,MonitoringDataType$1.SPAN);return s.id=t.spanContext.spanId,s.traceId=e.traceId,s.transactionId=e.transactionId,s.parentSpanId=t.spanContext.parentId,s.spanOrder=t.order,s.domainName=t.domainName?t.domainName:"",s.className=t.className?t.className:"",s.serviceName=this.rootSpan.operationName,s.operationName=t.operationName,s.startTimestamp=t.startTime,s.duration=t.getDuration(),s.finishTimestamp=t.finishTime,s.tags=t.tags,s.logs=t.logs,s}destroy(){this.config&&!this.config.disableInstrumentation&&(this.tracer.destroy(),"function"==typeof this.instrumenter.unhookModuleCompile&&this.instrumenter.unhookModuleCompile()),this.triggerClassName=void 0}getRequest(t){const e=this.config;if(e&&e.disableRequest)return null;if(e&&e.maskRequest&&"function"==typeof e.maskRequest){const s=JSON.parse(JSON.stringify(t));return e.maskRequest.call(this,s)}let s=!0;return this.triggerClassName!==ClassNames.CLOUDWATCH||e.enableFirehoseRequest||(s=!1),this.triggerClassName!==ClassNames.FIREHOSE||e.enableFirehoseRequest||(s=!1),this.triggerClassName!==ClassNames.KINESIS||e.enableKinesisRequest||(s=!1),s?t:null}getResponse(t){const e=this.config;if(e&&e.disableResponse)return null;if(e&&e.maskResponse&&"function"==typeof e.maskResponse){const s=JSON.parse(JSON.stringify(t));return e.maskResponse.call(this,s)}return t}extractSpanContext(t,e){const s=LambdaEventUtils.getLambdaEventType(t,e);return s===LambdaEventType.Lambda?this.tracer.extract(void 0,e.clientContext.custom):s===LambdaEventType.APIGatewayProxy?this.tracer.extract(void 0,t.headers):s===LambdaEventType.SNS?LambdaEventUtils.extractSpanContextFromSNSEvent(this.tracer,t):s===LambdaEventType.SQS?LambdaEventUtils.extractSpanContextFromSQSEvent(this.tracer,t):void 0}injectTriggerTags(t,e,s){try{const a=LambdaEventUtils.getLambdaEventType(e,s);if(a===LambdaEventType.Kinesis)return LambdaEventUtils.injectTriggerTagsForKinesis(t,e);if(a===LambdaEventType.FireHose)return LambdaEventUtils.injectTriggerTagsForFirehose(t,e);if(a===LambdaEventType.DynamoDB)return LambdaEventUtils.injectTriggerTagsForDynamoDB(t,e);if(a===LambdaEventType.SNS)return LambdaEventUtils.injectTriggerTagsForSNS(t,e);if(a===LambdaEventType.SQS)return LambdaEventUtils.injectTriggerTagsForSQS(t,e);if(a===LambdaEventType.S3)return LambdaEventUtils.injectTriggerTagsForS3(t,e);if(a===LambdaEventType.CloudWatchSchedule)return LambdaEventUtils.injectTriggerTagsForCloudWatchSchedule(t,e);if(a===LambdaEventType.CloudWatchLog)return LambdaEventUtils.injectTriggerTagsForCloudWatchLogs(t,e);if(a===LambdaEventType.CloudFront)return LambdaEventUtils.injectTriggerTagsForCloudFront(t,e);if(a===LambdaEventType.APIGatewayProxy)return LambdaEventUtils.injectTriggerTagsForAPIGatewayProxy(t,e);if(a===LambdaEventType.Lambda)return LambdaEventUtils.injectTriggerTagsForLambda(t,s);if(a===LambdaEventType.APIGatewayPassThrough)return LambdaEventUtils.injectTriggerTagsForAPIGatewayPassThrough(t,e)}catch(t){ThundraLogger.getInstance().error("Cannot inject trigger tags. "+t)}}}function instantiateTracePlugin(t){return new Trace(t)}class ThreadMetric extends MetricData{constructor(){super(),this.metricName="ThreadMetric"}}class MemoryMetric extends MetricData{constructor(){super(),this.metricName="MemoryMetric"}}class IOMetric extends MetricData{constructor(){super(),this.metricName="IOMetric"}}class CPUMetric extends MetricData{constructor(){super(),this.metricName="CPUMetric"}}class Metric{constructor(t){this.pluginOrder=2,this.sampled=!0,this.beforeInvocation=t=>__awaiter(this,void 0,void 0,function*(){this.reports=[];const e=this.config&&this.config.sampler&&"function"==typeof this.config.sampler.isSampled;if(this.sampled=!e||this.config.sampler.isSampled(),this.sampled){const{originalContext:e}=t,[s,a]=yield Promise.all([Utils.readProcMetricPromise(),Utils.readProcIoPromise()]);this.initialProcMetric=s,this.initialProcIo=a,this.reporter=t.reporter,this.metricData=Utils.initMonitoringData(this.pluginContext,MonitoringDataType$1.METRIC),this.metricData.metricTimestamp=Date.now(),this.metricData.tags["aws.region"]=this.pluginContext.applicationRegion;const r=this.tracer?this.tracer.getActiveSpan():void 0;this.metricData.transactionId=this.pluginContext.transactionId?this.pluginContext.transactionId:e.awsRequestId,this.metricData.spanId=r?r.spanContext.spanId:"",this.metricData.traceId=r?r.spanContext.traceId:"",this.startCpuUsage=Utils.getCpuUsage()}}),this.afterInvocation=()=>__awaiter(this,void 0,void 0,function*(){this.sampled&&(yield Promise.all([this.addThreadMetricReport(),this.addMemoryMetricReport(),this.addCpuMetricReport(),this.addIoMetricReport()]).catch(t=>{ThundraLogger.getInstance().error("Cannot obtain metric data :"+t)}),this.reports.forEach(t=>{this.report(t)}))}),this.addThreadMetricReport=()=>__awaiter(this,void 0,void 0,function*(){const{threadCount:t}=this.initialProcMetric,e=new ThreadMetric;e.initWithMetricMonitoringDataValues(this.metricData),e.id=Utils.generateId(),e.metricTimestamp=Date.now(),e.metrics={"app.threadCount":t};const s=Utils.generateReport(e,this.apiKey);this.reports=[...this.reports,s]}),this.addMemoryMetricReport=()=>__awaiter(this,void 0,void 0,function*(){const{rss:t,heapUsed:e,external:s}=process.memoryUsage(),a=os.totalmem(),r=os.freemem(),i=new MemoryMetric;i.initWithMetricMonitoringDataValues(this.metricData),i.id=Utils.generateId(),i.metricTimestamp=Date.now(),i.metrics={"app.maxMemory":1024*this.pluginContext.maxMemory*1024,"app.usedMemory":e,"app.rss":t,"sys.maxMemory":a,"sys.usedMemory":a-r,"sys.external":s,"sys.freeMemory":r};const n=Utils.generateReport(i,this.apiKey);this.reports=[...this.reports,n]}),this.addCpuMetricReport=()=>__awaiter(this,void 0,void 0,function*(){const t=Utils.getCpuUsage(),e=Utils.getCpuLoad(this.startCpuUsage,t,this.clockTick),s=new CPUMetric;s.initWithMetricMonitoringDataValues(this.metricData),s.id=Utils.generateId(),s.metricTimestamp=Date.now(),s.metrics={"app.cpuLoad":e.procCpuLoad,"sys.cpuLoad":e.sysCpuLoad};const a=Utils.generateReport(s,this.apiKey);this.reports=[...this.reports,a]}),this.addIoMetricReport=()=>__awaiter(this,void 0,void 0,function*(){const t=this.initialProcIo,e=yield Utils.readProcIoPromise(),s=new IOMetric;s.initWithMetricMonitoringDataValues(this.metricData),s.id=Utils.generateId(),s.metricTimestamp=Date.now(),s.metrics={"sys.diskReadBytes":e.readBytes-t.readBytes,"sys.diskWriteBytes":e.writeBytes-t.writeBytes};const a=Utils.generateReport(s,this.apiKey);this.reports=[...this.reports,a]}),this.hooks={"before-invocation":this.beforeInvocation,"after-invocation":this.afterInvocation},this.config=t,this.reports=[],this.clockTick=parseInt(child_process.execSync("getconf CLK_TCK").toString(),0),t&&(this.tracer=t.tracer)}report(t){this.reporter.addReport(t)}setPluginContext(t){this.pluginContext=t,this.apiKey=t.apiKey}}function instantiateMetricPlugin(t){return new Metric(t)}let AWSXRay,Subsegment;(AWSXRay=Utils.tryRequire("aws-xray-sdk-core"))&&(Subsegment=AWSXRay.Subsegment);class AwsXRayThundraSpanListener{constructor(t){this.xrayPlugin=t,this.subsegmentMap=new Map}onSpanStarted(t){try{if(!AWSXRay)return void ThundraLogger.getInstance().error("XRay plugin is enabled but cannot load module aws-xray-sdk-core.");const e=this.normalizeOperationName(t.getOperationName());t.setTag(AwsXrayConstants.XRAY_SUBSEGMENTED_TAG_NAME,!0);const s=AWSXRay.getSegment(),a=new Subsegment(e);this.subsegmentMap.set(t.spanContext.spanId,a),s.addSubsegment(a)}catch(t){ThundraLogger.getInstance().error("Error occurred while beginning XRay sub-segment for span "+t)}return!1}onSpanInitialized(t){return!1}onSpanFinished(t){try{if(!AWSXRay)return void ThundraLogger.getInstance().error("XRay plugin is enabled but cannot load module aws-xray-sdk-core.");if(t.getTag(AwsXrayConstants.XRAY_SUBSEGMENTED_TAG_NAME)){const e=this.subsegmentMap.get(t.spanContext.spanId);e&&(this.addToAnnotations(t,e),this.addToErrors(t,e),this.addToMetadatas(t,e),e.close(),this.subsegmentMap.delete(t.spanContext.spanId))}}catch(t){ThundraLogger.getInstance().error("Error occurred while ending XRay sub-segment for span "+t)}return!1}failOnError(){return!1}onDestroy(){this.subsegmentMap.clear()}normalizeAnnotationName(t){return t=(t=(t=t.replace(/\./g,"_")).replace(/[\W]+/g,"")).substring(0,500)}normalizeOperationName(t){return t?t.substring(0,200):AwsXrayConstants.DEFAULT_OPERATION_NAME}normalizeAnnotationValue(t){return"string"==typeof t&&(t=t.substring(0,1e3)),t}addToAnnotations(t,e){this.putAnnotationIfAvailable(e,"traceId",this.xrayPlugin.pluginContext.traceId),this.putAnnotationIfAvailable(e,"transactionId",this.xrayPlugin.pluginContext.transactionId),this.putAnnotationIfAvailable(e,"parentSpanId",t.spanContext.parentId),this.putAnnotationIfAvailable(e,"spanId",t.spanContext.spanId),this.putAnnotationIfAvailable(e,"domainName",t.domainName),this.putAnnotationIfAvailable(e,"className",t.className),this.putAnnotationIfAvailable(e,"operationName",t.getOperationName()),this.putAnnotationIfAvailable(e,"startTimestamp",t.startTime),this.putAnnotationIfAvailable(e,"finishTimestamp",t.finishTime),this.putAnnotationIfAvailable(e,"duration",t.getDuration());for(const s of Object.keys(t.tags))s!==AwsXrayConstants.XRAY_SUBSEGMENTED_TAG_NAME&&this.putAnnotationIfAvailable(e,"tags_"+s,t.tags[s])}putAnnotationIfAvailable(t,e,s){"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s||t.addAnnotation(this.normalizeAnnotationName(e),this.normalizeAnnotationValue(s))}addToErrors(t,e){t.getTag("error")&&e.addError(new Error(t.getTag("error.message")))}addToMetadatas(t,e){Object.keys(t.tags).forEach(s=>{e.addMetadata(s,t.tags[s])})}}class AwsXRay{constructor(t){let e;this.pluginOrder=4,this.setPluginContext=t=>{this.pluginContext=t},this.beforeInvocation=t=>{},this.afterInvocation=t=>{},this.hooks={"before-invocation":this.beforeInvocation,"after-invocation":this.afterInvocation},this.config=t,t&&(e=t.tracer),e?e.addSpanListener(new AwsXRayThundraSpanListener(this)):ThundraLogger.getInstance().error("Trace plugin is not enabled, AwsXRay plugin requires Thundra Trace Plugin.")}}function instantiateAwsXRayPlugin(t){return new AwsXRay(t)}class Invocation{constructor(t){this.pluginOrder=2,this.setPluginContext=t=>{this.pluginContext=t,this.apiKey=t.apiKey},this.beforeInvocation=t=>{const{originalContext:e,reporter:s}=t;this.reporter=s,this.finishTimestamp=null,this.startTimestamp=this.pluginContext.invocationStartTimestamp,InvocationSupport.clearError(),this.invocationData=Utils.initMonitoringData(this.pluginContext,MonitoringDataType$1.INVOCATION),this.invocationData.applicationPlatform=LAMBDA_FUNCTION_PLATFORM,this.invocationData.functionRegion=this.pluginContext.applicationRegion,this.invocationData.tags={},this.invocationData.userTags={},this.invocationData.startTimestamp=this.startTimestamp,this.invocationData.finishTimestamp=0,this.invocationData.duration=0,this.invocationData.erroneous=!1,this.invocationData.errorType="",this.invocationData.errorMessage="",this.invocationData.coldStart=0===this.pluginContext.requestCount,this.invocationData.timeout=!1,this.invocationData.transactionId=this.pluginContext.transactionId?this.pluginContext.transactionId:e.awsRequestId,this.invocationData.spanId=this.pluginContext.spanId,this.invocationData.traceId=this.pluginContext.traceId;const a=Utils.getXRayTraceInfo();a.traceID&&(this.invocationData.tags["aws.xray.trace.id"]=a.traceID),a.segmentID&&(this.invocationData.tags["aws.xray.segment.id"]=a.segmentID),this.invocationData.tags["aws.lambda.memory_limit"]=this.pluginContext.maxMemory,this.invocationData.tags["aws.lambda.arn"]=e.invokedFunctionArn,this.invocationData.tags["aws.account_no"]=Utils.getAWSAccountNo(e.invokedFunctionArn),this.invocationData.tags["aws.lambda.invocation.coldstart"]=0===this.pluginContext.requestCount,this.invocationData.tags["aws.region"]=this.pluginContext.applicationRegion,this.invocationData.tags["aws.lambda.log_group_name"]=e?e.logGroupName:"",this.invocationData.tags["aws.lambda.invocation.timeout"]=!1,this.invocationData.tags["aws.lambda.name"]=e?e.functionName:"",this.invocationData.tags["aws.lambda.log_stream_name"]=e.logStreamName,this.invocationData.tags["aws.lambda.invocation.request_id"]=e.awsRequestId;const{heapUsed:r}=process.memoryUsage();this.invocationData.tags["aws.lambda.invocation.memory_usage"]=Math.floor(r/1048576)},this.afterInvocation=t=>{if(InvocationSupport.hasError()&&this.invocationData.setError(InvocationSupport.error),t.error){const e=Utils.parseError(t.error);this.invocationData.setError(e),t.error instanceof TimeoutError&&(this.invocationData.timeout=!0,this.invocationData.tags["aws.lambda.invocation.timeout"]=!0),this.invocationData.tags.error=!0,this.invocationData.tags["error.message"]=e.errorMessage,this.invocationData.tags["error.kind"]=e.errorType,this.invocationData.tags["error.stack"]=e.stack,e.code&&(this.invocationData.tags["error.code"]=e.code),e.stack&&(this.invocationData.tags["error.stack"]=e.stack)}this.invocationData.setTags(InvocationSupport.tags),this.invocationData.setUserTags(InvocationSupport.userTags),this.finishTimestamp=this.pluginContext.invocationFinishTimestamp,this.invocationData.finishTimestamp=this.finishTimestamp,this.invocationData.duration=this.finishTimestamp-this.startTimestamp,this.invocationData.resources=InvocationTraceSupport.getResources(this.pluginContext.spanId),this.invocationData.incomingTraceLinks=InvocationTraceSupport.getIncomingTraceLinks(),this.invocationData.outgoingTraceLinks=InvocationTraceSupport.getOutgoingTraceLinks();const e=Utils.generateReport(this.invocationData,this.apiKey);this.report(e),this.destroy()},this.hooks={"before-invocation":this.beforeInvocation,"after-invocation":this.afterInvocation},this.options=t}report(t){this.reporter.addReport(t)}destroy(){InvocationSupport.removeTags(),InvocationSupport.removeAgentTags(),InvocationTraceSupport.clear()}}function instantiateInvocationPlugin(t){return new Invocation(t)}class PluginContext{constructor(t){t=t||{},this.applicationId=t.applicationId,this.applicationInstanceId=t.applicationInstanceId,this.applicationRegion=t.applicationRegion,this.applicationVersion=t.applicationVersion,this.requestCount=t.requestCount,this.apiKey=t.apiKey,this.timeoutMargin=t.timeoutMargin,this.transactionId=t.transactionId,this.config=t.config}get invocationStartTimestamp(){return this.$invocationStartTimestamp||(this.$invocationStartTimestamp=Date.now()),this.$invocationStartTimestamp}set invocationStartTimestamp(t){this.$invocationStartTimestamp=t}get invocationFinishTimestamp(){return this.$invocationFinishTimestamp||(this.$invocationFinishTimestamp=Date.now()),this.$invocationFinishTimestamp}set invocationFinishTimestamp(t){this.$invocationFinishTimestamp=t}}const get$i=require("lodash.get");class TimeAwareSamplerConfig extends BasePluginConfig{constructor(t){super(get$i(t=t||{},"enabled",!1));const e=get$i(t,"timeFreq",3e5);this.timeFreq=parseInt(e,10)}}class LogManager{constructor(){this.listeners=[]}addListener(t){this.listeners=[...this.listeners,t]}createLogger(t){return new Logger(t)}reportLog(t){this.listeners.forEach(e=>{e.reportLog(t)})}destroy(){this.listeners=[]}}class Logger{constructor(t){this.options=t,this.loggerName=t&&t.loggerName?t.loggerName:"default";const e=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_LOG_LOGLEVEL);this.logLevel=e&&logLevels[e]?logLevels[e]:0,this.levels={trace:this.trace,debug:this.debug,info:this.info,warn:this.warn,error:this.error,fatal:this.fatal}}static getLogManager(){return Logger.logManagerInstance||(Logger.logManagerInstance=new LogManager),Logger.logManagerInstance}reportLog(t,e){const s={logMessage:util.format.apply(util,e),logLevel:t,logLevelCode:logLevels[t],logContextName:this.loggerName,logTimestamp:Date.now()};Logger.getLogManager().reportLog(s)}trace(...t){this.reportLog("TRACE",t)}debug(...t){this.reportLog("DEBUG",t)}info(...t){this.reportLog("INFO",t)}warn(...t){this.reportLog("WARN",t)}error(...t){this.reportLog("ERROR",t)}fatal(...t){this.reportLog("FATAL",t)}log(...t){if(0===t.length)throw new Error("[ThundraLogger] no arguments provided");if("string"==typeof t[0]){if(!(t[0]in this.levels))throw new Error(`[ThundraLogger] level ${t[0]} is not defined, available levels are ${Object.keys(this.levels)}`);if(1===t.length)throw new Error("[ThundraLogger] empty log");this.levels[t[0]](...t.slice(1))}else{if(null===t[0]||"object"!=typeof t[0])throw new Error("[ThundraLogger] invalid usage");if(!(2===Object.keys(t[0]).length&&"level"in t[0]&&"message"in t[0]))throw new Error("[ThundraLogger] invalid usage, please provide both level and message");{const e=t[0].level,s=t[0].message;if(!(e in this.levels))throw new Error(`[ThundraLogger] level ${e} is not defined, available levels are ${Object.keys(this.levels)}`);this.levels[e](s)}}}destroy(){Logger.logManagerInstance.destroy()}}class Log{constructor(t){this.pluginOrder=4,this.consoleReference=console,this.beforeInvocation=t=>{this.logs=[],this.reporter=t.reporter,this.logData=Utils.initMonitoringData(this.pluginContext,MonitoringDataType$1.LOG),this.logData.transactionId=this.pluginContext.transactionId?this.pluginContext.transactionId:t.originalContext.awsRequestId,this.logData.traceId=this.pluginContext.traceId,this.logData.tags={},"true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_LOG_CONSOLE_DISABLE)&&this.shimConsole()},this.afterInvocation=t=>{if(!(this.config&&this.config.sampler&&"function"==typeof this.config.sampler.isSampled)||this.config.sampler.isSampled())for(const t of this.logs){const e=Utils.generateReport(t,this.apiKey);if(InvocationSupport.isErrorenous()){this.report(e);continue}const s=Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_LOG_LOGLEVEL),a=s&&logLevels[s]?logLevels[s]:0;logLevels[t.logLevel]>=a&&this.report(e)}else ThundraLogger.getInstance().debug("Skipping reporting logs due to sampling.");this.destroy()},this.hooks={"before-invocation":this.beforeInvocation,"after-invocation":this.afterInvocation},this.options=t,t&&(this.tracer=t.tracer),this.enabled=!1,Log.instance=this,this.config=t}static getInstance(){return Log.instance}report(t){this.reporter&&this.reporter.addReport(t)}setPluginContext(t){this.pluginContext=t,this.apiKey=t.apiKey}reportLog(t){if(!this.enabled)return;const e=new LogData,s=this.tracer?this.tracer.getActiveSpan():void 0,a=s?s.spanContext.spanId:"";e.initWithLogDataValues(this.logData,a,t),this.logs.push(e)}shimConsole(){ConsoleShimmedMethods.forEach(t=>{if(this.consoleReference[t]){const e=this.consoleReference[t].bind(console),s=Object.getOwnPropertyDescriptor(console,t);s&&Object.defineProperty(console,`original_${t}`,s),this.consoleReference[t]=(...s)=>{const a="LOG"===t.toUpperCase()?"INFO":t.toUpperCase(),r={logMessage:util.format.apply(util,s),logLevel:a,logLevelCode:"log"===t?2:logLevels[t],logContextName:"error"===t?StdErrorLogContext:StdOutLogContext,logTimestamp:Date.now()};this.reportLog(r),e.apply(console,s)}}})}unShimConsole(){ConsoleShimmedMethods.forEach(t=>{const e=Object.getOwnPropertyDescriptor(console,`original_${t}`);e&&Object.defineProperty(console,t,e)})}enable(){this.enabled=!0}disable(){this.enabled=!1}destroy(){"true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_LAMBDA_LOG_CONSOLE_DISABLE)&&this.unShimConsole()}}class DurationAwareSampler{constructor(t,e){this.duration=t,this.longerThan=e}isSampled(t){return!!t&&(this.longerThan?t.getDuration()>this.duration:t.getDuration()<=this.duration)}}class ErrorAwareSampler{isSampled(){return InvocationSupport.isErrorenous()}}const ThundraWarmup=require("@thundra/warmup"),get$j=require("lodash.get");let tracer$1;module.exports=t=>{const e=new ThundraConfig(t),s=[];if(!e.apiKey||e.disableThundra)return t=>t;if("true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE_TRACE)&&e.traceConfig.enabled){const t=instantiateTracePlugin(e.traceConfig);s.push(t),tracer$1=t.tracer,e.metricConfig.tracer=tracer$1,e.logConfig.tracer=tracer$1,e.xrayConfig.tracer=tracer$1,InvocationTraceSupport.tracer=tracer$1}if("true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE_METRIC,"true")&&e.metricConfig.enabled){const t=instantiateMetricPlugin(e.metricConfig);s.push(t)}if("true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE_LOG,"true")&&e.logConfig.enabled){if(!Log.getInstance()){const t=new Log(e.logConfig);Logger.getLogManager().addListener(t)}const t=Log.getInstance();t.enable(),s.push(t)}if("true"!==Utils.getConfiguration(envVariableKeys.THUNDRA_DISABLE_XRAY)&&e.xrayConfig.enabled){const t=instantiateAwsXRayPlugin(e.metricConfig);s.push(t)}const a=instantiateInvocationPlugin(e.invocationConfig);s.push(a),e.trustAllCert&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),ApplicationSupport.parseApplicationTags();const r=Utils.getConfiguration(envVariableKeys.AWS_LAMBDA_LOG_STREAM_NAME),i=Utils.getConfiguration(envVariableKeys.AWS_REGION),n=Utils.getConfiguration(envVariableKeys.AWS_LAMBDA_FUNCTION_VERSION),o=r?r.split("]").pop():Utils.generateId(),p=new PluginContext({applicationInstanceId:o,applicationRegion:i||"",applicationVersion:n||"",requestCount:0,apiKey:e.apiKey,timeoutMargin:e.timeoutMargin,transactionId:null,config:e}),c=()=>p.requestCount+=1;return t=>{if(get$j(t,"thundraWrapped",!1))return t;const a=(e,a,r)=>{const i=Utils.getApplicationId(a,p);p.applicationId=i,s.forEach(t=>{t.setPluginContext(p)});return new ThundraWrapper(void 0,e,a,r,t,s,p).invoke()};if(a.thundraWrapped=!0,e.warmupAware){return ThundraWarmup(c)(a)}return a}},module.exports.tracer=()=>tracer$1,module.exports.createLogger=t=>{if(!Log.getInstance()){const t=new LogConfig({}),e=new Log(t);Logger.getLogManager().addListener(e)}return Logger.getLogManager().createLogger(t)},module.exports.addLogListener=t=>Logger.getLogManager().addListener(t),module.exports.config={ThundraConfig:ThundraConfig,TraceConfig:TraceConfig,MetricConfig:MetricConfig,InvocationConfig:InvocationConfig,LogConfig:LogConfig,TraceableConfig:dist_1,IntegrationConfig:IntegrationConfig,TimeAwareSamplerConfig:TimeAwareSamplerConfig,AwsXRayConfig:AwsXRayConfig},module.exports.samplers={CompositeSampler:CompositeSampler,CountAwareSampler:CountAwareSampler,DurationAwareSampler:DurationAwareSampler,ErrorAwareSampler:ErrorAwareSampler,TimeAwareSampler:TimeAwareSampler,SamplerCompositionOperator:SamplerCompositionOperator},module.exports.InvocationSupport=InvocationSupport,module.exports.InvocationTraceSupport=InvocationTraceSupport,module.exports.updateConfig=ThundraConfig.updateConfig,module.exports.listeners={ErrorInjectorSpanListener:ErrorInjectorSpanListener,FilteringSpanListener:FilteringSpanListener,LatencyInjectorSpanListener:LatencyInjectorSpanListener,TagInjectorSpanListener:TagInjectorSpanListener,StandardSpanFilter:StandardSpanFilter,CompositeSpanFilter:CompositeSpanFilter,StandardSpanFilterer:StandardSpanFilterer};