hud-sdk 1.8.6 → 1.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,n){if("object"==typeof exports&&"object"==typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t=n();for(var i in t)("object"==typeof exports?exports:e)[i]=t[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_MODULE_NAME=void 0,n.SDK_MODULE_NAME="hud-sdk"},2509:function(e,n,t){var i=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var o=Object.getOwnPropertyDescriptor(n,t);o&&!("get"in o?!n.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,o)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),o=this&&this.__exportStar||function(e,n){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(n,t)||i(n,e,t)};Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=n.SDK_MODULE_NAME=void 0,o(t(2887),n),o(t(2570),n);var a=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return a.SDK_MODULE_NAME}}),o(t(7089),n);var r=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.refreshInvestigationEnabled=function(e,n,t){if(null==e)return;const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return;const a=o.data?.enableInvestigation;if(void 0===a)return;a!==globalThis.hudEnableInvestigation&&(n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=a,t.info("Periodic refresh - Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:a})))},n.updateDynamicConfig=function(e,n,t){const a=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!a.success)return t.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:a,remoteConfig:e}),n.dynamicConfig;const r=o(n.dynamicConfig,a.data);return void 0!==r.enableInvestigation&&r.enableInvestigation!==n.dynamicConfig.enableInvestigation&&(t.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:r.enableInvestigation}),n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=r.enableInvestigation)),void 0!==r.enableInvestigationArgsSending&&r.enableInvestigationArgsSending!==n.dynamicConfig.enableInvestigationArgsSending&&(t.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:r.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=r.enableInvestigationArgsSending),void 0!==r?.investigationRateLimits?.executionFlowMaxLength&&r?.investigationRateLimits?.executionFlowMaxLength!==n.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=r.investigationRateLimits.executionFlowMaxLength),void 0!==r?.investigationRateLimits?.exceptionMaxLength&&r?.investigationRateLimits?.exceptionMaxLength!==n.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=r.investigationRateLimits.exceptionMaxLength),r};const i=t(2887);function o(e,n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(e)&&Array.isArray(n))return n;const t={...e};for(const i in n){const a=e[i],r=n[i];t[i]=o(a,r)}return t}},2887:function(e,n,t){var i,o=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var o=Object.getOwnPropertyDescriptor(n,t);o&&!("get"in o?!n.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,o)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),a=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var n=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[n.length]=t);return n},i(e)},function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t=i(e),r=0;r<t.length;r++)"default"!==t[r]&&o(n,e,t[r]);return a(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.loggerConfig=n.hudConfig=n.HudDynamicConfigSchema=void 0,n.functionUuidToBase64=d,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{n=new Map}return n},n.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},n.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)};const s=t(8528),l=r(t(6928)),u=t(3903),c=t(1569);function d(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";n.HudDynamicConfigSchema=c.z.object({aggregationInterval:c.z.number(),aggregationFirstSendTimeout:c.z.number(),investigationInterval:c.z.number(),investigationFirstSendTimeout:c.z.number(),enableInvestigation:c.z.boolean(),enableInvestigationArgsSending:c.z.boolean(),investigationRateLimits:c.z.object({maxSameInvestigations:c.z.number().int().positive(),sameInvestigationTimeWindowMs:c.z.number().int().positive(),maxTotalInvestigations:c.z.number().int().positive(),maxTotalInvestigationsErrorBased:c.z.number().int().positive(),maxTotalInvestigationsDurationBased:c.z.number().int().positive(),totalInvestigationTimeWindowMs:c.z.number().int().positive(),maxUniqLogs:c.z.number().int().positive(),maxStringLength:c.z.number().int().positive(),maxArrayLength:c.z.number().int().positive(),maxObjectDepth:c.z.number().int().positive(),maxKeyLength:c.z.number().int().positive(),executionFlowMaxLength:c.z.number().int().positive(),exceptionMaxLength:c.z.number().int().positive(),maxUniqueSetFailureErrors:c.z.number().int().positive()}),machineMetricsInterval:c.z.number().int().positive(),blacklistParams:c.z.array(c.z.string()),forensicsBlacklistFields:c.z.array(c.z.string()),forensicsWhitelistFields:c.z.array(c.z.string()),censorshipRegexes:c.z.array(c.z.object({regex:c.z.string(),replacement:c.z.string()})),reingestInterval:c.z.number().int().positive(),extraHeaders:c.z.array(c.z.string()),performanceMetricsInterval:c.z.number().int().positive(),enableOutboundData:c.z.boolean(),maxTotalOutbounds:c.z.number().int().positive(),maxOutboundCountWithData:c.z.number().int().positive(),maxHTTPRequestBodySize:c.z.number().int().positive(),maxHTTPResponseBodySize:c.z.number().int().positive(),functionDetachEnabled:c.z.boolean(),functionDetachThresholdPerSecond:c.z.number().int().positive(),enableMongoDocumentData:c.z.boolean()});const g=process.env.HUD_ENABLE_INVESTIGATION,v="_HUD",p="94a210f3-861c-4e18-ab27-6b6c19437c9d",b={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration",getKnownDetachedFunctions:"sink/known-detached-functions/get",setDetachedFunctions:"sink/known-detached-functions/set"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{lean:{value:!1,source:"DEFAULT"},minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},disableDetachedFunctions:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,remoteConfigRefreshInterval:3e5,workerStateCollectionDelay:6e5,workerGrace:6e4,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:p,wrapVarPrefix:v,functionInitFunctionName:`${v}i`,functionCatchFunctionName:`${v}c`,functionFinallyFunctionName:`${v}n`,callContextVarName:`${v}x`,fixStackFunctionName:`${v}s`,asyncIteratorWrapperFunctionName:`${v}w`,wrapperUserCatchFunctionName:`${v}u`,asyncWrapperFunctionName:`${v}a`,internalAsyncWrapperFunctionName:`${v}b`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/compiled/next-server/pages-api-turbo.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=16.0.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:">=7.5.0",patcher:"sqsConsumer"}],[["@mondaydotcomorg/monday-sqs-consumer","sqs-consumer"].join(l.sep),{framework:s.availableFrameworks.sqs,enable:"win32"!==process.platform,version:">=5.2.2 <6",patcher:"sqsConsumer",extraInfo:{isMondayVersion:!0,srcHash:"bd9064befbf3abb9ad0e6a53b0cf721d5612d5b8d8790875c994b7ff40b951c5"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["@clickhouse/client-common",{framework:s.availableFrameworks.clickhouse,enable:!1,version:"^1.10.0",patcher:"outbound/clickhouse",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["mongodb",{framework:s.availableFrameworks.mongodb,enable:!0,version:">=5.0.0 <8.0.0",patcher:"outbound/mongodb",extraInfo:{isOutbound:!0}}],["mongoose",{framework:s.availableFrameworks.mongoose,enable:!0,version:">=5.0.0 <7.0.0",patcher:"outbound/mongoose",extraInfo:{isOutbound:!0}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,enableInvestigationArgsSending:!1,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30,maxUniqueSetFailureErrors:100},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20,functionDetachEnabled:!1,functionDetachThresholdPerSecond:5833,enableMongoDocumentData:!1},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:d((0,u.v5)("axios",p)),nodeFetchFunctionId:d((0,u.v5)("node-fetch",p)),nodeFetchBodiesFunctionIds:{json:d((0,u.v5)("node-fetch-body-json",p)),text:d((0,u.v5)("node-fetch-body-text",p)),arrayBuffer:d((0,u.v5)("node-fetch-body-arrayBuffer",p)),blob:d((0,u.v5)("node-fetch-body-blob",p))},requestFunctionId:d((0,u.v5)("request-request",p)),requestMethodFunctionIds:{get:d((0,u.v5)("request-get",p)),head:d((0,u.v5)("request-head",p)),options:d((0,u.v5)("request-options",p)),post:d((0,u.v5)("request-post",p)),put:d((0,u.v5)("request-put",p)),patch:d((0,u.v5)("request-patch",p)),del:d((0,u.v5)("request-del",p)),delete:d((0,u.v5)("request-delete",p))},pgConnectFunctionId:d((0,u.v5)("pg-connect",p)),pgQueryFunctionId:d((0,u.v5)("pg-query",p)),pgEndFunctionId:d((0,u.v5)("pg-end",p)),clickhouseQueryFunctionId:d((0,u.v5)("clickhouse-query",p)),clickhouseExecFunctionId:d((0,u.v5)("clickhouse-exec",p)),clickhouseCommandFunctionId:d((0,u.v5)("clickhouse-command",p)),clickhouseInsertFunctionId:d((0,u.v5)("clickhouse-insert",p)),clickhouseCloseFunctionId:d((0,u.v5)("clickhouse-close",p)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};n.hudConfig=function(e={}){return{...b,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),n.default=n.hudConfig;const f=process.env.HUD_DEBUG?n.hudConfig.logger.debug:n.hudConfig.logger.default;n.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.8.6"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),o=i.z.object({type:i.z.literal("s3")}),a=i.z.object({type:i.z.literal("disk"),path:i.z.string()}),r=i.z.object({type:i.z.literal("customer_s3"),bucket:i.z.string(),region:i.z.string(),prefix:i.z.string().optional()});n.ObjectStoreConfigSchema=i.z.union([o,a,r])},8528:e=>{e.exports=require("./dto")}},n={};return function t(i){var o=n[i];if(void 0!==o)return o.exports;var a=n[i]={exports:{}};return e[i].call(a.exports,a,a.exports,t),a.exports}(2509)})());
1
+ !function(e,n){if("object"==typeof exports&&"object"==typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t=n();for(var i in t)("object"==typeof exports?exports:e)[i]=t[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_MODULE_NAME=void 0,n.SDK_MODULE_NAME="hud-sdk"},2509:function(e,n,t){var i=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),a=this&&this.__exportStar||function(e,n){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(n,t)||i(n,e,t)};Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=n.SDK_MODULE_NAME=void 0,a(t(2887),n),a(t(2570),n);var o=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return o.SDK_MODULE_NAME}}),a(t(7089),n);var r=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.refreshInvestigationEnabled=function(e,n,t){if(null==e)return;const a=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!a.success)return;const o=a.data?.enableInvestigation;if(void 0===o)return;o!==globalThis.hudEnableInvestigation&&(n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o,t.info("Periodic refresh - Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o})))},n.updateDynamicConfig=function(e,n,t){const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return t.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:o,remoteConfig:e}),n.dynamicConfig;const r=a(n.dynamicConfig,o.data);return void 0!==r.enableInvestigation&&r.enableInvestigation!==n.dynamicConfig.enableInvestigation&&(t.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:r.enableInvestigation}),n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=r.enableInvestigation)),void 0!==r.enableInvestigationArgsSending&&r.enableInvestigationArgsSending!==n.dynamicConfig.enableInvestigationArgsSending&&(t.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:r.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=r.enableInvestigationArgsSending),void 0!==r?.investigationRateLimits?.executionFlowMaxLength&&r?.investigationRateLimits?.executionFlowMaxLength!==n.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=r.investigationRateLimits.executionFlowMaxLength),void 0!==r?.investigationRateLimits?.exceptionMaxLength&&r?.investigationRateLimits?.exceptionMaxLength!==n.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=r.investigationRateLimits.exceptionMaxLength),r};const i=t(2887);function a(e,n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(e)&&Array.isArray(n))return n;const t={...e};for(const i in n){const o=e[i],r=n[i];t[i]=a(o,r)}return t}},2887:function(e,n,t){var i,a=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var n=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[n.length]=t);return n},i(e)},function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t=i(e),r=0;r<t.length;r++)"default"!==t[r]&&a(n,e,t[r]);return o(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.loggerConfig=n.hudConfig=n.HudDynamicConfigSchema=void 0,n.functionUuidToBase64=d,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{n=new Map}return n},n.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},n.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)};const s=t(8528),l=r(t(6928)),u=t(3903),c=t(1569);function d(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";n.HudDynamicConfigSchema=c.z.object({aggregationInterval:c.z.number(),aggregationFirstSendTimeout:c.z.number(),investigationInterval:c.z.number(),investigationFirstSendTimeout:c.z.number(),enableInvestigation:c.z.boolean(),enableInvestigationArgsSending:c.z.boolean(),investigationRateLimits:c.z.object({maxSameInvestigations:c.z.number().int().positive(),sameInvestigationTimeWindowMs:c.z.number().int().positive(),maxTotalInvestigations:c.z.number().int().positive(),maxTotalInvestigationsErrorBased:c.z.number().int().positive(),maxTotalInvestigationsDurationBased:c.z.number().int().positive(),totalInvestigationTimeWindowMs:c.z.number().int().positive(),maxUniqLogs:c.z.number().int().positive(),maxStringLength:c.z.number().int().positive(),maxArrayLength:c.z.number().int().positive(),maxObjectDepth:c.z.number().int().positive(),maxKeyLength:c.z.number().int().positive(),executionFlowMaxLength:c.z.number().int().positive(),exceptionMaxLength:c.z.number().int().positive(),maxUniqueSetFailureErrors:c.z.number().int().positive()}),machineMetricsInterval:c.z.number().int().positive(),blacklistParams:c.z.array(c.z.string()),forensicsBlacklistFields:c.z.array(c.z.string()),forensicsWhitelistFields:c.z.array(c.z.string()),censorshipRegexes:c.z.array(c.z.object({regex:c.z.string(),replacement:c.z.string()})),reingestInterval:c.z.number().int().positive(),extraHeaders:c.z.array(c.z.string()),performanceMetricsInterval:c.z.number().int().positive(),enableOutboundData:c.z.boolean(),maxTotalOutbounds:c.z.number().int().positive(),maxOutboundCountWithData:c.z.number().int().positive(),maxHTTPRequestBodySize:c.z.number().int().positive(),maxHTTPResponseBodySize:c.z.number().int().positive(),functionDetachEnabled:c.z.boolean(),functionDetachThresholdPerSecond:c.z.number().int().positive(),enableMongoDocumentData:c.z.boolean(),enableTeardown:c.z.boolean()});const g=process.env.HUD_ENABLE_INVESTIGATION,v="_HUD",b="94a210f3-861c-4e18-ab27-6b6c19437c9d",p={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration",getKnownDetachedFunctions:"sink/known-detached-functions/get",setDetachedFunctions:"sink/known-detached-functions/set"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{lean:{value:!1,source:"DEFAULT"},minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},disableDetachedFunctions:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,remoteConfigRefreshInterval:3e5,workerStateCollectionDelay:1e4,workerGrace:6e4,teardownGrace:5e3,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:b,wrapVarPrefix:v,functionInitFunctionName:`${v}i`,functionCatchFunctionName:`${v}c`,functionFinallyFunctionName:`${v}n`,callContextVarName:`${v}x`,fixStackFunctionName:`${v}s`,asyncIteratorWrapperFunctionName:`${v}w`,wrapperUserCatchFunctionName:`${v}u`,asyncWrapperFunctionName:`${v}a`,internalAsyncWrapperFunctionName:`${v}b`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0 || ^3.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/compiled/next-server/pages-api-turbo.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=16.0.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:">=7.5.0",patcher:"sqsConsumer"}],[["@mondaydotcomorg/monday-sqs-consumer","sqs-consumer"].join(l.sep),{framework:s.availableFrameworks.sqs,enable:"win32"!==process.platform,version:">=5.2.2 <6",patcher:"sqsConsumer",extraInfo:{isMondayVersion:!0,srcHash:"bd9064befbf3abb9ad0e6a53b0cf721d5612d5b8d8790875c994b7ff40b951c5"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["@clickhouse/client-common",{framework:s.availableFrameworks.clickhouse,enable:!1,version:"^1.10.0",patcher:"outbound/clickhouse",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["mongodb",{framework:s.availableFrameworks.mongodb,enable:!0,version:">=5.0.0 <8.0.0",patcher:"outbound/mongodb",extraInfo:{isOutbound:!0}}],["mongoose",{framework:s.availableFrameworks.mongoose,enable:!0,version:">=5.0.0 <7.0.0",patcher:"outbound/mongoose",extraInfo:{isOutbound:!0}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,enableInvestigationArgsSending:!1,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30,maxUniqueSetFailureErrors:100},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20,functionDetachEnabled:!1,functionDetachThresholdPerSecond:5833,enableMongoDocumentData:!1,enableTeardown:!1},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:d((0,u.v5)("axios",b)),nodeFetchFunctionId:d((0,u.v5)("node-fetch",b)),nodeFetchBodiesFunctionIds:{json:d((0,u.v5)("node-fetch-body-json",b)),text:d((0,u.v5)("node-fetch-body-text",b)),arrayBuffer:d((0,u.v5)("node-fetch-body-arrayBuffer",b)),blob:d((0,u.v5)("node-fetch-body-blob",b))},requestFunctionId:d((0,u.v5)("request-request",b)),requestMethodFunctionIds:{get:d((0,u.v5)("request-get",b)),head:d((0,u.v5)("request-head",b)),options:d((0,u.v5)("request-options",b)),post:d((0,u.v5)("request-post",b)),put:d((0,u.v5)("request-put",b)),patch:d((0,u.v5)("request-patch",b)),del:d((0,u.v5)("request-del",b)),delete:d((0,u.v5)("request-delete",b))},pgConnectFunctionId:d((0,u.v5)("pg-connect",b)),pgQueryFunctionId:d((0,u.v5)("pg-query",b)),pgEndFunctionId:d((0,u.v5)("pg-end",b)),clickhouseQueryFunctionId:d((0,u.v5)("clickhouse-query",b)),clickhouseExecFunctionId:d((0,u.v5)("clickhouse-exec",b)),clickhouseCommandFunctionId:d((0,u.v5)("clickhouse-command",b)),clickhouseInsertFunctionId:d((0,u.v5)("clickhouse-insert",b)),clickhouseCloseFunctionId:d((0,u.v5)("clickhouse-close",b)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};n.hudConfig=function(e={}){return{...p,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),n.default=n.hudConfig;const f=process.env.HUD_DEBUG?n.hudConfig.logger.debug:n.hudConfig.logger.default;n.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.8.8"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),a=i.z.object({type:i.z.literal("s3")}),o=i.z.object({type:i.z.literal("disk"),path:i.z.string()}),r=i.z.object({type:i.z.literal("customer_s3"),bucket:i.z.string(),region:i.z.string(),prefix:i.z.string().optional()});n.ObjectStoreConfigSchema=i.z.union([a,o,r])},8528:e=>{e.exports=require("./dto")}},n={};return function t(i){var a=n[i];if(void 0!==a)return a.exports;var o=n[i]={exports:{}};return e[i].call(o.exports,o,o.exports,t),o.exports}(2509)})());
2
2
  //# sourceMappingURL=config.js.map
package/dist/cjs/core.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1427:e=>{e.exports=require("./nativerequire")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&r(t,e,n[o]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=o(n(523)),c=n(8528),d=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==c.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&r(t,e,n[o]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=o(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const r=n(8167),s=n(2546),o=n(5809),a=n(8269),c=n(523),d=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&c.customer_logger.logEntry(s.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof s.HudSessionThrottle?(c.customer_logger.logEntry(s.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof s.HudInitNetworkError&&e.originalAxiosErrorCode?(c.customer_logger.logEntry((0,s.getNetworkError)(e.originalAxiosErrorCode)),c.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(c.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,s.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,s.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),c.customer_logger.logEntry(s.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(r.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();c.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,s.next)(e).then(async()=>{c.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{c.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new s.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(o.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),o.hudConfig.dynamicConfig.functionDetachEnabled&&!o.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,d.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,o.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof s.HudSessionThrottle)throw e;throw c.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=s.myRequire.resolve(`${o.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new r.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:o.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(o.hudConfig.workerTimeout)}catch(e){if(e instanceof s.HudSessionThrottle)throw c.app_logger.info("Worker started in idle mode - session throttled"),e;throw c.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(c.app_logger.info("Remote configuration exists"),o.hudConfig.dynamicConfig=(0,o.updateDynamicConfig)(e,o.hudConfig,c.app_logger),(0,o.updateInvestigationRateLimitGlobals)(),c.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:o.hudConfig.dynamicConfig})):c.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:o.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void r.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,c.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,c.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void r.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(r.app_logger.info("Initializing hud",{userConfig:Object.entries(o.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new s.MainThread(g.apiKey,g.service,globalThis.hudStartTime,o.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,d.safeCall)(r.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;r.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof d.HudSessionThrottle)return;r.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{r.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,c.getShouldFlushOnInit)()&&((0,c.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),r=n(523),s=n(5994),o=n(5809),a=n(8528),c=n(8269),d=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,c.detachHud)(e,t),n&&(0,d.safeCall)(r.app_logger,f()),l&&(0,d.safeCall)(r.app_logger,l.terminateMessenger());const s=(0,c.getLambdaExtensionId)();s&&!u&&(u=!0,(0,d.safeCall)(r.app_logger,(0,i.nextLoopDummy)(s))),(0,c.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,c.getSessionInfo)(),s=(0,c.getStoredApiKey)(),o=(0,c.getStoredService)();try{const a=e||s;if(!a||"string"!=typeof a)return;const c=t||o||"unknown",d=(0,r.getSavedLogs)();for(const e of d){const{HudClient:t}=n(4672),s=new t;i?(r.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:c}),s.setSession(i),await s.logs(e)):(r.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:c}),await s.sessionslessLogs(e,a)),r.app_logger.info("Successfully flushed logs")}}catch(e){try{r.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=c,t._liftExceptions=g,t.prepCalls=function(e,t){let n=null;if(i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){const e=process.hrtime.bigint();let t;t=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(e-a)/1e6,c(e),n=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(t/1e3)}const d=(new Date).toISOString(),l=[];return Object.entries(hudCalls).map(([r,a])=>{const c=a.shouldDetach;let u=0;var h;Object.entries(a).forEach(([n,o])=>{"shouldDetach"!==n&&Object.entries(o).forEach(([o,a])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||c||(u+=a.count),0===a.sampledCount)return;const s={function_id:r,wrapped_flow_id:o||void 0,wrapped_caller_id:n||void 0,timestamp:d,timeslice:e,exceptions:g(a.exceptions),count:a.count,sampled_count:a.sampledCount,sum_duration:a.sum,sum_squared_duration:a.squareSum,sketch:a.sketch?t.encode(a.sketch):void 0,is_linked_function:a.isLinkedFunction};l.push(s),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(a)}catch(e){s.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:n,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==n&&u>n&&(hudCalls[r].shouldDetach=!0,h=r,o.push(h),s.app_logger.info("Detaching function",{func:r,totalFunctionCalls:u}))}),l.length>0&&(0,r.clearMetricsIndicator)(),l},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])d(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=o;return o=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(s.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){s.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),r=n(8269),s=n(523);let o=[],a=null;function c(e){a=e}function d(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,r=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&r(t,e,n[o]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(523)),c=o(n(6460)),d=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),k=n(8269),C=n(1427),y=n(6281),w=n(8269),b=n(2546),E=n(6261),_=a.app_logger,T=m.safeCall.bind(m.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,_.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&_.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),_.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,y._detachAndTerminate)(!0,!1,!0)}catch(e){_.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),_.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:_.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.periodicRefreshRemoteConfig()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.periodicSendDetachedFunctions()),T(this.periodicFetchKnownDetachedFunctions()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.delayedStateCollection()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:_.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let r;e=Array.isArray(e)?e:[e];const s=this.consumeMessageFromQueue(e);if(s)return _.info("Found message in queue",{msg:s.msg}),s;const o=new AbortController,a=()=>{o.abort()};this.abortController.signal.addEventListener("abort",a);const d=c.setTimeout(t,void 0,{signal:o.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(r=t,o.abort(),this.consumeMessageFromQueue([t.msg]),_.info("Received message from worker (canceling timeout)",t))}catch(e){_.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await d,_.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return r}async getMode(){await(0,u.safeUnrefInterval)(async()=>{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);t?.msg===e.msg&&void 0!==t?.content.mode?t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode):_.error("Unexpected message from worker",t)},d.hudConfig.modeInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed getting mode from worker",{msg:e.message,stack:e.stack})})}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){_.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return _.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)(),await(0,u.safeUnrefInterval)(()=>(0,f.saveMachineMetric)(),d.hudConfig.dynamicConfig.machineMetricsInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed saving machine metrics",{msg:e.message,stack:e.stack})})}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;await(0,u.safeUnrefInterval)(()=>{_.info("Resetting caller",{interval:e}),(0,p.resetCallers)()},e,{signal:this.abortController.signal,onError:e=>_.error("Failed reseting caller counters",{msg:e.message,stack:e.stack})})}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),_.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){_.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds(),await(0,u.safeUnrefInterval)(()=>this.updateEndpointDurationsInvestigationThresholds(),d.hudConfig.endpointsDurationsInvestigationThresholdsInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed updating endpoints durations investigation thresholds",{msg:e.message,stack:e.stack})})}async updateRefreshRemoteConfig(){const e="RefreshRemoteConfig",t={msg:"RefreshRemoteConfig"};try{const n=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!1,t);if(n?.msg!==e||void 0===n?.content)return;(0,d.refreshInvestigationEnabled)(n.content,d.hudConfig,_)}catch(e){_.error("Failed refreshing remote config from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicRefreshRemoteConfig(){await(0,u.safeUnrefInterval)(()=>this.updateRefreshRemoteConfig(),d.hudConfig.remoteConfigRefreshInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed refreshing remote config",{msg:e.message,stack:e.stack})})}async delayedStateCollection(){await this.setupPeriodicTask(0,d.hudConfig.workerStateCollectionDelay,()=>{try{this._updateTsNodeConfig()&&_.info("ts-node config updated from delayed task")}catch(e){_.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollecgtion",!0)}async periodicSendProcessedFiles(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,k.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,k.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,k.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){_.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const n=(0,p.prepCalls)(t,e);n.length>0&&this._sendArray("Invocations",n)}catch(e){_.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){_.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!d.hudConfig.dynamicConfig.functionDetachEnabled||d.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){_.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){_.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){d.hudConfig.dynamicConfig.functionDetachEnabled&&!d.hudConfig.userConfig.disableDetachedFunctions?.value&&await(0,u.safeUnrefInterval)(()=>this.fetchKnownDetachedFunctions(),d.hudConfig.dynamicConfig.aggregationInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed fetching known detached functions",{msg:e.message,stack:e.stack})})}async highFrequencySendInvestigations(){if(!d.hudConfig.dynamicConfig.enableInvestigation)return;const e=d.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=d.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,k.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,k.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,w.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,w.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",d.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:d.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw _.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;_.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}_.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):_.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=d.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();await(0,u.safeUnrefInterval)(()=>{const e=(0,m.collectThreadPerformance)(t,_,"MainThread");e&&this._sendObject("PerformanceMetrics",e)},e,{signal:this.abortController.signal,onError:e=>_.error("Failed sending thread performance metrics",{msg:e.message,stack:e.stack})})}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(C.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void _.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){_.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){await(0,u.safeUnrefInterval)(()=>this.handleLogsTask(),e,{signal:this.abortController.signal,onError:e=>_.error("Failed sending logs periodically",{msg:e.message,stack:e.stack})})}async setupPeriodicTask(e,t,n,i,r=!1){function s(e){let t=!0;try{t=n(e)}catch(e){_.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),s(e)?r||await(0,u.safeUnrefInterval)(e=>{s(t)||(_.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i}),e())},t,{signal:this.abortController.signal,onError:e=>_.error("Failed in periodic task interval",{taskName:i,msg:e.message,stack:e.stack})}):_.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{_.info("Resetting global investigation counter",{interval:e}),(0,k.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()},e,{signal:this.abortController.signal,onError:e=>_.error("Failed resetting global investigation counter",{msg:e.message,stack:e.stack})})}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{_.info("Resetting investigation deduping cache",{interval:e}),(0,k.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)(),(0,f.getUniqueSetFailureErrors)().clear()},e,{signal:this.abortController.signal,onError:e=>_.error("Failed resetting investigation deduping cache",{msg:e.message,stack:e.stack})})}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,_.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=d.hudConfig.staticNextJsEndpointsInterval,t=d.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;await(0,u.safeUnrefInterval)(e=>{if(n++,_.debug("Attempting to send static next.js endpoints",{attemptCount:n}),(0,k.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,k.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const t=(0,k.getNextConfig)();return this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(t)}),void e()}n>t&&(_.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,k.isNextConfigExtracted)(),attemptCount:n}),e())},e,{signal:this.abortController.signal,onError:e=>_.error("Failed sending static next.js endpoints",{msg:e.message,stack:e.stack})})}async periodicSendReingest(){await(0,u.safeUnrefInterval)(()=>{const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))},d.hudConfig.dynamicConfig.reingestInterval,{signal:this.abortController.signal,onError:e=>_.error("Failed sending reingest",{msg:e.message,stack:e.stack})})}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}return n.c=t,n(n.s=5119)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1427:e=>{e.exports=require("./nativerequire")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=o(n(523)),d=n(8528),c=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==d.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){c.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.updateTsNodeConfig=t.tryFlushPendingLogs=t.init=void 0;const a=o(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}}),Object.defineProperty(t,"updateTsNodeConfig",{enumerable:!0,get:function(){return a.updateTsNodeConfig}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const s=n(8167),r=n(2546),o=n(5809),a=n(8269),d=n(523),c=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&d.customer_logger.logEntry(r.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;lifecycleHooksRegistered=!1;teardownInFlight;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof r.HudSessionThrottle?(d.customer_logger.logEntry(r.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof r.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.logEntry((0,r.getNetworkError)(e.originalAxiosErrorCode)),d.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(d.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,r.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,r.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),this.registerLifecycleTeardown(),d.customer_logger.logEntry(r.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(s.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();d.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,r.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{d.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new r.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(o.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),o.hudConfig.dynamicConfig.functionDetachEnabled&&!o.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,c.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,o.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof r.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=r.myRequire.resolve(`${o.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new s.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:o.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(o.hudConfig.workerTimeout)}catch(e){if(e instanceof r.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),o.hudConfig.dynamicConfig=(0,o.updateDynamicConfig)(e,o.hudConfig,d.app_logger),(0,o.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:o.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:o.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}registerLifecycleTeardown(){if(this.lifecycleHooksRegistered)return;if(this.lifecycleHooksRegistered=!0,globalThis.hudRuningInsideLambda)return;if(!o.hudConfig.dynamicConfig.enableTeardown)return;const e=async()=>{try{if(this.teardownInFlight)return void await this.teardownInFlight;this.teardownInFlight=this.gracefulShutdown(),await this.teardownInFlight}catch{}};process.once("beforeExit",()=>{e()}),process.prependOnceListener("SIGTERM",async()=>{const t=process.listenerCount("SIGTERM")>0;try{await e()}catch{}t||process.kill(process.pid,"SIGTERM")}),process.prependOnceListener("SIGINT",async()=>{const t=process.listenerCount("SIGINT")>0;try{await e()}catch{}t||process.kill(process.pid,"SIGINT")})}async gracefulShutdown(){if(this.messenger){try{await this.messenger.gracefulShutdown()}catch{}this.messenger=void 0,(0,a.detachHud)(!1,!1)}}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void s.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void s.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(s.app_logger.info("Initializing hud",{userConfig:Object.entries(o.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new r.MainThread(g.apiKey,g.service,globalThis.hudStartTime,o.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(s.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;s.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;s.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{s.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.updateTsNodeConfig=function(){try{return!!l?.messenger&&l.messenger.updateTsNodeConfig()}catch(e){return s.app_logger.error("Failed to update ts-node config",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),!1}},t.tryFlushPendingLogs=async function(e,t){(0,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),s=n(523),r=n(5994),o=n(5809),a=n(8528),d=n(8269),c=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,d.detachHud)(e,t),n&&(0,c.safeCall)(s.app_logger,f()),l&&(0,c.safeCall)(s.app_logger,l.terminateMessenger());const r=(0,d.getLambdaExtensionId)();r&&!u&&(u=!0,(0,c.safeCall)(s.app_logger,(0,i.nextLoopDummy)(r))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,d.getSessionInfo)(),r=(0,d.getStoredApiKey)(),o=(0,d.getStoredService)();try{const a=e||r;if(!a||"string"!=typeof a)return;const d=t||o||"unknown",c=(0,s.getSavedLogs)();for(const e of c){const{HudClient:t}=n(4672),r=new t;i?(s.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:d}),r.setSession(i),await r.logs(e)):(s.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await r.sessionslessLogs(e,a)),s.app_logger.info("Successfully flushed logs")}}catch(e){try{s.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=d,t.getLastPrepCallsTimestamp=function(){return a},t._liftExceptions=g,t.prepCalls=function(e,t){const n=process.hrtime.bigint();let c;c=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(n-a)/1e6,d(n);let l=null;i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&(l=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(c/1e3));const u=(new Date).toISOString(),h=[];return Object.entries(hudCalls).map(([n,s])=>{const a=s.shouldDetach;let d=0;var c;Object.entries(s).forEach(([s,o])=>{"shouldDetach"!==s&&Object.entries(o).forEach(([o,c])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||a||(d+=c.count),0===c.sampledCount)return;const r={function_id:n,wrapped_flow_id:o||void 0,wrapped_caller_id:s||void 0,timestamp:u,timeslice:e,exceptions:g(c.exceptions),count:c.count,sampled_count:c.sampledCount,sum_duration:c.sum,sum_squared_duration:c.squareSum,sketch:c.sketch?t.encode(c.sketch):void 0,is_linked_function:c.isLinkedFunction};h.push(r),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){r.app_logger.error("Failed preparing invocation, skipping",{func:n,wrappedCaller:s,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==l&&d>l&&(hudCalls[n].shouldDetach=!0,c=n,o.push(c),r.app_logger.info("Detaching function",{func:n,totalFunctionCalls:d}))}),h.length>0&&(0,s.clearMetricsIndicator)(),h},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])c(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=o;return o=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(r.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){r.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),s=n(8269),r=n(523);let o=[],a=null;function d(e){a=e}function c(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(523)),d=o(n(6460)),c=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),w=n(8269),y=n(1427),k=n(6281),C=n(8269),b=n(2546),E=n(6261),T=a.app_logger,_=m.safeCall.bind(m.safeCall,T);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;gracefulShutdownDone=!1;threadStatsBaseline=(0,g.createThreadStatsBaseline)();abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,T.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,c.hudConfig.communicationKeepaliveGrace),this.updateTsNodeConfig()&&T.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),T.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,k._detachAndTerminate)(!0,!1,!0)}catch(e){T.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){try{this.abortWorker()}catch{}c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),T.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw T.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:T.info("Enabled mode"),_(this.getMode()),_(this.periodicGetEndpointsDurationsInvestigationThresholds()),_(this.periodicRefreshRemoteConfig()),_(this.startPeriodicTasks()),_(this.periodicSendMetrics()),_(this.periodicSendDetachedFunctions()),_(this.periodicFetchKnownDetachedFunctions()),_(this.highFrequencySendInvestigations()),_(this.periodicSendProcessedFiles()),_(this.delayedStateCollection()),_(this.periodicSendEndpoints()),_(this.periodicSendOutbounds()),_(this.periodicSendLazyEndpoints()),_(this.periodicSendKafkaJS()),_(this.periodicSendSqs()),_(this.periodicSendGraphQL()),_(this.sendStaticNextJsEndpointsOnce()),_(this.periodicSaveMachineMetrics()),_(this.periodicSendReingest()),_(this.resetCallerCounters()),_(this.periodicResetGlobalInvestigationCounter()),_(this.periodicResetInvestigationDedupingCache()),_(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),_(this.sendRuntime()),_(this.sendPatchedModules()),_(this.sendPreloadedModules()),_(this.dumpModulesAfterWhile(6e4)),_(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:T.info("Disabled mode"),_(this.getMode());break;case l.HudRunningMode.detached:T.info("Detached"),(0,k._detachAndTerminate)(!1,!1),this.stop();break;default:T.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let s;e=Array.isArray(e)?e:[e];const r=this.consumeMessageFromQueue(e);if(r)return T.info("Found message in queue",{msg:r.msg}),r;const o=new AbortController,a=()=>{o.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:o.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(s=t,o.abort(),this.consumeMessageFromQueue([t.msg]),T.info("Received message from worker (canceling timeout)",t))}catch(e){T.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await c,T.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return s}async getMode(){await(0,u.safeUnrefInterval)(async()=>{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);t?.msg===e.msg&&void 0!==t?.content.mode?t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode):T.error("Unexpected message from worker",t)},c.hudConfig.modeInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed getting mode from worker",{msg:e.message,stack:e.stack})})}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,c.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){T.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return T.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)(),await(0,u.safeUnrefInterval)(()=>(0,f.saveMachineMetric)(),c.hudConfig.dynamicConfig.machineMetricsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed saving machine metrics",{msg:e.message,stack:e.stack})})}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting caller",{interval:e}),(0,p.resetCallers)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed reseting caller counters",{msg:e.message,stack:e.stack})})}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),T.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){T.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds(),await(0,u.safeUnrefInterval)(()=>this.updateEndpointDurationsInvestigationThresholds(),c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed updating endpoints durations investigation thresholds",{msg:e.message,stack:e.stack})})}async updateRefreshRemoteConfig(){const e="RefreshRemoteConfig",t={msg:"RefreshRemoteConfig"};try{const n=await this.getMessageFromWorker(e,c.hudConfig.workerMessageTimeout,!1,t);if(n?.msg!==e||void 0===n?.content)return;(0,c.refreshInvestigationEnabled)(n.content,c.hudConfig,T)}catch(e){T.error("Failed refreshing remote config from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicRefreshRemoteConfig(){await(0,u.safeUnrefInterval)(()=>this.updateRefreshRemoteConfig(),c.hudConfig.remoteConfigRefreshInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed refreshing remote config",{msg:e.message,stack:e.stack})})}async delayedStateCollection(){await this.setupPeriodicTask(0,c.hudConfig.workerStateCollectionDelay,()=>{try{this.updateTsNodeConfig()&&T.info("ts-node config updated from delayed task")}catch(e){T.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollection",2)}sendProcessedFiles(){const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();this._sendArray("ProcessedFiles",e)}sendKafkaTopics(){const e=(0,w.getKafkaJSTopics)();this._sendArray("KafkaJSTopics",e)}sendSqsQueues(){const e=(0,w.getSqsQueues)();e.length>0&&this._sendArray("SqsQueue",e)}sendGraphQLOperations(){const e=Object.values((0,w.getGraphQLOperations)());e.length>0&&this._sendArray("GraphQLDeclaration",e)}sendInvocations(e,t){const n=(0,p.prepCalls)(e,t);n.length>0&&this._sendArray("Invocations",n)}sendFlowMetrics(e){const t=(0,f.getFlowMetrics)(e);Object.keys(t).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:t})}sendThreadPerformanceMetrics(){const e=(0,m.collectThreadPerformance)(this.threadStatsBaseline,T,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}sendStaticNextJsEndpointsIfReady(){return!(!(0,g.isNextJsApp)()||!(0,w.isNextConfigExtracted)()||this.staticNextJsEndpointsSent||(this.staticNextJsEndpointsSent=!0,this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify((0,w.getNextConfig)())}),0))}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendProcessedFiles(),!0),"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendKafkaTopics(),!0),"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendSqsQueues(),!0),"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGraphQLOperations(),!0),"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){T.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{this.sendInvocations(t,e)}catch(e){T.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{this.sendFlowMetrics(t)}catch(e){T.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!c.hudConfig.dynamicConfig.functionDetachEnabled||c.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){T.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){T.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){c.hudConfig.dynamicConfig.functionDetachEnabled&&!c.hudConfig.userConfig.disableDetachedFunctions?.value&&await(0,u.safeUnrefInterval)(()=>this.fetchKnownDetachedFunctions(),c.hudConfig.dynamicConfig.aggregationInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed fetching known detached functions",{msg:e.message,stack:e.stack})})}async highFrequencySendInvestigations(){if(!c.hudConfig.dynamicConfig.enableInvestigation)return;const e=c.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=c.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,C.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,C.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}flushAllPendingData(){const e=(0,p.getLastPrepCallsTimestamp)(),t=null===e?c.hudConfig.dynamicConfig.aggregationInterval:Number(process.hrtime.bigint()-e)/1e6,n=Math.max(1,t),i=new h.SketchManager(c.hudConfig.huddBinWidth),s=[{label:"investigations",fn:()=>this.refreshInvestigations()},{label:"invocations",fn:()=>this.sendInvocations(n,i)},{label:"flow metrics",fn:()=>this.sendFlowMetrics(n)},{label:"processed files",fn:()=>this.sendProcessedFiles()},{label:"endpoints",fn:()=>{this.sendEndpoints(),this.sendOutbounds()}},{label:"Kafka topics",fn:()=>this.sendKafkaTopics()},{label:"SQS queues",fn:()=>this.sendSqsQueues()},{label:"GraphQL declarations",fn:()=>this.sendGraphQLOperations()},{label:"static Next.js endpoints",fn:()=>{this.sendStaticNextJsEndpointsIfReady()}},{label:"thread performance metrics",fn:()=>this.sendThreadPerformanceMetrics()}];for(const e of s)try{e.fn()}catch(t){T.error(`Failed flushing ${e.label}`,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}}async sendTerminateAndAwait(e){const t=a.getSavedLogs();try{await this.getMessageFromWorker("terminated",e.grace,e.shouldRef,{msg:"Terminate",content:{grace:e.grace,logBuffers:t}})}catch(t){t instanceof m.HudTimeoutError?(T.critical(e.timeoutLogMsg,{error:t.message}),await this.worker.terminate()):(T.critical(e.unexpectedLogMsg,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),await this.worker.terminate())}}async gracefulShutdown(){if(!this.gracefulShutdownDone){this.gracefulShutdownDone=!0;try{this.abortController.abort(),this.abortController=new AbortController,c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.worker.ref(),this.flushAllPendingData(),await this.sendTerminateAndAwait({grace:c.hudConfig.teardownGrace,shouldRef:!0,timeoutLogMsg:"Teardown grace timeout - terminating worker",unexpectedLogMsg:"Unexpected error during SDK graceful shutdown"})}finally{try{this.worker.unref()}catch{}this.stop()}}}async terminateWorker(){await this.sendTerminateAndAwait({grace:c.hudConfig.workerGrace,shouldRef:!1,timeoutLogMsg:"Grace period timeout - terminating worker",unexpectedLogMsg:"Unexpected error during worker termination"}),T.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):T.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval;await(0,u.safeUnrefInterval)(()=>this.sendThreadPerformanceMetrics(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending thread performance metrics",{msg:e.message,stack:e.stack})})}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(y.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void T.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){await(0,u.safeUnrefInterval)(()=>this.handleLogsTask(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending logs periodically",{msg:e.message,stack:e.stack})})}async setupPeriodicTask(e,t,n,i,s=0){function r(e){let t=!0;try{t=n(e)}catch(e){T.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),!r(e))return void T.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i});if(1===s)return;let o=s>0?s-1:0;await(0,u.safeUnrefInterval)(e=>{if(!r(t))return T.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i}),void e();o>0&&0===--o&&e()},t,{signal:this.abortController.signal,onError:e=>T.error("Failed in periodic task interval",{taskName:i,msg:e.message,stack:e.stack})})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting global investigation counter",{msg:e.message,stack:e.stack})})}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)(),(0,f.getUniqueSetFailureErrors)().clear()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting investigation deduping cache",{msg:e.message,stack:e.stack})})}updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,T.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,k._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;await(0,u.safeUnrefInterval)(e=>{if(n++,T.debug("Attempting to send static next.js endpoints",{attemptCount:n}),this.sendStaticNextJsEndpointsIfReady())return T.info("Sent static next.js endpoints"),void e();n>t&&(T.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:n}),e())},e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending static next.js endpoints",{msg:e.message,stack:e.stack})})}async periodicSendReingest(){await(0,u.safeUnrefInterval)(()=>{const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))},c.hudConfig.dynamicConfig.reingestInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed sending reingest",{msg:e.message,stack:e.stack})})}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}return n.c=t,n(n.s=5119)})());
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1145:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MONGOOSE_QUERY_OPS=t.MONGO_COLLECTION_METHODS=t.CLICKHOUSE_CLIENT_METHODS=t.createOutboundDeclarations=void 0,t.createAxiosDeclaration=a,t.createNodeFetchDeclaration=c,t.createRequestDeclaration=l,t.createPgDeclaration=u,t.createClickHouseDeclaration=d,t.createIoRedisDeclaration=p,t.generateOutboundFunctionId=f,t.createMongoDeclaration=m,t.createMongooseDeclaration=y;const o=n(5809),i=n(8528),r=n(3903),s=n(9850);function a(){return[h("axios","Axios","request",o.hudConfig.axiosFunctionId)]}function c(){return[h("node-fetch","node-fetch","fetch",o.hudConfig.nodeFetchFunctionId),...Object.entries(o.hudConfig.nodeFetchBodiesFunctionIds).map(([e,t])=>h("node-fetch","node-fetch",e,t))]}function l(){return[h("request","request","request",o.hudConfig.requestFunctionId),...Object.entries(o.hudConfig.requestMethodFunctionIds).map(([e,t])=>h("request","request",e,t))]}function u(){return[h("pg","Client","connect",o.hudConfig.pgConnectFunctionId),h("pg","Client","query",o.hudConfig.pgQueryFunctionId),h("pg","Client","end",o.hudConfig.pgEndFunctionId)]}function d(){const e={query:o.hudConfig.clickhouseQueryFunctionId,exec:o.hudConfig.clickhouseExecFunctionId,command:o.hudConfig.clickhouseCommandFunctionId,insert:o.hudConfig.clickhouseInsertFunctionId,close:o.hudConfig.clickhouseCloseFunctionId};return t.CLICKHOUSE_CLIENT_METHODS.map(t=>h("@clickhouse/client-common","ClickHouseClient",t,e[t]))}function p(e){return e&&0!==e.length?e.map(e=>h("ioredis","Redis",e,f("ioredis",e))):[]}function f(e,t){return(0,o.functionUuidToBase64)((0,r.v5)(`${e}-${t}`,o.hudConfig.functionUuidNamespace))}function m(){return[h("mongodb","MongoClient","connect",f("mongodb","connect")),...t.MONGO_COLLECTION_METHODS.map(e=>h("mongodb","Collection",e,f("mongodb",e)))]}function y(){return[h("mongoose","mongoose","connect",f("mongoose","connect")),h("mongoose","mongoose","createConnection",f("mongoose","createConnection")),...t.MONGOOSE_QUERY_OPS.map(e=>h("mongoose","Query",e,f("mongoose",e))),h("mongoose","Aggregate","aggregate",f("mongoose","aggregate")),h("mongoose","Model","insertMany",f("mongoose","insertMany")),h("mongoose","Model","save",f("mongoose","save"))]}function h(e,t,n,o){return{id_generated:!0,module:e,third_party_module:e,file:`${e}.js`,format:"commonjs",async:!0,runtime_function_id:(0,s.rawFunctionIdToUuidFunctionId)(o),type:i.EntityType.ClassMethod,methodKind:"method",symbol:{sourcemap_location_hints:[{name:n,line:0,column:0,source:`${e}.js`}],name:n,format:"%s"},scope_chain:[{type:i.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0},{type:i.EntityType.ClassDeclaration,symbol:{sourcemap_location_hints:[{name:t,line:0,column:0,source:`${e}.js`}],name:t,format:"%s"},context:{},childrenCount:{},siblingIndex:0}],original_location:{file:`${e}.js`,start_line:0,end_line:0,start_column:0,end_column:0},parameters:[],start_line:0,end_line:0,start_column:0,source_code_hash:"1",bundler_build_id:"1",was_bundler_build_id_generated:!0,has_input_map:!0,sourcemap_crc:1,file_path_checksum:1,file_checksum:1,declarations_count:1,childrenCount:{},siblingIndex:0,context:{}}}t.createOutboundDeclarations={axios:a,"node-fetch":c,request:l,pg:u,"@clickhouse/client-common":d,ioredis:p,mongodb:m,mongoose:y},t.CLICKHOUSE_CLIENT_METHODS=["query","exec","command","insert","close"],t.MONGO_COLLECTION_METHODS=["findOne","countDocuments","distinct","insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOneAndUpdate","findOneAndDelete","find","aggregate"],t.MONGOOSE_QUERY_OPS=["find","findOne","count","countDocuments","estimatedDocumentCount","deleteOne","deleteMany","findOneAndDelete","updateOne","updateMany","replaceOne","findOneAndUpdate","findOneAndReplace","distinct"]},1427:e=>{e.exports=require("./nativerequire")},1498:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDeclarationsBatchRequest=function(e){const t=(new Date).toISOString();return{...i.HudClient.defaultRequest,type:"FunctionDeclaration",arr:e,send_time:t,event_version:o.FUNCTION_DECLARATION_VERSION}};const o=n(8528),i=n(4672)},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const r=(0,o.getEntityType)(e);if(r){const s=(0,o.getEntityIdentity)(e.node),a=(0,i.getContextualData)(e,n),c=s?s.loc?[n(s.loc.start,s.name,s.loc.filename??t)]:[]:e.node.loc?[n(e.node.loc.start,void 0,e.node.loc.filename??t)]:[],l=c[0]?.name??s?.name;return{type:r,context:a,symbol:{name:l,sourcemap_location_hints:c,format:l?"%s":void 0},methodKind:(0,i.getMethodKind)(e.node)}}};const o=n(5203),i=n(9127)},2535:function(e,t,n){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const o=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==o.length?i.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:o}):t=r.default.format(e.format,...o):t=o.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const o=e.loc?.start,r=e.loc?.end;if(!o||!r)return i.worker_logger.info("Node without location",{filename:n,type:e.type}),{start:{source:null,line:-1,column:-1},end:{source:null,line:-1,column:-1}};const s=t({line:o.line,column:o.column}),a=t({line:r.line,column:r.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(i.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:o,locEnd:r}),s.line=-1,s.column=-1,a.line=-1,a.column=-1),{start:{source:s.source,line:s.line,column:s.column},end:{source:a.source,line:a.line,column:a.column}}};const i=n(523),r=o(n(9023))},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3176:e=>{e.exports=require("buffer-crc32")},3903:e=>{e.exports=require("uuid")},4634:e=>{e.exports=require("source-map")},4672:e=>{e.exports=require("./client")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return o.types.isFunctionDeclaration(t)?i.EntityType.FunctionDeclaration:o.types.isFunctionExpression(t)?i.EntityType.FunctionExpression:o.types.isArrowFunctionExpression(t)?i.EntityType.FunctionArrow:o.types.isObjectMethod(t)?i.EntityType.ObjectMethod:o.types.isStaticBlock(t)||o.types.isClassMethod(t)?i.EntityType.ClassMethod:o.types.isClassPrivateMethod(t)?i.EntityType.ClassPrivateMethod:o.types.isClassDeclaration(t)?i.EntityType.ClassDeclaration:o.types.isClassExpression(t)?i.EntityType.ClassExpression:o.types.isForInStatement(t)||o.types.isForOfStatement(t)||o.types.isForStatement(t)?i.EntityType.ForLoop:o.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(o.types.isFunctionDeclaration(t)||o.types.isFunctionExpression(t)||o.types.isArrowFunctionExpression(t)||o.types.isClassMethod(t)||o.types.isObjectMethod(t)||o.types.isClassPrivateMethod(t)))if(o.types.isIfStatement(t)){if("consequent"===e.parentKey)return i.EntityType.IfConsequent;if("alternate"===e.parentKey)return i.EntityType.IfAlternate;if("test"===e.parentKey)return i.EntityType.IfTest}else{if(o.types.isBlockStatement(t)||o.types.isProgram(t))return i.EntityType.Block;if(o.types.isTryStatement(t)){if("block"===e.parentKey)return i.EntityType.Try;if("finalizer"===e.parentKey)return i.EntityType.Finally}else{if(o.types.isCatchClause(t))return;if(o.types.isWhileStatement(t))return"test"===e.parentKey?i.EntityType.WhileTest:i.EntityType.Do;if(o.types.isDoWhileStatement(t))return"test"===e.parentKey?i.EntityType.WhileTest:i.EntityType.Do;if(!(o.types.isForStatement(t)||o.types.isForInStatement(t)||o.types.isForOfStatement(t)))return;if("test"===e.parentKey)return i.EntityType.ForTest;if("body"===e.parentKey)return i.EntityType.ForBlock}}}(e):o.types.isProgram(t)?i.EntityType.Program:o.types.isDoWhileStatement(t)?i.EntityType.DoWhile:o.types.isWhileStatement(t)?i.EntityType.While:o.types.isCatchClause(t)?i.EntityType.Catch:o.types.isObjectExpression(t)?i.EntityType.ObjectExpression:o.types.isWithStatement(t)?i.EntityType.With:o.types.isSwitchStatement(t)?i.EntityType.Switch:o.types.isSwitchCase(t)?i.EntityType.SwitchCase:o.types.isTryStatement(t)?i.EntityType.TryCatch:o.types.isIfStatement(t)?i.EntityType.If:i.EntityType.Other},t.getEntityIdentity=function(e){return o.types.isFunctionDeclaration(e)?o.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Function declaration without an identifier"):o.types.isClassDeclaration(e)?o.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Class declaration without an identifier"):o.types.isFunctionExpression(e)||o.types.isClassExpression(e)?o.types.isIdentifier(e.id)?e.id:void 0:o.types.isClassMethod(e)?o.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Class method without an identifier"):o.types.isObjectMethod(e)?o.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Object method without an identifier"):o.types.isClassPrivateMethod(e)?o.types.isIdentifier(e.key.id)?e.key.id:void r.worker_logger.info("Class private method without an identifier"):void 0};const o=n(6346),i=n(8528),r=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(1498),t),i(n(9850),t),i(n(1145),t),i(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getParameterInfo=function(e,t){return e.node.params.map(e=>{try{return d(e,t)}catch{return}}).filter(e=>void 0!==e)};const a=s(n(6346)),c=n(8528),l=n(523);function u(e,t){if(a.types.isIdentifier(e.argument)){const n=e.argument.loc?t(e.argument.loc.start):void 0;return{name:n?.name??e.argument.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}{l.worker_logger.warning("Unsupported rest element",{type:e.argument.type});const n=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}}function d(e,t){if(e)switch(e?.type){case"Identifier":return function(e,t){const n=e.loc?t(e.loc.start,e.name):void 0;return{name:n?.name??e.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}(e,t);case"AssignmentPattern":return function(e,t,n,o){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,left:t,right:o}}(e,d(e.left,t),t,function(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"BigIntLiteral":case"DecimalLiteral":return{type:e.type,value:e.value};case"RegExpLiteral":return{type:e.type,value:e.pattern}}return{type:e.type}}(e.right));case"ArrayPattern":return function(e,t,n){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,elements:t}}(e,e.elements.map(e=>d(e,t)).filter(e=>void 0!==e),t);case"RestElement":return u(e,t);case"ObjectPattern":{const n=[];return e.properties.forEach(e=>{if(a.types.isObjectProperty(e)){const o=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:d(e.key,t);n.push(function(e,t,n,o){const i=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,key:n,value:o}}(e,t,o,d(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,properties:t}}(e,n,t)}default:l.worker_logger.warning("Unsupported parameter type",{type:e.type})}}},8528:e=>{e.exports=require("./dto")},9011:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NamespaceScopeAlias=t.ScopableAlias=void 0,t.isHudScopeable=function(e){return o.types.isArrowFunctionExpression(e)||o.types.isBlockStatement(e)||o.types.isCatchClause(e)||o.types.isClassMethod(e)||o.types.isClassPrivateMethod(e)||o.types.isDeclareModule(e)||o.types.isDoExpression(e)||o.types.isDoWhileStatement(e)||o.types.isForInStatement(e)||o.types.isForOfStatement(e)||o.types.isForStatement(e)||o.types.isFunctionDeclaration(e)||o.types.isFunctionExpression(e)||o.types.isIfStatement(e)||o.types.isLabeledStatement(e)||o.types.isObjectMethod(e)||o.types.isProgram(e)||o.types.isStaticBlock(e)||o.types.isSwitchCase(e)||o.types.isTSModuleBlock(e)||o.types.isTryStatement(e)||o.types.isWhileStatement(e)||o.types.isWithStatement(e)||o.types.isClassDeclaration(e)||o.types.isClassExpression(e)||o.types.isObjectExpression(e)||o.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return o.types.isFunction(e)||o.types.isClass(e)||o.types.isObjectExpression(e)};const o=n(6346);t.ScopableAlias="ArrowFunctionExpression|BlockStatement|CatchClause|ClassMethod|ClassPrivateMethod|DeclareModule|DoExpression|DoWhileStatement|ForInStatement|ForOfStatement|ForStatement|FunctionDeclaration|FunctionExpression|IfStatement|LabeledStatement|ObjectMethod|StaticBlock|SwitchCase|TSModuleBlock|TryStatement|WhileStatement|WithStatement|ClassDeclaration|ClassExpression|ObjectExpression|SwitchStatement",t.NamespaceScopeAlias="FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod|ClassPrivateMethod|ClassDeclaration|ClassExpression|ObjectExpression"},9023:e=>{e.exports=require("util")},9127:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionIdentifier=function(e){const{node:t}=e;if(c.types.isFunctionDeclaration(t)||c.types.isFunctionExpression(t)){if(c.types.isIdentifier(t.id))return t.id}else if(c.types.isClassMethod(t)){if(c.types.isIdentifier(t.key))return t.key}else if(c.types.isClassPrivateMethod(t)){if(c.types.isIdentifier(t.key.id))return t.key.id}else if(c.types.isObjectMethod(t)&&c.types.isIdentifier(t.key))return t.key},t.getContextSymbol=h,t.getContextualData=function(e,t){let n,o;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[o,i]of n.node.arguments.entries())if(i===e.node){const i=n.node.callee;let r;try{r=m(i,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${i.type}-${e.node.type}`;b.has(n)||(d.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:i.type,nodeType:e.node.type}),b.add(n))}}const s=g(n.node,t);return{callee:{symbol:r,argsCount:n.node.arguments.length,args:s},index:o}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(o=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const i=h(e,t);return i&&(i.name=(0,p.getSymbolName)(i)),{symbol:i,callback:n,immediatelyInvoked:o}},t.getMethodKind=function(e){if(a.types.isClassMethod(e)||a.types.isObjectMethod(e)||a.types.isClassPrivateMethod(e))return e.kind};const a=s(n(6346)),c=n(6346),l=n(8528),u=n(2546),d=n(523),p=n(2535);function f(e,t,n){const o=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:o?.name??t,sourcemap_location_hints:o?[o]:[],format:"%s"}}function m(e,t){if(c.types.isIdentifier(e)){const n=e.loc?[t(e.loc.start,e.name,e.loc.filename)]:[];return{name:n[0]?.name??e.name,sourcemap_location_hints:n,format:"%s"}}if(c.types.isMemberExpression(e)||c.types.isOptionalMemberExpression(e)){let n;n=c.types.isThisExpression(e.object)?{name:"this",sourcemap_location_hints:e.object.loc?[t(e.object.loc.start,"this",e.object.loc.filename)]:[]}:m(e.object,t);const o=m(e.property,t),i=e.computed?n.name+"["+o.name+"]":n.name+"."+o.name,r=n.format??"%s",s=o.format??"%s",a=e.computed?`${r}[${s}]`:`${r}.${s}`;return{name:i,sourcemap_location_hints:[...n.sourcemap_location_hints,...o.sourcemap_location_hints],format:a}}if(c.types.isOptionalCallExpression(e)||c.types.isCallExpression(e))return m(e.callee,t);if(c.types.isSequenceExpression(e))return m(e.expressions[e.expressions.length-1],t);if(c.types.isArrayExpression(e))return{name:"[]",sourcemap_location_hints:e.loc?[t(e.loc.start,"[]",e.loc.filename)]:[],format:"%s"};if(c.types.isObjectExpression(e))return{name:"{}",sourcemap_location_hints:e.loc?[t(e.loc.start,"{}",e.loc.filename)]:[],format:"%s"};if(c.types.isStringLiteral(e)){const n=e.loc?[t(e.loc.start,e.value,e.loc.filename)]:[];return{name:`"${n[0]?.name??e.value}"`,sourcemap_location_hints:n,format:'"%s"'}}throw new u.HudUnsupportedError("Unsupported left side of assignment - "+e.type+"loc - "+JSON.stringify(e.loc))}const y=new Set;function h(e,t){const{node:n}=e;if(e.isExpression())try{return function(e,t){const{parent:n}=e;if(c.types.isVariableDeclarator(n)&&c.types.isIdentifier(n.id))return f(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return f(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return f(n,n.key.name,t);if(c.types.isAssignmentExpression(n))return m(n.left,t);if(c.types.isAssignmentPattern(n))return m(n.left,t);throw new u.HudUnsupportedError(`Unsupported parent type - ${n.type} for me ${e.node.type}`)}(e,t)}catch(t){if(t instanceof u.HudUnsupportedError){const n=`${e.parentPath?.node.type}`;return void(y.has(n)||(d.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),y.add(n)))}throw t}d.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function g(e,t){const n=[];return e.arguments.forEach((e,o)=>{let i,r;if(c.types.isStringLiteral(e)?(i=l.ArgumentTypes.StringLiteral,r=e.value):c.types.isTemplateLiteral(e)?(i=l.ArgumentTypes.TemplateString,r=function(e){let t="";const n=e.quasis,o=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<o.length&&(t+=`\${${_(o[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(i=l.ArgumentTypes.Identifier,r=e.name),i&&r){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:o,type:i,value:a?.name??r,sourcemap_location_hint:a})}}),n}function _(e){if(c.types.isIdentifier(e))return e.name;if(c.types.isStringLiteral(e))return e.value;if(c.types.isCallExpression(e)||c.types.isOptionalCallExpression(e)){const t=e;if(c.types.isIdentifier(t.callee))return t.callee.name;if(c.types.isMemberExpression(t.callee)||c.types.isOptionalMemberExpression(t.callee)){let e="";const n=t.callee;if(c.types.isThisExpression(n.object)?e+="this.":c.types.isIdentifier(n.object)&&(e+=`${n.object.name}.`),""!==e&&c.types.isIdentifier(n.property))return e+=`${n.property.name}`,e}}return""}const b=new Set},9850:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fixSourceMap=I,t.getRealPositionNothingFunc=M,t.getRealPositionOffsetsFunc=F,t.getRealPositionSourceMapFunc=T,t.parseDeclarations=async function(e,t,n=null,o,i=!1){const{filename:r,bundlerBuildId:s,bundlerBuildIdGenerated:a,lineOffset:M,columnOffset:A,file_path_checksum:N,file_checksum:q,functionIds:B,sourceCodeHash:L,moduleBase:U,isNextJsApp:R,marksCount:$,prebundle_file_checksum:H}=e,W=H??q;if(g.worker_logger.debug("Parsing code",{filename:r}),o)try{if(!j){const e=(0,_.myRequire)("ts-node");j=e.create({...o,transpileOnly:!0,typeCheck:!1})}const e=function(e,t,n){try{return n.compile(e,t)}catch(e){return void g.worker_logger.warning("ts file pass, but failed to compile with ts-node",{filename:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(t,r,j);if(!e)return{declarations:[],blacklist:{file_path_checksum:N,file_checksum:W,uuids:B},generatedAsyncFunctions:[]};t=e}catch(e){return g.worker_logger.error("Failed to require and compile ts file",{filename:r,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),{declarations:[],blacklist:{file_path_checksum:N,file_checksum:W,uuids:B},generatedAsyncFunctions:[]}}else if(r.endsWith(".ts")||r.endsWith(".mts"))return g.worker_logger.error("ts file pass, but not found ts-options"),{declarations:[],blacklist:{file_path_checksum:N,file_checksum:W,uuids:B},generatedAsyncFunctions:[]};const K=(0,b.default)(t).readUInt32BE();if(K!==q)return g.worker_logger.warning("File checksum mismatch",{filename:r,file_path_checksum:N,diskFileChecksum:K,file_checksum:q,functionIds:B}),{declarations:[],blacklist:{file_path_checksum:N,file_checksum:W,uuids:B},generatedAsyncFunctions:[]};let G,Q,J=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(function(e){return void 0!==e.lineOffset&&void 0!==e.columnOffset&&(0!==e.lineOffset||0!==e.columnOffset)}(e))J=F(M,A);else{const e=(0,v.getSourceMap)(r,t);try{null!==e&&(Q=(0,b.default)(e).readUInt32BE(),f.hudConfig.userConfig.disableSourceMapsResolution?.value||(G=JSON.parse(e),G&&(J=T(await new u.SourceMapConsumer(I(G))))))}catch(e){g.worker_logger.error("Failed to parse source map",{filename:r,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}g.worker_logger.debug("Parsing code",{filename:r});const V=[],z=new w(t,U),Y=z.getRemainingMarksCount(),X=await c.parseAsync(t,S);if(null===X)return g.worker_logger.warning("Failed parsing code to tree",{filename:r,file_path_checksum:N,diskFileChecksum:K,file_checksum:W,functionIds:B}),{declarations:[],blacklist:{file_path_checksum:N,file_checksum:W,uuids:B},generatedAsyncFunctions:[]};g.worker_logger.debug("Parsed code to tree",{filename:r});const Z=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],ee=new Set,te=[];g.worker_logger.debug("Traversing declarations",{filename:r}),n?.postMessage("eventlooptime"),c.traverse(X,{AssignmentExpression:{enter(e){const t=function(e){try{const{node:t}=e,n=t.left;if("MemberExpression"!==n.type)return;const o=n.object;if("Identifier"!==o.type)return;if("globalThis"!==o.name)return;const i=n.property;if("Identifier"!==i.type)return;if(i.name!==f.hudConfig.esbuildFunctionIdVar)return;const r=t.right;if("StringLiteral"!==r.type)return;const s=r.value.split(":");if(2!==s.length)return;return{functionId:D(s[0]),functionHash:s[1]}}catch{return}}(e);t&&(te[te.length-1]=t)}},[x.NamespaceScopeAlias]:{enter(e){const{node:t}=e;if(!(0,x.isNamespaceScopeable)(t))return;const n=Z[Z.length-1],o=(0,k.getScope)(e,r,J);if(!o)return;const i=n.childrenCount[o.type]||0,s={...o,childrenCount:{},siblingIndex:i};n.childrenCount[o.type]=i+1,Z.push(s),ee.add(t),e.isFunction()&&te.push(null)},exit(e){const{node:n}=e;!function(){if(e.isFunction()){const n=te.pop()??null,o=function(e,t,n,o,i,r,s,a){try{const l=(0,h.getInstrumentedThirdPartyModuleInfo)(n);let u;if(l){if(!function(e,t){const n=(0,p.getFunctionIdentifier)(e);if(!n)return!1;const o=n.name;return t.functions.includes(o)}(e,l))return;u=l.moduleName}if(!1===f.hudConfig.userConfig.instrumentOneLiners?.value&&function(e){const t=e.node;if("ArrowFunctionExpression"!==t.type)return!1;if(t.async||t.generator)return!1;if("BlockStatement"!==t.body.type)return!0;const n=t.body;return 1===n.body.length&&"ReturnStatement"===n.body[0].type}(e))return;const _=P(e);if(!_)throw new Error("Function node has no block start location");const v=e;if(void 0===e.node.start||null===e.node.start||void 0===e.node.end||null===e.node.end)throw new Error("Function node has no start or end location");let k=a?.functionId??null;const x=null===k;null===k&&(k=function(e,t,n,o){const i=o.slice(0,n),r=`${e}_${t}_${Buffer.byteLength(i,"utf8")}`;return d.v5(r,f.hudConfig.functionUuidNamespace).toString()}(t,n,_.start-(i-1),r));const S=a?.functionHash??(c=r.slice(e.node.start,e.node.end),(0,b.default)(c).readUInt32BE().toString());if(!S)return void g.worker_logger.warning("Function hash not found",{functionId:k,filename:n});const w=v.node.async||!1,I=v.node.loc?s(v.node.loc.start,void 0,n):void 0,M=v.node.loc?s(v.node.loc.end,void 0,n):void 0,F=I?.source??n,T=(0,E.getEntityType)(v),j=(0,p.getMethodKind)(v.node),D=(0,p.getContextualData)(v,s),A=(0,O.getParameterInfo)(v,s),{siblingIndex:N,childrenCount:q}=o[o.length-1],B=o.slice(0,-1),L=(0,p.getFunctionIdentifier)(v),U=L?L.loc?[s(L.loc.start,L.name,F)]:[]:v.node.loc?[s(v.node.loc.start,void 0,F)]:[],R=U[0]?.name??L?.name,$={name:R,sourcemap_location_hints:U,format:R?"%s":void 0};return $.name&&($.name=(0,C.getSymbolName)($)),{module:m.default.parse(F).name,symbol:$,context:D,file:F,type:T,format:y.Format.cjs,parameters:A,async:w,start_line:I?.line??-1,end_line:M?.line??-1,start_column:I?.column??-1,source_code_hash:S,runtime_function_id:k,scope_chain:B,methodKind:j,siblingIndex:N,childrenCount:q,third_party_module:u,original_location:{file:n,start_line:e.node.loc?.start?.line,end_line:e.node.loc?.end?.line,start_column:e.node.loc?.start?.column,end_column:e.node.loc?.end?.column},id_generated:x}}catch(e){g.worker_logger.error("Failed to handle function",{filename:n,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}var c}(e,L,r,Z,U,t,J,n);if(!o)return;if(!R)return void V.push(o);const i=P(e);if(!i)return;z.functionContainsMark(i.start,i.end)&&V.push(o)}}(),ee.has(n)&&(Z.pop(),ee.delete(n))}}}),g.worker_logger.debug("Traversed declarations",{filename:r}),R&&$!==V.length&&g.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:r,marksCount:$,declarationsCount:V.length,remainingMarks:z.getRemainingMarksCount(),initialMarkCount:Y});const{declarations:ne,blacklist:oe,generatedAsyncFunctions:ie}=function(e,t,n,o,i,r,s,a,c,l){t=t.map(D);const u=new Set(t),d=new Set(e.map(e=>e.runtime_function_id));let p=[];const f=[],m=[];e.forEach(e=>{u.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:o,has_input_map:void 0!==i,sourcemap_crc:r,file_path_checksum:s,file_checksum:a}):l&&e.id_generated?e.async&&m.push(e):f.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),f.length>0&&g.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t,missingInstrumentation:f});const y=new Set;u.forEach(e=>{d.has(e)||y.add(e)});const h=y.size>0;return h&&g.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...y]}),{declarations:p,blacklist:h?{file_path_checksum:s,file_checksum:a,uuids:[...y]}:void 0,generatedAsyncFunctions:m}}(V,B,s,a,G,Q,N,W,r,i);return{declarations:ne,blacklist:oe,generatedAsyncFunctions:ie}},t.rawFunctionIdToUuidFunctionId=D;const c=s(n(6346)),l=n(8528),u=n(4634),d=s(n(3903)),p=n(9127),f=n(5809),m=a(n(6760)),y=n(8528),h=n(2546),g=n(523),_=n(1427),b=a(n(3176)),v=n(2784),E=n(5203),O=n(6864),k=n(1602),C=n(2535),x=n(9011),S={babelrc:!1,configFile:!1};class w{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=f.hudConfig.nextJsMarkVarName;let n=0,o=e.indexOf(t,n);for(;-1!==o;)this.markPositions.push(o),n=o+t.length,o=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,o=t-this.moduleBase;let i=!1,r=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=o){i=!0,r=e;break}}return i&&this.markPositions.splice(r,1),i}getRemainingMarksCount(){return this.markPositions.length}}function I(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function M(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function F(e,t){return(n,o,i)=>({name:o??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:i??void 0})}function T(e){return(t,n,o)=>{const i=e.originalPositionFor({line:t.line,column:t.column});return i?{name:i.name??n,line:i.line??-1,column:i.column??-1,source:i.source??o,resolved:!0,server:{name:n,line:t.line,column:t.column,source:o}}:{name:n??void 0,line:t.line,column:t.column,source:o??void 0,resolved:!1}}}function P(e){let t=e.node.body.loc?.start?.index;if(void 0===t)return null;"ArrowFunctionExpression"===e.node.type&&e.node.body.extra?.parenthesized&&e.node.body.extra?.parenStart&&Number.isInteger(e.node.body.extra.parenStart)&&(t=e.node.body.extra.parenStart);const n=e.node.end;return null==n?null:{start:t,end:n}}let j;function D(e){try{return d.stringify(Buffer.from(e+"==","base64"))}catch(t){throw g.worker_logger.error("Failed to convert raw function id to uuid function id",{rawFunctionId:e,error:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),t}}}},t={};return function n(o){var i=t[o];if(void 0!==i)return i.exports;var r=t[o]={exports:{}};return e[o].call(r.exports,r,r.exports,n),r.exports}(6066)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var o in n)("object"==typeof exports?exports:e)[o]=n[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1145:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MONGOOSE_QUERY_OPS=t.MONGO_COLLECTION_METHODS=t.CLICKHOUSE_CLIENT_METHODS=t.createOutboundDeclarations=void 0,t.createAxiosDeclaration=a,t.createNodeFetchDeclaration=c,t.createRequestDeclaration=l,t.createPgDeclaration=u,t.createClickHouseDeclaration=d,t.createIoRedisDeclaration=p,t.generateOutboundFunctionId=f,t.createMongoDeclaration=m,t.createMongooseDeclaration=y;const o=n(5809),i=n(8528),r=n(3903),s=n(9850);function a(){return[h("axios","Axios","request",o.hudConfig.axiosFunctionId)]}function c(){return[h("node-fetch","node-fetch","fetch",o.hudConfig.nodeFetchFunctionId),...Object.entries(o.hudConfig.nodeFetchBodiesFunctionIds).map(([e,t])=>h("node-fetch","node-fetch",e,t))]}function l(){return[h("request","request","request",o.hudConfig.requestFunctionId),...Object.entries(o.hudConfig.requestMethodFunctionIds).map(([e,t])=>h("request","request",e,t))]}function u(){return[h("pg","Client","connect",o.hudConfig.pgConnectFunctionId),h("pg","Client","query",o.hudConfig.pgQueryFunctionId),h("pg","Client","end",o.hudConfig.pgEndFunctionId)]}function d(){const e={query:o.hudConfig.clickhouseQueryFunctionId,exec:o.hudConfig.clickhouseExecFunctionId,command:o.hudConfig.clickhouseCommandFunctionId,insert:o.hudConfig.clickhouseInsertFunctionId,close:o.hudConfig.clickhouseCloseFunctionId};return t.CLICKHOUSE_CLIENT_METHODS.map(t=>h("@clickhouse/client-common","ClickHouseClient",t,e[t]))}function p(e){return e&&0!==e.length?e.map(e=>h("ioredis","Redis",e,f("ioredis",e))):[]}function f(e,t){return(0,o.functionUuidToBase64)((0,r.v5)(`${e}-${t}`,o.hudConfig.functionUuidNamespace))}function m(){return[h("mongodb","MongoClient","connect",f("mongodb","connect")),...t.MONGO_COLLECTION_METHODS.map(e=>h("mongodb","Collection",e,f("mongodb",e)))]}function y(){return[h("mongoose","mongoose","connect",f("mongoose","connect")),h("mongoose","mongoose","createConnection",f("mongoose","createConnection")),...t.MONGOOSE_QUERY_OPS.map(e=>h("mongoose","Query",e,f("mongoose",e))),h("mongoose","Aggregate","aggregate",f("mongoose","aggregate")),h("mongoose","Model","insertMany",f("mongoose","insertMany")),h("mongoose","Model","save",f("mongoose","save"))]}function h(e,t,n,o){return{id_generated:!0,module:e,third_party_module:e,file:`${e}.js`,format:"commonjs",async:!0,runtime_function_id:(0,s.rawFunctionIdToUuidFunctionId)(o),type:i.EntityType.ClassMethod,methodKind:"method",symbol:{sourcemap_location_hints:[{name:n,line:0,column:0,source:`${e}.js`}],name:n,format:"%s"},scope_chain:[{type:i.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0},{type:i.EntityType.ClassDeclaration,symbol:{sourcemap_location_hints:[{name:t,line:0,column:0,source:`${e}.js`}],name:t,format:"%s"},context:{},childrenCount:{},siblingIndex:0}],original_location:{file:`${e}.js`,start_line:0,end_line:0,start_column:0,end_column:0},parameters:[],start_line:0,end_line:0,start_column:0,source_code_hash:"1",bundler_build_id:"1",was_bundler_build_id_generated:!0,has_input_map:!0,sourcemap_crc:1,file_path_checksum:1,file_checksum:1,declarations_count:1,childrenCount:{},siblingIndex:0,context:{}}}t.createOutboundDeclarations={axios:a,"node-fetch":c,request:l,pg:u,"@clickhouse/client-common":d,ioredis:p,mongodb:m,mongoose:y},t.CLICKHOUSE_CLIENT_METHODS=["query","exec","command","insert","close"],t.MONGO_COLLECTION_METHODS=["findOne","countDocuments","distinct","insertOne","insertMany","updateOne","updateMany","replaceOne","deleteOne","deleteMany","findOneAndUpdate","findOneAndDelete","find","aggregate"],t.MONGOOSE_QUERY_OPS=["find","findOne","count","countDocuments","estimatedDocumentCount","deleteOne","deleteMany","findOneAndDelete","updateOne","updateMany","replaceOne","findOneAndUpdate","findOneAndReplace","distinct"]},1427:e=>{e.exports=require("./nativerequire")},1498:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getDeclarationsBatchRequest=function(e){const t=(new Date).toISOString();return{...i.HudClient.defaultRequest,type:"FunctionDeclaration",arr:e,send_time:t,event_version:o.FUNCTION_DECLARATION_VERSION}};const o=n(8528),i=n(4672)},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const r=(0,o.getEntityType)(e);if(r){const s=(0,o.getEntityIdentity)(e.node),a=(0,i.getContextualData)(e,n),c=s?s.loc?[n(s.loc.start,s.name,s.loc.filename??t)]:[]:e.node.loc?[n(e.node.loc.start,void 0,e.node.loc.filename??t)]:[],l=c[0]?.name??s?.name;return{type:r,context:a,symbol:{name:l,sourcemap_location_hints:c,format:l?"%s":void 0},methodKind:(0,i.getMethodKind)(e.node)}}};const o=n(5203),i=n(9127)},2535:function(e,t,n){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const o=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==o.length?i.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:o}):t=r.default.format(e.format,...o):t=o.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const o=e.loc?.start,r=e.loc?.end;if(!o||!r)return i.worker_logger.info("Node without location",{filename:n,type:e.type}),{start:{source:null,line:-1,column:-1},end:{source:null,line:-1,column:-1}};const s=t({line:o.line,column:o.column}),a=t({line:r.line,column:r.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(i.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:o,locEnd:r}),s.line=-1,s.column=-1,a.line=-1,a.column=-1),{start:{source:s.source,line:s.line,column:s.column},end:{source:a.source,line:a.line,column:a.column}}};const i=n(523),r=o(n(9023))},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3176:e=>{e.exports=require("buffer-crc32")},3903:e=>{e.exports=require("uuid")},4634:e=>{e.exports=require("source-map")},4672:e=>{e.exports=require("./client")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return o.types.isFunctionDeclaration(t)?i.EntityType.FunctionDeclaration:o.types.isFunctionExpression(t)?i.EntityType.FunctionExpression:o.types.isArrowFunctionExpression(t)?i.EntityType.FunctionArrow:o.types.isObjectMethod(t)?i.EntityType.ObjectMethod:o.types.isStaticBlock(t)||o.types.isClassMethod(t)?i.EntityType.ClassMethod:o.types.isClassPrivateMethod(t)?i.EntityType.ClassPrivateMethod:o.types.isClassDeclaration(t)?i.EntityType.ClassDeclaration:o.types.isClassExpression(t)?i.EntityType.ClassExpression:o.types.isForInStatement(t)||o.types.isForOfStatement(t)||o.types.isForStatement(t)?i.EntityType.ForLoop:o.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(o.types.isFunctionDeclaration(t)||o.types.isFunctionExpression(t)||o.types.isArrowFunctionExpression(t)||o.types.isClassMethod(t)||o.types.isObjectMethod(t)||o.types.isClassPrivateMethod(t)))if(o.types.isIfStatement(t)){if("consequent"===e.parentKey)return i.EntityType.IfConsequent;if("alternate"===e.parentKey)return i.EntityType.IfAlternate;if("test"===e.parentKey)return i.EntityType.IfTest}else{if(o.types.isBlockStatement(t)||o.types.isProgram(t))return i.EntityType.Block;if(o.types.isTryStatement(t)){if("block"===e.parentKey)return i.EntityType.Try;if("finalizer"===e.parentKey)return i.EntityType.Finally}else{if(o.types.isCatchClause(t))return;if(o.types.isWhileStatement(t))return"test"===e.parentKey?i.EntityType.WhileTest:i.EntityType.Do;if(o.types.isDoWhileStatement(t))return"test"===e.parentKey?i.EntityType.WhileTest:i.EntityType.Do;if(!(o.types.isForStatement(t)||o.types.isForInStatement(t)||o.types.isForOfStatement(t)))return;if("test"===e.parentKey)return i.EntityType.ForTest;if("body"===e.parentKey)return i.EntityType.ForBlock}}}(e):o.types.isProgram(t)?i.EntityType.Program:o.types.isDoWhileStatement(t)?i.EntityType.DoWhile:o.types.isWhileStatement(t)?i.EntityType.While:o.types.isCatchClause(t)?i.EntityType.Catch:o.types.isObjectExpression(t)?i.EntityType.ObjectExpression:o.types.isWithStatement(t)?i.EntityType.With:o.types.isSwitchStatement(t)?i.EntityType.Switch:o.types.isSwitchCase(t)?i.EntityType.SwitchCase:o.types.isTryStatement(t)?i.EntityType.TryCatch:o.types.isIfStatement(t)?i.EntityType.If:i.EntityType.Other},t.getEntityIdentity=function(e){return o.types.isFunctionDeclaration(e)?o.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Function declaration without an identifier"):o.types.isClassDeclaration(e)?o.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Class declaration without an identifier"):o.types.isFunctionExpression(e)||o.types.isClassExpression(e)?o.types.isIdentifier(e.id)?e.id:void 0:o.types.isClassMethod(e)?o.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Class method without an identifier"):o.types.isObjectMethod(e)?o.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Object method without an identifier"):o.types.isClassPrivateMethod(e)?o.types.isIdentifier(e.key.id)?e.key.id:void r.worker_logger.info("Class private method without an identifier"):void 0};const o=n(6346),i=n(8528),r=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var o=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||o(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),i(n(1498),t),i(n(9850),t),i(n(1145),t),i(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getParameterInfo=function(e,t){return e.node.params.map(e=>{try{return d(e,t)}catch{return}}).filter(e=>void 0!==e)};const a=s(n(6346)),c=n(8528),l=n(523);function u(e,t){if(a.types.isIdentifier(e.argument)){const n=e.argument.loc?t(e.argument.loc.start):void 0;return{name:n?.name??e.argument.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}{l.worker_logger.warning("Unsupported rest element",{type:e.argument.type});const n=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}}function d(e,t){if(e)switch(e?.type){case"Identifier":return function(e,t){const n=e.loc?t(e.loc.start,e.name):void 0;return{name:n?.name??e.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}(e,t);case"AssignmentPattern":return function(e,t,n,o){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,left:t,right:o}}(e,d(e.left,t),t,function(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"BigIntLiteral":case"DecimalLiteral":return{type:e.type,value:e.value};case"RegExpLiteral":return{type:e.type,value:e.pattern}}return{type:e.type}}(e.right));case"ArrayPattern":return function(e,t,n){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,elements:t}}(e,e.elements.map(e=>d(e,t)).filter(e=>void 0!==e),t);case"RestElement":return u(e,t);case"ObjectPattern":{const n=[];return e.properties.forEach(e=>{if(a.types.isObjectProperty(e)){const o=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:d(e.key,t);n.push(function(e,t,n,o){const i=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,key:n,value:o}}(e,t,o,d(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,properties:t}}(e,n,t)}default:l.worker_logger.warning("Unsupported parameter type",{type:e.type})}}},8528:e=>{e.exports=require("./dto")},9011:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NamespaceScopeAlias=t.ScopableAlias=void 0,t.isHudScopeable=function(e){return o.types.isArrowFunctionExpression(e)||o.types.isBlockStatement(e)||o.types.isCatchClause(e)||o.types.isClassMethod(e)||o.types.isClassPrivateMethod(e)||o.types.isDeclareModule(e)||o.types.isDoExpression(e)||o.types.isDoWhileStatement(e)||o.types.isForInStatement(e)||o.types.isForOfStatement(e)||o.types.isForStatement(e)||o.types.isFunctionDeclaration(e)||o.types.isFunctionExpression(e)||o.types.isIfStatement(e)||o.types.isLabeledStatement(e)||o.types.isObjectMethod(e)||o.types.isProgram(e)||o.types.isStaticBlock(e)||o.types.isSwitchCase(e)||o.types.isTSModuleBlock(e)||o.types.isTryStatement(e)||o.types.isWhileStatement(e)||o.types.isWithStatement(e)||o.types.isClassDeclaration(e)||o.types.isClassExpression(e)||o.types.isObjectExpression(e)||o.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return o.types.isFunction(e)||o.types.isClass(e)||o.types.isObjectExpression(e)};const o=n(6346);t.ScopableAlias="ArrowFunctionExpression|BlockStatement|CatchClause|ClassMethod|ClassPrivateMethod|DeclareModule|DoExpression|DoWhileStatement|ForInStatement|ForOfStatement|ForStatement|FunctionDeclaration|FunctionExpression|IfStatement|LabeledStatement|ObjectMethod|StaticBlock|SwitchCase|TSModuleBlock|TryStatement|WhileStatement|WithStatement|ClassDeclaration|ClassExpression|ObjectExpression|SwitchStatement",t.NamespaceScopeAlias="FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod|ClassPrivateMethod|ClassDeclaration|ClassExpression|ObjectExpression"},9023:e=>{e.exports=require("util")},9127:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionIdentifier=function(e){const{node:t}=e;if(c.types.isFunctionDeclaration(t)||c.types.isFunctionExpression(t)){if(c.types.isIdentifier(t.id))return t.id}else if(c.types.isClassMethod(t)){if(c.types.isIdentifier(t.key))return t.key}else if(c.types.isClassPrivateMethod(t)){if(c.types.isIdentifier(t.key.id))return t.key.id}else if(c.types.isObjectMethod(t)&&c.types.isIdentifier(t.key))return t.key},t.getContextSymbol=h,t.getContextualData=function(e,t){let n,o;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[o,i]of n.node.arguments.entries())if(i===e.node){const i=n.node.callee;let r;try{r=m(i,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${i.type}-${e.node.type}`;b.has(n)||(d.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:i.type,nodeType:e.node.type}),b.add(n))}}const s=g(n.node,t);return{callee:{symbol:r,argsCount:n.node.arguments.length,args:s},index:o}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(o=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const i=h(e,t);return i&&(i.name=(0,p.getSymbolName)(i)),{symbol:i,callback:n,immediatelyInvoked:o}},t.getMethodKind=function(e){if(a.types.isClassMethod(e)||a.types.isObjectMethod(e)||a.types.isClassPrivateMethod(e))return e.kind};const a=s(n(6346)),c=n(6346),l=n(8528),u=n(2546),d=n(523),p=n(2535);function f(e,t,n){const o=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:o?.name??t,sourcemap_location_hints:o?[o]:[],format:"%s"}}function m(e,t){if(c.types.isIdentifier(e)){const n=e.loc?[t(e.loc.start,e.name,e.loc.filename)]:[];return{name:n[0]?.name??e.name,sourcemap_location_hints:n,format:"%s"}}if(c.types.isMemberExpression(e)||c.types.isOptionalMemberExpression(e)){let n;n=c.types.isThisExpression(e.object)?{name:"this",sourcemap_location_hints:e.object.loc?[t(e.object.loc.start,"this",e.object.loc.filename)]:[]}:m(e.object,t);const o=m(e.property,t),i=e.computed?n.name+"["+o.name+"]":n.name+"."+o.name,r=n.format??"%s",s=o.format??"%s",a=e.computed?`${r}[${s}]`:`${r}.${s}`;return{name:i,sourcemap_location_hints:[...n.sourcemap_location_hints,...o.sourcemap_location_hints],format:a}}if(c.types.isOptionalCallExpression(e)||c.types.isCallExpression(e))return m(e.callee,t);if(c.types.isSequenceExpression(e))return m(e.expressions[e.expressions.length-1],t);if(c.types.isArrayExpression(e))return{name:"[]",sourcemap_location_hints:e.loc?[t(e.loc.start,"[]",e.loc.filename)]:[],format:"%s"};if(c.types.isObjectExpression(e))return{name:"{}",sourcemap_location_hints:e.loc?[t(e.loc.start,"{}",e.loc.filename)]:[],format:"%s"};if(c.types.isStringLiteral(e)){const n=e.loc?[t(e.loc.start,e.value,e.loc.filename)]:[];return{name:`"${n[0]?.name??e.value}"`,sourcemap_location_hints:n,format:'"%s"'}}throw new u.HudUnsupportedError("Unsupported left side of assignment - "+e.type+"loc - "+JSON.stringify(e.loc))}const y=new Set;function h(e,t){const{node:n}=e;if(e.isExpression())try{return function(e,t){const{parent:n}=e;if(c.types.isVariableDeclarator(n)&&c.types.isIdentifier(n.id))return f(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return f(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return f(n,n.key.name,t);if(c.types.isAssignmentExpression(n))return m(n.left,t);if(c.types.isAssignmentPattern(n))return m(n.left,t);throw new u.HudUnsupportedError(`Unsupported parent type - ${n.type} for me ${e.node.type}`)}(e,t)}catch(t){if(t instanceof u.HudUnsupportedError){const n=`${e.parentPath?.node.type}`;return void(y.has(n)||(d.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),y.add(n)))}throw t}d.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function g(e,t){const n=[];return e.arguments.forEach((e,o)=>{let i,r;if(c.types.isStringLiteral(e)?(i=l.ArgumentTypes.StringLiteral,r=e.value):c.types.isTemplateLiteral(e)?(i=l.ArgumentTypes.TemplateString,r=function(e){let t="";const n=e.quasis,o=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<o.length&&(t+=`\${${_(o[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(i=l.ArgumentTypes.Identifier,r=e.name),i&&r){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:o,type:i,value:a?.name??r,sourcemap_location_hint:a})}}),n}function _(e){if(c.types.isIdentifier(e))return e.name;if(c.types.isStringLiteral(e))return e.value;if(c.types.isCallExpression(e)||c.types.isOptionalCallExpression(e)){const t=e;if(c.types.isIdentifier(t.callee))return t.callee.name;if(c.types.isMemberExpression(t.callee)||c.types.isOptionalMemberExpression(t.callee)){let e="";const n=t.callee;if(c.types.isThisExpression(n.object)?e+="this.":c.types.isIdentifier(n.object)&&(e+=`${n.object.name}.`),""!==e&&c.types.isIdentifier(n.property))return e+=`${n.property.name}`,e}}return""}const b=new Set},9850:function(e,t,n){var o,i=this&&this.__createBinding||(Object.create?function(e,t,n,o){void 0===o&&(o=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,i)}:function(e,t,n,o){void 0===o&&(o=n),e[o]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=o(e),s=0;s<n.length;s++)"default"!==n[s]&&i(t,e,n[s]);return r(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fixSourceMap=I,t.getRealPositionNothingFunc=M,t.getRealPositionOffsetsFunc=F,t.getRealPositionSourceMapFunc=T,t.parseDeclarations=async function(e,t,n=null,o,i=!1){const{filename:r,bundlerBuildId:s,bundlerBuildIdGenerated:a,lineOffset:_,columnOffset:M,file_path_checksum:A,file_checksum:B,functionIds:L,sourceCodeHash:U,moduleBase:R,isNextJsApp:$,marksCount:H,prebundle_file_checksum:K}=e,W=K??B,G=o?N(o):void 0;g.worker_logger.debug("Parsing code",{filename:r});const J={declarations:[],blacklist:{file_path_checksum:A,file_checksum:W,uuids:L},generatedAsyncFunctions:[]};if([".ts",".mts",".cts",".tsx"].some(e=>r.endsWith(e))){if(!o)return g.worker_logger.error("ts file found but no ts-node config available",{filename:r}),J;const e=j(t,r,G);if(!e)return J;const n=D(e);if(n!==B)return g.worker_logger.warning("File checksum mismatch",{filename:r,file_path_checksum:A,compiledChecksum:n,file_checksum:B,functionIds:L,transpileOnly:o?.transpileOnly}),J;t=e}else{const e=D(t);if(e!==B){let n=!1;if(o?.allowJs){const e=j(t,r,G);if(!e)return J;D(e)===B&&(n=!0,t=e)}if(!n)return g.worker_logger.warning("File checksum mismatch",{filename:r,file_path_checksum:A,diskFileChecksum:e,file_checksum:B,functionIds:L,transpileOnly:o?.transpileOnly}),J}}let Q,V,z=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(function(e){return void 0!==e.lineOffset&&void 0!==e.columnOffset&&(0!==e.lineOffset||0!==e.columnOffset)}(e))z=F(_,M);else{const e=(0,v.getSourceMap)(r,t);try{null!==e&&(V=(0,b.default)(e).readUInt32BE(),f.hudConfig.userConfig.disableSourceMapsResolution?.value||(Q=JSON.parse(e),Q&&(z=T(await new u.SourceMapConsumer(I(Q))))))}catch(e){g.worker_logger.error("Failed to parse source map",{filename:r,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}g.worker_logger.debug("Parsing code",{filename:r});const Y=[],X=new w(t,R),Z=X.getRemainingMarksCount(),ee=await c.parseAsync(t,S);if(null===ee)return g.worker_logger.warning("Failed parsing code to tree",{filename:r,file_path_checksum:A,file_checksum:W,functionIds:L}),{declarations:[],blacklist:{file_path_checksum:A,file_checksum:W,uuids:L},generatedAsyncFunctions:[]};g.worker_logger.debug("Parsed code to tree",{filename:r});const te=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],ne=new Set,oe=[];g.worker_logger.debug("Traversing declarations",{filename:r}),n?.postMessage("eventlooptime"),c.traverse(ee,{AssignmentExpression:{enter(e){const t=function(e){try{const{node:t}=e,n=t.left;if("MemberExpression"!==n.type)return;const o=n.object;if("Identifier"!==o.type)return;if("globalThis"!==o.name)return;const i=n.property;if("Identifier"!==i.type)return;if(i.name!==f.hudConfig.esbuildFunctionIdVar)return;const r=t.right;if("StringLiteral"!==r.type)return;const s=r.value.split(":");if(2!==s.length)return;return{functionId:q(s[0]),functionHash:s[1]}}catch{return}}(e);t&&(oe[oe.length-1]=t)}},[x.NamespaceScopeAlias]:{enter(e){const{node:t}=e;if(!(0,x.isNamespaceScopeable)(t))return;const n=te[te.length-1],o=(0,C.getScope)(e,r,z);if(!o)return;const i=n.childrenCount[o.type]||0,s={...o,childrenCount:{},siblingIndex:i};n.childrenCount[o.type]=i+1,te.push(s),ne.add(t),e.isFunction()&&oe.push(null)},exit(e){const{node:n}=e;!function(){if(e.isFunction()){const n=oe.pop()??null,o=function(e,t,n,o,i,r,s,a){try{const l=(0,h.getInstrumentedThirdPartyModuleInfo)(n);let u;if(l){if(!function(e,t){const n=(0,p.getFunctionIdentifier)(e);if(!n)return!1;const o=n.name;return t.functions.includes(o)}(e,l))return;u=l.moduleName}if(!1===f.hudConfig.userConfig.instrumentOneLiners?.value&&function(e){const t=e.node;if("ArrowFunctionExpression"!==t.type)return!1;if(t.async||t.generator)return!1;if("BlockStatement"!==t.body.type)return!0;const n=t.body;return 1===n.body.length&&"ReturnStatement"===n.body[0].type}(e))return;const _=P(e);if(!_)throw new Error("Function node has no block start location");const v=e;if(void 0===e.node.start||null===e.node.start||void 0===e.node.end||null===e.node.end)throw new Error("Function node has no start or end location");let C=a?.functionId??null;const x=null===C;null===C&&(C=function(e,t,n,o){const i=o.slice(0,n),r=`${e}_${t}_${Buffer.byteLength(i,"utf8")}`;return d.v5(r,f.hudConfig.functionUuidNamespace).toString()}(t,n,_.start-(i-1),r));const S=a?.functionHash??(c=r.slice(e.node.start,e.node.end),(0,b.default)(c).readUInt32BE().toString());if(!S)return void g.worker_logger.warning("Function hash not found",{functionId:C,filename:n});const w=v.node.async||!1,I=v.node.loc?s(v.node.loc.start,void 0,n):void 0,M=v.node.loc?s(v.node.loc.end,void 0,n):void 0,F=I?.source??n,T=(0,O.getEntityType)(v),j=(0,p.getMethodKind)(v.node),D=(0,p.getContextualData)(v,s),A=(0,E.getParameterInfo)(v,s),{siblingIndex:N,childrenCount:q}=o[o.length-1],B=o.slice(0,-1),L=(0,p.getFunctionIdentifier)(v),U=L?L.loc?[s(L.loc.start,L.name,F)]:[]:v.node.loc?[s(v.node.loc.start,void 0,F)]:[],R=U[0]?.name??L?.name,$={name:R,sourcemap_location_hints:U,format:R?"%s":void 0};return $.name&&($.name=(0,k.getSymbolName)($)),{module:m.default.parse(F).name,symbol:$,context:D,file:F,type:T,format:y.Format.cjs,parameters:A,async:w,start_line:I?.line??-1,end_line:M?.line??-1,start_column:I?.column??-1,source_code_hash:S,runtime_function_id:C,scope_chain:B,methodKind:j,siblingIndex:N,childrenCount:q,third_party_module:u,original_location:{file:n,start_line:e.node.loc?.start?.line,end_line:e.node.loc?.end?.line,start_column:e.node.loc?.start?.column,end_column:e.node.loc?.end?.column},id_generated:x}}catch(e){g.worker_logger.error("Failed to handle function",{filename:n,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}var c}(e,U,r,te,R,t,z,n);if(!o)return;if(!$)return void Y.push(o);const i=P(e);if(!i)return;X.functionContainsMark(i.start,i.end)&&Y.push(o)}}(),ne.has(n)&&(te.pop(),ne.delete(n))}}}),g.worker_logger.debug("Traversed declarations",{filename:r}),$&&H!==Y.length&&g.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:r,marksCount:H,declarationsCount:Y.length,remainingMarks:X.getRemainingMarksCount(),initialMarkCount:Z});const{declarations:ie,blacklist:re,generatedAsyncFunctions:se}=function(e,t,n,o,i,r,s,a,c,l){t=t.map(q);const u=new Set(t),d=new Set(e.map(e=>e.runtime_function_id));let p=[];const f=[],m=[];e.forEach(e=>{u.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:o,has_input_map:void 0!==i,sourcemap_crc:r,file_path_checksum:s,file_checksum:a}):l&&e.id_generated?e.async&&m.push(e):f.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),f.length>0&&g.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t,missingInstrumentation:f});const y=new Set;u.forEach(e=>{d.has(e)||y.add(e)});const h=y.size>0;return h&&g.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...y]}),{declarations:p,blacklist:h?{file_path_checksum:s,file_checksum:a,uuids:[...y]}:void 0,generatedAsyncFunctions:m}}(Y,L,s,a,Q,V,A,W,r,i);return{declarations:ie,blacklist:re,generatedAsyncFunctions:se}},t.rawFunctionIdToUuidFunctionId=q;const c=s(n(6346)),l=n(8528),u=n(4634),d=s(n(3903)),p=n(9127),f=n(5809),m=a(n(6760)),y=n(8528),h=n(2546),g=n(523),_=n(1427),b=a(n(3176)),v=n(2784),O=n(5203),E=n(6864),C=n(1602),k=n(2535),x=n(9011),S={babelrc:!1,configFile:!1};class w{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=f.hudConfig.nextJsMarkVarName;let n=0,o=e.indexOf(t,n);for(;-1!==o;)this.markPositions.push(o),n=o+t.length,o=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,o=t-this.moduleBase;let i=!1,r=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=o){i=!0,r=e;break}}return i&&this.markPositions.splice(r,1),i}getRemainingMarksCount(){return this.markPositions.length}}function I(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function M(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function F(e,t){return(n,o,i)=>({name:o??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:i??void 0})}function T(e){return(t,n,o)=>{const i=e.originalPositionFor({line:t.line,column:t.column});return i?{name:i.name??n,line:i.line??-1,column:i.column??-1,source:i.source??o,resolved:!0,server:{name:n,line:t.line,column:t.column,source:o}}:{name:n??void 0,line:t.line,column:t.column,source:o??void 0,resolved:!1}}}function P(e){let t=e.node.body.loc?.start?.index;if(void 0===t)return null;"ArrowFunctionExpression"===e.node.type&&e.node.body.extra?.parenthesized&&e.node.body.extra?.parenStart&&Number.isInteger(e.node.body.extra.parenStart)&&(t=e.node.body.extra.parenStart);const n=e.node.end;return null==n?null:{start:t,end:n}}function j(e,t,n){try{return n.compile(e,t)}catch(e){return void g.worker_logger.warning("ts file pass, but failed to compile with ts-node",{filename:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}function D(e){return(0,b.default)(e).readUInt32BE()}let A;function N(e){if(!A){const t=(0,_.myRequire)("ts-node");A=t.create({...e,transpileOnly:!0,typeCheck:!1})}return A}function q(e){try{return d.stringify(Buffer.from(e+"==","base64"))}catch(t){throw g.worker_logger.error("Failed to convert raw function id to uuid function id",{rawFunctionId:e,error:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),t}}}},t={};return function n(o){var i=t[o];if(void 0!==i)return i.exports;var r=t[o]={exports:{}};return e[o].call(r.exports,r,r.exports,n),r.exports}(6066)})());
2
2
  //# sourceMappingURL=declarations.js.map
package/dist/cjs/dto.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(n||(t.HudSessionInitStatus=n={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(o(7789),t),r(o(8086),t),r(o(7935),t),r(o(6910),t),r(o(2176),t),r(o(9107),t),r(o(7022),t),r(o(6604),t),r(o(4909),t),r(o(878),t),r(o(8377),t),r(o(8054),t),r(o(6328),t),r(o(6413),t),r(o(6364),t),r(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const n=o(1569),r=o(7789);t.HudOptionsSchema=n.z.object({includeModules:n.z.array(n.z.string()).optional(),excludeDirs:n.z.array(n.z.string()).optional(),enableFrameworks:r.availableFrameworksSchema.optional(),maxMappedFunctions:n.z.number().optional(),minPodMemoryMB:n.z.number().optional(),maxFileSizeBytes:n.z.number().optional(),maxTimeUntilInitSessionMs:n.z.number().optional(),verbose:n.z.boolean().optional(),disableSourceMapsResolution:n.z.boolean().optional(),disableRuntimeInstrumentation:n.z.boolean().optional(),disableParametersExtraction:n.z.boolean().optional(),disableDetachedFunctions:n.z.boolean().optional(),customForensicsStorage:n.z.object({bucket:n.z.string(),region:n.z.string(),prefix:n.z.string().optional()}).optional(),customOptions:n.z.record(n.z.string(),n.z.string()).optional()}),t.HudSessionOptionsSchema=n.z.object({tags:n.z.record(n.z.string(),n.z.string()).optional()})},6413:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(n||(t.ArgumentTypes=n={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(r||(t.EntityType=r={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const n=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp",mongodb:"mongodb",mongoose:"mongoose",clickhouse:"clickhouse"},t.availableFrameworksSchema=n.z.union([n.z.map(n.z.nativeEnum(t.availableFrameworks),n.z.boolean()),n.z.record(n.z.nativeEnum(t.availableFrameworks),n.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,n,r,i,s){this.flow_id=e,this.methods=t,this.framework=n,this.partial_path=s,r||(r=""),this.path=o(r,i),this.partial_path=o(r,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Cleared=3]="Cleared"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql"}(n||(t.InvestigationType=n={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis",e.MONGO="mongo"}(r||(t.OutboundType=r={}))},9107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(3487)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(n||(t.HudSessionInitStatus=n={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(o(7789),t),r(o(8086),t),r(o(7935),t),r(o(6910),t),r(o(2176),t),r(o(9107),t),r(o(7022),t),r(o(6604),t),r(o(4909),t),r(o(878),t),r(o(8377),t),r(o(8054),t),r(o(6328),t),r(o(6413),t),r(o(6364),t),r(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const n=o(1569),r=o(7789);t.HudOptionsSchema=n.z.object({includeModules:n.z.array(n.z.string()).optional(),excludeDirs:n.z.array(n.z.string()).optional(),enableFrameworks:r.availableFrameworksSchema.optional(),maxMappedFunctions:n.z.number().optional(),minPodMemoryMB:n.z.number().optional(),maxFileSizeBytes:n.z.number().optional(),maxTimeUntilInitSessionMs:n.z.number().optional(),verbose:n.z.boolean().optional(),disableSourceMapsResolution:n.z.boolean().optional(),disableRuntimeInstrumentation:n.z.boolean().optional(),disableParametersExtraction:n.z.boolean().optional(),disableDetachedFunctions:n.z.boolean().optional(),customForensicsStorage:n.z.object({bucket:n.z.string(),region:n.z.string(),prefix:n.z.string().optional()}).optional(),customOptions:n.z.record(n.z.string(),n.z.string()).optional()}),t.HudSessionOptionsSchema=n.z.object({tags:n.z.record(n.z.string(),n.z.string()).optional()})},6413:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(n||(t.ArgumentTypes=n={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(r||(t.EntityType=r={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const n=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp",mongodb:"mongodb",mongoose:"mongoose",clickhouse:"clickhouse"},t.availableFrameworksSchema=n.z.union([n.z.map(n.z.nativeEnum(t.availableFrameworks),n.z.boolean()),n.z.record(n.z.nativeEnum(t.availableFrameworks),n.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,n,r,i,s){this.flow_id=e,this.methods=t,this.framework=n,this.partial_path=s,r||(r=""),this.path=o(r,i),this.partial_path=o(r,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Cleared=3]="Cleared"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql"}(n||(t.InvestigationType=n={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis",e.MONGO="mongo"}(r||(t.OutboundType=r={}))},9107:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndReason=void 0,function(e){e.ServerTimeout="http.server_timeout",e.ClientTimeout="http.client_timeout",e.ResponseAborted="http.response_aborted"}(o||(t.HttpEndReason=o={}))}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(3487)})());
2
2
  //# sourceMappingURL=dto.js.map