hud-sdk 1.6.37 → 1.6.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/api.js CHANGED
@@ -1 +1 @@
1
- module.exports = require("./dist/cjs/api.js");
1
+ module.exports = require("./dist/cjs/api.js");
@@ -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 r=Object.getOwnPropertyDescriptor(n,t);r&&!("get"in r?!n.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,r)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),r=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,r(t(2887),n),r(t(2570),n);var a=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return a.SDK_MODULE_NAME}}),r(t(7089),n);var s=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return s.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),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 s=r(n.dynamicConfig,a.data);return void 0!==s.enableInvestigation&&s.enableInvestigation!==n.dynamicConfig.enableInvestigation&&(t.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:s.enableInvestigation}),n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=s.enableInvestigation)),void 0!==s.enableInvestigationArgsSending&&s.enableInvestigationArgsSending!==n.dynamicConfig.enableInvestigationArgsSending&&(t.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:s.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=s.enableInvestigationArgsSending),s};const i=t(2887);function r(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],s=n[i];t[i]=r(a,s)}return t}},2887:function(e,n,t){var i,r=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var r=Object.getOwnPropertyDescriptor(n,t);r&&!("get"in r?!n.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,r)}: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}),s=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),s=0;s<t.length;s++)"default"!==t[s]&&r(n,e,t[s]);return a(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.hudConfig=n.HudDynamicConfigSchema=void 0,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=o.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)},n.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let n=__dirname,t=0;for(;"/"!==n&&t<10;){const e=`${n}/hud.config`;if(l.existsSync(e))return e;n=d.dirname(n),t++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(n){throw new v(e,n.code)}};const o=t(8528),l=s(t(9896)),d=s(t(6928)),u=t(1569),c="globalThis._hudMark";n.HudDynamicConfigSchema=u.z.object({aggregationInterval:u.z.number(),aggregationFirstSendTimeout:u.z.number(),investigationInterval:u.z.number(),investigationFirstSendTimeout:u.z.number(),enableInvestigation:u.z.boolean(),enableInvestigationArgsSending:u.z.boolean(),investigationRateLimits:u.z.object({maxSameInvestigations:u.z.number().int().positive(),sameInvestigationTimeWindowMs:u.z.number().int().positive(),maxTotalInvestigations:u.z.number().int().positive(),maxTotalInvestigationsErrorBased:u.z.number().int().positive(),maxTotalInvestigationsDurationBased:u.z.number().int().positive(),totalInvestigationTimeWindowMs:u.z.number().int().positive(),maxUniqLogs:u.z.number().int().positive()}),machineMetricsInterval:u.z.number().int().positive(),blacklistParams:u.z.array(u.z.string()),forensicsBlacklistFields:u.z.array(u.z.string()),forensicsWhitelistFields:u.z.array(u.z.string()),censorshipRegexes:u.z.array(u.z.object({regex:u.z.string(),replacement:u.z.string()})),reingestInterval:u.z.number().int().positive(),extraHeaders:u.z.array(u.z.string()),performanceMetricsInterval:u.z.number().int().positive()});const m=process.env.HUD_ENABLE_INVESTIGATION,g="_HUD",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"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.1",store:{type:"s3"},limits:{executionFlowMaxLength:100,exceptionMaxLength:100},maxStringLength:1024,maxArrayLength:100,maxObjectDepth:10},userConfig:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,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,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:"94a210f3-861c-4e18-ab27-6b6c19437c9d",wrapVarPrefix:g,functionIdVarName:`${g}_fid`,frameworksToPatch:new Map([["express",{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[d.join("express","lib","application.js"),{framework:o.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:o.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:o.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:o.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:o.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:o.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:o.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:o.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:o.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:o.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:o.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(d.sep),{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:o.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:o.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:o.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[d.join("serverless-http","lib","framework","get-framework.js"),{framework:o.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}]]),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"===m,enableInvestigationArgsSending:!0,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[]},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==m,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,functionsToInstrument:[{moduleName:"pg",fileToFunctionsMapping:{[d.join(d.sep,"pg","lib","client.js")]:["query","connect","end"]}},{moduleName:"axios",fileToFunctionsMapping:{[d.join(d.sep,"axios","dist","node","axios.cjs")]:["request"]}},{moduleName:"typeorm",fileToFunctionsMapping:{[d.join(d.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",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:c,nextJsMarkStatement:`${c} = "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;class v extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=v},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.6.37"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),r=i.z.object({type:i.z.literal("s3")}),a=i.z.object({type:i.z.literal("disk"),path:i.z.string()});n.ObjectStoreConfigSchema=i.z.union([r,a])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},n={};return function t(i){var r=n[i];if(void 0!==r)return r.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 r=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return r.SDK_MODULE_NAME}}),a(t(7089),n);var o=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return o.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateDynamicConfig=function(e,n,t){const r=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!r.success)return t.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:r,remoteConfig:e}),n.dynamicConfig;const o=a(n.dynamicConfig,r.data);return void 0!==o.enableInvestigation&&o.enableInvestigation!==n.dynamicConfig.enableInvestigation&&(t.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o.enableInvestigation}),n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o.enableInvestigation)),void 0!==o.enableInvestigationArgsSending&&o.enableInvestigationArgsSending!==n.dynamicConfig.enableInvestigationArgsSending&&(t.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:o.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=o.enableInvestigationArgsSending),o};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 r=e[i],o=n[i];t[i]=a(r,o)}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]}),r=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),o=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),o=0;o<t.length;o++)"default"!==t[o]&&a(n,e,t[o]);return r(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.hudConfig=n.HudDynamicConfigSchema=void 0,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;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)},n.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let n=__dirname,t=0;for(;"/"!==n&&t<10;){const e=`${n}/hud.config`;if(l.existsSync(e))return e;n=d.dirname(n),t++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(n){throw new f(e,n.code)}};const s=t(8528),l=o(t(9896)),d=o(t(6928)),u=t(3903),c=t(1569),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()}),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()});const g=process.env.HUD_ENABLE_INVESTIGATION,p="_HUD",v="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"},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"},limits:{executionFlowMaxLength:20,exceptionMaxLength:20},maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30},userConfig:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,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,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:v,wrapVarPrefix:p,functionIdVarName:`${p}_fid`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[d.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/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(d.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:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[d.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:"^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs"}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js"}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg"}]]),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:!0,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2},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},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:(0,u.v5)("axios",v),nodeFetchFunctionId:(0,u.v5)("node-fetch",v),nodeFetchBodiesFunctionIds:{json:(0,u.v5)("node-fetch-body-json",v),text:(0,u.v5)("node-fetch-body-text",v),arrayBuffer:(0,u.v5)("node-fetch-body-arrayBuffer",v),blob:(0,u.v5)("node-fetch-body-blob",v)},pgConnectFunctionId:(0,u.v5)("pg-connect",v),pgQueryFunctionId:(0,u.v5)("pg-query",v),pgEndFunctionId:(0,u.v5)("pg-end",v),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[d.join(d.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",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;class f extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=f},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.6.38"},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")}),r=i.z.object({type:i.z.literal("disk"),path:i.z.string()});n.ObjectStoreConfigSchema=i.z.union([a,r])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},n={};return function t(i){var a=n[i];if(void 0!==a)return a.exports;var r=n[i]={exports:{}};return e[i].call(r.exports,r,r.exports,t),r.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 r=t();for(var i in r)("object"==typeof exports?exports:e)[i]=r[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(r(523)),d=r(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}}},5119:function(e,t,r){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.init=void 0;const o=i(r(6281));t.init=o.default},5809:e=>{e.exports=require("./config")},5994:function(e,t,r){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 o=r(8167),n=r(2546),s=r(5809),a=r(8269),d=r(523),c=r(6281),g=i(r(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(n.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,r,i){this.apiKey=e,this.service=t,this.startTime=r,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof n.HudSessionThrottle?(d.customer_logger.log(n.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof n.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,n.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,c._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,n.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,n.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(n.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(o.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,n.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new n.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof n.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=n.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),r={...process.env};delete r.NODE_OPTIONS;const i=new o.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:r});let a;try{a=new g.default(i),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof n.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"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void o.app_logger.warning("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!o.app_logger.isValid()||!o.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,i.updateUserConfigFromInit)(e,t,r);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void o.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(o.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new n.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(o.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;o.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;o.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{o.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;const i=r(2546),o=r(523),n=r(5994),s=r(5809),a=r(8528),d=r(8269),c=r(2546),g=r(7274);let l,u=!1;function h(e=!0,t=!1,r=!1){(0,d.detachHud)(e,t),r&&(0,c.safeCall)(o.app_logger,(0,d.flushLogs)()),l&&(0,c.safeCall)(o.app_logger,l.terminateMessenger());const n=(0,d.getLambdaExtensionId)();n&&!u&&(u=!0,(0,c.safeCall)(o.app_logger,(0,i.nextLoopDummy)(n))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const r=(new Date).toISOString(),n=[];return Object.entries(hudCalls).map(([i,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const o={function_id:i,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:r,timeslice:e,exceptions:s(c.exceptions),count:c.count-c.lastSentCounter,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};n.push(o),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){o.app_logger.error("Failed preparing invocation, skipping",{func:i,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),n.length>0&&(0,i.clearMetricsIndicator)(),n},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const r in globalThis.hudCalls[e][t])n(globalThis.hudCalls[e][t][r])};const i=r(8269),o=r(523);function n(e){e.lastSentCounter-=e.count,e.count=0}function s(e){const t={};for(const r in e)t[r]=[{count:e[r]}];return t}},7320:function(e,t,r){var i,o=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),n=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||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=i(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return n(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(r(523)),d=s(r(6460)),c=r(5809),g=r(2546),l=r(8528),u=r(2546),h=r(7131),f=r(8269),p=r(2546),m=r(7274),v=r(2702),k=r(8269),w=r(2546),y=r(6281),C=r(2546),b=r(6261),_=a.app_logger,E=p.safeCall.bind(p.safeCall,_);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;constructor(e){this.worker=e,this.abortController=new AbortController,(0,b.setMaxListeners)(20,this.abortController.signal),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,c.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&_.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new p.HudClientUnauthorizedError).code&&a.customer_logger.log(p.UserErrorLogs.ApiKeyDenied(c.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,p.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(),c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,(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 r={msg:e,content:t};this.worker.postMessage(r)}async checkWorker(e){const t=["started"];let r;try{r=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof p.HudTimeoutError))throw i;r=await this.getMessageFromWorker(t,e/2,!1)}if(!r)throw new p.HudInitError("Worker not started");return r}async checkWorkerInitialized(e){let t;const r=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(r,e,!0)}catch(i){if(!(i instanceof p.HudTimeoutError))throw i;t=await this.getMessageFromWorker(r,e/10,!1)}if("throttled"===t?.msg)throw new p.HudSessionThrottle;if("networkError"===t?.msg)throw _.error("networkError",{error:t.content.error}),new p.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new p.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new p.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:_.info("Enabled mode"),E(this.getMode()),E(this.periodicGetEndpointsDurationsInvestigationThresholds()),E(this.startPeriodicTasks()),E(this.periodicSendMetrics()),E(this.highFrequencySendInvestigations()),E(this.periodicSendProcessedFiles()),E(this.periodicSendEndpoints()),E(this.periodicSendLazyEndpoints()),E(this.periodicSendKafkaJS()),E(this.periodicSendSqs()),E(this.periodicSendGraphQL()),E(this.sendStaticNextJsEndpointsOnce()),E(this.periodicSaveMachineMetrics()),E(this.periodicSendReingest()),E(this.resetCallerCounters()),E(this.periodicResetGlobalInvestigationCounter()),E(this.periodicResetInvestigationDedupingCache()),E(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),E(this.sendRuntime()),E(this.sendPatchedModules()),E(this.sendPreloadedModules()),E(this.dumpModulesAfterWhile(6e4)),E(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:_.info("Disabled mode"),E(this.getMode());break;case l.HudRunningMode.detached:_.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:_.error("Running mode not handled")}}async getMessageFromWorker(e,t,r=!1,i){let o;e=Array.isArray(e)?e:[e];const n=new AbortController,s=()=>{n.abort()};this.abortController.signal.addEventListener("abort",s);const a=d.setTimeout(t,void 0,{signal:n.signal,ref:r}),c=t=>{try{e.includes(t.msg)&&(o=t,n.abort(),_.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.worker.on("message",c).unref(),i&&this.worker.postMessage(i);try{throw await a,_.warning("Timeout waiting for message from worker"),new p.HudTimeoutError}catch(e){if(!(0,p.isAbortError)(e))throw(0,p.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",s),this.worker.off("message",c)}return o}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){_.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){_.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}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){_.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting caller",{interval:e}),(0,m.resetCallers)()}catch(e){_.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const r=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(r?.msg!==t||void 0===r?.content)throw new Error(`Unexpected message from worker: ${r}`);(0,f.setInvestigationDurationThresholds)(r?.content),_.debug("Endpoints durations investigation thresholds updated",{thresholds:r?.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();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let r=!0;await this.setupPeriodicTask(e,t,()=>{if(r){r=!1;try{this._updateTsNodeConfig()&&_.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,k.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.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=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.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(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,r=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,r,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 r=(0,m.prepCalls)(t,e);r.length>0&&this._sendArray("Invocations",r)}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 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,k.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 periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.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)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof p.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:r.c[r.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=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,p.collectThreadPerformance)(t,_,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(w.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){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,r,i){function o(e){let t=!0;try{t=r(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}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),o(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!o(t))return void _.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i})}else _.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting global investigation counter",{interval:e}),(0,k.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){_.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{_.info("Resetting investigation deduping cache",{interval:e}),(0,k.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){_.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,C.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 p.HudError&&(0,p.setFirstError)(e.code),(0,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let r=0;for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(r++,_.debug("Attempting to send static next.js endpoints",{attemptCount:r}),(0,k.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){_.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,k.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,k.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(r>t){_.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,k.isNextConfigExtracted)(),attemptCount:r});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function r(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,r),n.exports}return r.c=t,r(r.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 i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(i(523)),d=i(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,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(i(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,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const n=i(8167),o=i(2546),s=i(5809),a=i(8269),d=i(523),c=i(6281),g=r(i(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(o.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,i,r){this.apiKey=e,this.service=t,this.startTime=i,this.tags=r,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof o.HudSessionThrottle?(d.customer_logger.log(o.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof o.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,o.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,c._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,o.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,o.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(o.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(n.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,o.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new o.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof o.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=o.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),i={...process.env};delete i.NODE_OPTIONS;const r=new n.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:i});let a;try{a=new g.default(r),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof o.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{r.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,i){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void n.app_logger.warning("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!n.app_logger.isValid()||!n.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,r.updateUserConfigFromInit)(e,t,i);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void n.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(n.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new o.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(n.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;n.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;n.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{n.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,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const r=i(2546),n=i(523),o=i(5994),s=i(5809),a=i(8528),d=i(8269),c=i(2546),g=i(7274);let l,u=!1;function h(e=!0,t=!1,i=!1){(0,d.detachHud)(e,t),i&&(0,c.safeCall)(n.app_logger,f()),l&&(0,c.safeCall)(n.app_logger,l.terminateMessenger());const o=(0,d.getLambdaExtensionId)();o&&!u&&(u=!0,(0,c.safeCall)(n.app_logger,(0,r.nextLoopDummy)(o))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const r=(0,d.getSessionInfo)(),o=(0,d.getStoredApiKey)(),s=(0,d.getStoredService)();try{const a=e||o;if(!a||"string"!=typeof a)return;const d=t||s||"unknown",c=(0,n.getSavedLogs)();for(const e of c){const{HudClient:t}=i(4672),o=new t;r?(n.app_logger.info("Flushing logs with session",{size:e.length,sessionId:r.sessionId,service:d}),o.setSession(r),await o.logs(e)):(n.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await o.sessionslessLogs(e,a)),n.app_logger.info("Successfully flushed logs")}}catch(e){try{n.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==r})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const i=(new Date).toISOString(),o=[];return Object.entries(hudCalls).map(([r,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const n={function_id:r,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:i,timeslice:e,exceptions:s(c.exceptions),count:c.count-c.lastSentCounter,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};o.push(n),function(e){e.lastSentCounter=e.count,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){n.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),o.length>0&&(0,r.clearMetricsIndicator)(),o},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const i in globalThis.hudCalls[e][t])o(globalThis.hudCalls[e][t][i])};const r=i(8269),n=i(523);function o(e){e.lastSentCounter-=e.count,e.count=0}function s(e){const t={};for(const i in e)t[i]=[{count:e[i]}];return t}},7320:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=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||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(i(523)),d=s(i(6460)),c=i(5809),g=i(2546),l=i(8528),u=i(2546),h=i(7131),f=i(8269),m=i(2546),p=i(7274),v=i(2702),w=i(8269),k=i(2546),y=i(6281),b=i(8269),C=i(2546),_=i(6261),E=a.app_logger,T=m.safeCall.bind(m.safeCall,E);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new _.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,_.setMaxListeners)(20,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,E.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()&&E.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),E.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){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(),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),E.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const i={msg:e,content:t};this.worker.postMessage(i)}async checkWorker(e){const t=["started"];let i;try{i=await this.getMessageFromWorker(t,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;i=await this.getMessageFromWorker(t,e/2,!1)}if(!i)throw new m.HudInitError("Worker not started");return i}async checkWorkerInitialized(e){let t;const i=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(i,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;t=await this.getMessageFromWorker(i,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw E.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:E.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),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(c.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:E.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:E.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:E.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,i=!1,r){let n;e=Array.isArray(e)?e:[e];const o=this.consumeMessageFromQueue(e);if(o)return E.info("Found message in queue",{msg:o.msg}),o;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:s.signal,ref:i}),g=t=>{try{e.includes(t.msg)&&(n=t,s.abort(),this.consumeMessageFromQueue([t.msg]),E.info("Received message from worker (canceling timeout)",t))}catch(e){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),r&&this.worker.postMessage(r);try{throw await c,E.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 n}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){E.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){E.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}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){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 periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){E.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);(0,f.setInvestigationDurationThresholds)(i?.content),E.debug("Endpoints durations investigation thresholds updated",{thresholds:i?.content})}catch(e){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();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let i=!0;await this.setupPeriodicTask(e,t,()=>{if(i){i=!1;try{this._updateTsNodeConfig()&&E.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,w.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,i=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,i,t=>{try{this.refreshInvestigations()}catch(e){E.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const i=(0,p.prepCalls)(t,e);i.length>0&&this._sendArray("Invocations",i)}catch(e){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){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 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,b.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw E.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;E.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}E.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:i.c[i.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):E.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,E,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void E.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){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){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){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,i,r){function n(e){let t=!0;try{t=i(e)}catch(e){E.error("Failed in periodic task",{taskName:r,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}),n(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!n(t))return void E.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:r})}else E.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:r})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){E.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){E.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,C.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,E.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=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let i=0;for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(i++,E.debug("Attempting to send static next.js endpoints",{attemptCount:i}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){E.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(i>t){E.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:i});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,i),o.exports}return i.c=t,i(i.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 i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const o=(0,i.getEntityType)(e);if(o){const s=(0,i.getEntityIdentity)(e.node),a=(0,r.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:o,context:a,symbol:{name:l,sourcemap_location_hints:c,format:l?"%s":void 0},methodKind:(0,r.getMethodKind)(e.node)}}};const i=n(5203),r=n(9127)},2535: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.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const i=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==i.length?r.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:i}):t=o.default.format(e.format,...i):t=i.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const i=e.loc?.start,o=e.loc?.end;if(!i||!o)return r.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:i.line,column:i.column}),a=t({line:o.line,column:o.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(r.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:i,locEnd:o}),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 r=n(523),o=i(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")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return i.types.isFunctionDeclaration(t)?r.EntityType.FunctionDeclaration:i.types.isFunctionExpression(t)?r.EntityType.FunctionExpression:i.types.isArrowFunctionExpression(t)?r.EntityType.FunctionArrow:i.types.isObjectMethod(t)?r.EntityType.ObjectMethod:i.types.isStaticBlock(t)||i.types.isClassMethod(t)?r.EntityType.ClassMethod:i.types.isClassPrivateMethod(t)?r.EntityType.ClassPrivateMethod:i.types.isClassDeclaration(t)?r.EntityType.ClassDeclaration:i.types.isClassExpression(t)?r.EntityType.ClassExpression:i.types.isForInStatement(t)||i.types.isForOfStatement(t)||i.types.isForStatement(t)?r.EntityType.ForLoop:i.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(i.types.isFunctionDeclaration(t)||i.types.isFunctionExpression(t)||i.types.isArrowFunctionExpression(t)||i.types.isClassMethod(t)||i.types.isObjectMethod(t)||i.types.isClassPrivateMethod(t)))if(i.types.isIfStatement(t)){if("consequent"===e.parentKey)return r.EntityType.IfConsequent;if("alternate"===e.parentKey)return r.EntityType.IfAlternate;if("test"===e.parentKey)return r.EntityType.IfTest}else{if(i.types.isBlockStatement(t)||i.types.isProgram(t))return r.EntityType.Block;if(i.types.isTryStatement(t)){if("block"===e.parentKey)return r.EntityType.Try;if("finalizer"===e.parentKey)return r.EntityType.Finally}else{if(i.types.isCatchClause(t))return;if(i.types.isWhileStatement(t))return"test"===e.parentKey?r.EntityType.WhileTest:r.EntityType.Do;if(i.types.isDoWhileStatement(t))return"test"===e.parentKey?r.EntityType.WhileTest:r.EntityType.Do;if(!(i.types.isForStatement(t)||i.types.isForInStatement(t)||i.types.isForOfStatement(t)))return;if("test"===e.parentKey)return r.EntityType.ForTest;if("body"===e.parentKey)return r.EntityType.ForBlock}}}(e):i.types.isProgram(t)?r.EntityType.Program:i.types.isDoWhileStatement(t)?r.EntityType.DoWhile:i.types.isWhileStatement(t)?r.EntityType.While:i.types.isCatchClause(t)?r.EntityType.Catch:i.types.isObjectExpression(t)?r.EntityType.ObjectExpression:i.types.isWithStatement(t)?r.EntityType.With:i.types.isSwitchStatement(t)?r.EntityType.Switch:i.types.isSwitchCase(t)?r.EntityType.SwitchCase:i.types.isTryStatement(t)?r.EntityType.TryCatch:i.types.isIfStatement(t)?r.EntityType.If:r.EntityType.Other},t.getEntityIdentity=function(e){return i.types.isFunctionDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void o.worker_logger.info("Function declaration without an identifier"):i.types.isClassDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void o.worker_logger.info("Class declaration without an identifier"):i.types.isFunctionExpression(e)||i.types.isClassExpression(e)?i.types.isIdentifier(e.id)?e.id:void 0:i.types.isClassMethod(e)?i.types.isIdentifier(e.key)?e.key:void o.worker_logger.info("Class method without an identifier"):i.types.isObjectMethod(e)?i.types.isIdentifier(e.key)?e.key:void o.worker_logger.info("Object method without an identifier"):i.types.isClassPrivateMethod(e)?i.types.isIdentifier(e.key.id)?e.key.id:void o.worker_logger.info("Class private method without an identifier"):void 0};const i=n(6346),r=n(8528),o=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var i=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]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(9850),t),r(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864: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]}),o=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||(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),s=0;s<n.length;s++)"default"!==n[s]&&r(t,e,n[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getParameterInfo=function(e,t){return e.node.params.map(e=>{try{return p(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 p(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,i){const r=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:r,left:t,right:i}}(e,p(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 i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,elements:t}}(e,e.elements.map(e=>p(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 i=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:p(e.key,t);n.push(function(e,t,n,i){const r=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:r,key:n,value:i}}(e,t,i,p(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,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 i.types.isArrowFunctionExpression(e)||i.types.isBlockStatement(e)||i.types.isCatchClause(e)||i.types.isClassMethod(e)||i.types.isClassPrivateMethod(e)||i.types.isDeclareModule(e)||i.types.isDoExpression(e)||i.types.isDoWhileStatement(e)||i.types.isForInStatement(e)||i.types.isForOfStatement(e)||i.types.isForStatement(e)||i.types.isFunctionDeclaration(e)||i.types.isFunctionExpression(e)||i.types.isIfStatement(e)||i.types.isLabeledStatement(e)||i.types.isObjectMethod(e)||i.types.isProgram(e)||i.types.isStaticBlock(e)||i.types.isSwitchCase(e)||i.types.isTSModuleBlock(e)||i.types.isTryStatement(e)||i.types.isWhileStatement(e)||i.types.isWithStatement(e)||i.types.isClassDeclaration(e)||i.types.isClassExpression(e)||i.types.isObjectExpression(e)||i.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return i.types.isFunction(e)||i.types.isClass(e)||i.types.isObjectExpression(e)};const i=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 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]}),o=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||(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),s=0;s<n.length;s++)"default"!==n[s]&&r(t,e,n[s]);return o(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=g,t.getContextualData=function(e,t){let n,i;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[i,r]of n.node.arguments.entries())if(r===e.node){const r=n.node.callee;let o;try{o=m(r,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${r.type}-${e.node.type}`;v.has(n)||(p.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:r.type,nodeType:e.node.type}),v.add(n))}}const s=_(n.node,t);return{callee:{symbol:o,argsCount:n.node.arguments.length,args:s},index:i}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(i=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const r=g(e,t);return r&&(r.name=(0,f.getSymbolName)(r)),{symbol:r,callback:n,immediatelyInvoked:i}},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),p=n(523),d=n(9772),f=n(2535);function y(e,t,n){const i=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:i?.name??t,sourcemap_location_hints:i?[i]:[],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 i=m(e.property,t),r=e.computed?n.name+"["+i.name+"]":n.name+"."+i.name,o=n.format??"%s",s=i.format??"%s",a=e.computed?`${o}[${s}]`:`${o}.${s}`;return{name:r,sourcemap_location_hints:[...n.sourcemap_location_hints,...i.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(0,d.isHudAwaitSequence)(e)?m((0,d.getHudAwaitSequenceElement)(e),t):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 h=new Set;function g(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 y(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return y(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return y(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(h.has(n)||(p.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),h.add(n)))}throw t}p.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function _(e,t){const n=[];return e.arguments.forEach((e,i)=>{let r,o;if(c.types.isStringLiteral(e)?(r=l.ArgumentTypes.StringLiteral,o=e.value):c.types.isTemplateLiteral(e)?(r=l.ArgumentTypes.TemplateString,o=function(e){let t="";const n=e.quasis,i=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<i.length&&(t+=`\${${b(i[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(r=l.ArgumentTypes.Identifier,o=e.name),r&&o){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:i,type:r,value:a?.name??o,sourcemap_location_hint:a})}}),n}function b(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 v=new Set},9772:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHudAwaitSequence=function(e){if(e.expressions.length<2)return!1;const t=e.expressions[e.expressions.length-1];return!!i.types.isIdentifier(t)&&!!t.name.startsWith(r.hudConfig.wrapVarPrefix)},t.getHudAwaitSequenceElement=function(e){const t=e.expressions[0];if(!i.types.isAssignmentExpression(t))throw new o.HudUnsupportedError("Expected assignment expression");const{left:n,right:s}=t;if(!i.types.isIdentifier(n)||!n.name.startsWith(r.hudConfig.wrapVarPrefix))throw new o.HudUnsupportedError("Expected identifier starting with "+r.hudConfig.wrapVarPrefix);return s};const i=n(6346),r=n(5809),o=n(2546)},9850: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]}),o=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||(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),s=0;s<n.length;s++)"default"!==n[s]&&r(t,e,n[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fixSourceMap=O,t.getRealPositionNothingFunc=P,t.getRealPositionOffsetsFunc=M,t.getRealPositionSourceMapFunc=F,t.parseDeclarations=async function(e,t,n=null,i){const{filename:r,bundlerBuildId:o,bundlerBuildIdGenerated:s,lineOffset:a,columnOffset:P,file_path_checksum:j,file_checksum:D,functionIds:A,sourceCodeHash:B,moduleBase:N,isNextJsApp:q,marksCount:W}=e;if(h.worker_logger.debug("Parsing code",{filename:r}),i)try{if(!T){const e=(0,m.myRequire)("ts-node");T=e.create({...i,transpileOnly:!0,typeCheck:!1})}const e=function(e,t,n){try{return n.compile(e,t)}catch(e){return void h.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,T);if(!e)return{declarations:[],blacklist:{file_path_checksum:j,file_checksum:D,uuids:A}};t=e}catch(e){return h.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:j,file_checksum:D,uuids:A}}}else if(r.endsWith(".ts")||r.endsWith(".mts"))return h.worker_logger.error("ts file pass, but not found ts-options"),{declarations:[],blacklist:{file_path_checksum:j,file_checksum:D,uuids:A}};const $=(0,g.default)(t).readUInt32BE();if($!==D)return h.worker_logger.warning("File checksum mismatch",{filename:r,file_path_checksum:j,diskFileChecksum:$,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:j,file_checksum:D,uuids:A}};let L,U,K=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(a&&P)K=M(a,P);else{const e=(0,_.getSourceMap)(r,t);try{null!==e&&(U=(0,g.default)(e).readUInt32BE(),d.hudConfig.userConfig.disableSourceMapsResolution?.value||(L=JSON.parse(e),L&&(K=F(await new u.SourceMapConsumer(O(L))))))}catch(e){h.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})}}h.worker_logger.debug("Parsing code",{filename:r});const H=[],R=new C(t,N),J=R.getRemainingMarksCount(),V=await c.parseAsync(t,S);if(null===V)return h.worker_logger.warning("Failed parsing code to tree",{filename:r,file_path_checksum:j,diskFileChecksum:$,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:j,file_checksum:D,uuids:A}};h.worker_logger.debug("Parsed code to tree",{filename:r});const z=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],G=new Set,Q=new Map;h.worker_logger.debug("Traversing declarations",{filename:r}),n?.postMessage("eventlooptime"),c.traverse(V,{[x.NamespaceScopeAlias]:{enter(e){const{node:n}=e;if(!(0,x.isNamespaceScopeable)(n))return;const i=z[z.length-1],o=(0,E.getScope)(e,r,K);if(!o)return;const s=i.childrenCount[o.type]||0,a={...o,childrenCount:{},siblingIndex:s};if(i.childrenCount[o.type]=s+1,z.push(a),G.add(n),e.isFunction()){const i=function(e,t,n,i,r,o,s){try{const c=(0,m.getInstrumentedThirdPartyModuleInfo)(n);let l;if(c){if(!function(e,t){const n=(0,p.getFunctionIdentifier)(e);if(!n)return!1;const i=n.name;return t.functions.includes(i)}(e,c))return;l=c.moduleName}const u=I(e);if(!u)throw new Error("Function node has no block start location");const _=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");const E=function(e,t,n,i){const r=i.slice(0,n),o=`${e}_${t}_${Buffer.byteLength(r,"utf8")}`;return(0,b.v5)(o,d.hudConfig.functionUuidNamespace).toString()}(t,n,u.start-(r-1),o),x=(a=o.slice(e.node.start,e.node.end),(0,g.default)(a).readUInt32BE().toString());if(!x)return void h.worker_logger.warning("Function hash not found",{functionID:E,filename:n});const S=_.node.async||!1,C=_.node.loc?s(_.node.loc.start,void 0,n):void 0,O=_.node.loc?s(_.node.loc.end,void 0,n):void 0,P=C?.source??n,M=(0,v.getEntityType)(_),F=(0,p.getMethodKind)(_.node),T=(0,p.getContextualData)(_,s),j=(0,k.getParameterInfo)(_,s),{siblingIndex:D,childrenCount:A}=i[i.length-1],B=i.slice(0,-1),N=(0,p.getFunctionIdentifier)(_),q=N?N.loc?[s(N.loc.start,N.name,P)]:[]:_.node.loc?[s(_.node.loc.start,void 0,P)]:[],W=q[0]?.name??N?.name,$={name:W,sourcemap_location_hints:q,format:W?"%s":void 0};return $.name&&($.name=(0,w.getSymbolName)($)),{module:f.default.parse(P).name,symbol:$,context:T,file:P,type:M,format:y.Format.cjs,parameters:j,async:S,start_line:C?.line??-1,end_line:O?.line??-1,start_column:C?.column??-1,source_code_hash:x,runtime_function_id:E,scope_chain:B,methodKind:F,siblingIndex:D,childrenCount:A,third_party_module:l,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}}}catch(e){h.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 a}(e,B,r,z,N,t,K);i&&(q?Q.set(n,i):H.push(i))}},exit(e){const{node:t}=e;if(q&&e.isFunction()&&Q.has(t)){const n=Q.get(t),i=I(e);i&&R.functionContainsMark(i.start,i.end)&&H.push(n),Q.delete(t)}G.has(t)&&(z.pop(),G.delete(t))}}}),h.worker_logger.debug("Traversed declarations",{filename:r}),q&&W!==H.length&&h.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:r,marksCount:W,declarationsCount:H.length,remainingMarks:R.getRemainingMarksCount(),initialMarkCount:J});const{declarations:X,blacklist:Y}=function(e,t,n,i,r,o,s,a,c){const l=new Set(t),u=new Set(e.map(e=>e.runtime_function_id));let p=[];const d=[];e.forEach(e=>{l.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:i,has_input_map:void 0!==r,sourcemap_crc:o,file_path_checksum:s,file_checksum:a}):d.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),d.length>0&&h.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t});const f=new Set;l.forEach(e=>{u.has(e)||f.add(e)});const y=f.size>0;return y&&h.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...f]}),{declarations:p,blacklist:y?{file_path_checksum:s,file_checksum:a,uuids:[...f]}:void 0}}(H,A,o,s,L,U,j,D,r);return{declarations:X,blacklist:Y}};const c=s(n(6346)),l=n(8528),u=n(4634),p=n(9127),d=n(5809),f=a(n(6760)),y=n(8528),m=n(2546),h=n(523),g=a(n(3176)),_=n(2784),b=n(3903),v=n(5203),k=n(6864),E=n(1602),w=n(2535),x=n(9011),S={babelrc:!1,configFile:!1};class C{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=d.hudConfig.nextJsMarkVarName;let n=0,i=e.indexOf(t,n);for(;-1!==i;)this.markPositions.push(i),n=i+t.length,i=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,i=t-this.moduleBase;let r=!1,o=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=i){r=!0,o=e;break}}return r&&this.markPositions.splice(o,1),r}getRemainingMarksCount(){return this.markPositions.length}}function O(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function P(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function M(e,t){return(n,i,r)=>({name:i??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:r??void 0})}function F(e){return(t,n,i)=>{const r=e.originalPositionFor({line:t.line,column:t.column});return r?{name:r.name??n,line:r.line??-1,column:r.column??-1,source:r.source??i,resolved:!0,server:{name:n,line:t.line,column:t.column,source:i}}:{name:n??void 0,line:t.line,column:t.column,source:i??void 0,resolved:!1}}}function I(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 T}},t={};return function n(i){var r=t[i];if(void 0!==r)return r.exports;var o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.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 i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1145:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createOutboundDeclarations=void 0,t.createAxiosDeclaration=r,t.createNodeFetchDeclaration=s,t.createPgDeclaration=a;const i=n(5809),o=n(8528);function r(){return[c("axios","Axios","request",i.hudConfig.axiosFunctionId)]}function s(){return[c("node-fetch","node-fetch","fetch",i.hudConfig.nodeFetchFunctionId),...Object.entries(i.hudConfig.nodeFetchBodiesFunctionIds).map(([e,t])=>c("node-fetch","node-fetch",e,t))]}function a(){return[c("pg","Client","connect",i.hudConfig.pgConnectFunctionId),c("pg","Client","query",i.hudConfig.pgQueryFunctionId),c("pg","Client","end",i.hudConfig.pgEndFunctionId)]}function c(e,t,n,i){return{module:e,third_party_module:e,file:`${e}.js`,format:"commonjs",async:!0,runtime_function_id:i,type:o.EntityType.ClassMethod,methodKind:"method",symbol:{sourcemap_location_hints:[{name:n,line:0,column:0,source:`${e}.js`}],name:n,format:"%s"},scope_chain:[{type:o.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0},{type:o.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:r,"node-fetch":s,pg:a}},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const r=(0,i.getEntityType)(e);if(r){const s=(0,i.getEntityIdentity)(e.node),a=(0,o.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,o.getMethodKind)(e.node)}}};const i=n(5203),o=n(9127)},2535: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.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const i=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==i.length?o.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:i}):t=r.default.format(e.format,...i):t=i.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const i=e.loc?.start,r=e.loc?.end;if(!i||!r)return o.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:i.line,column:i.column}),a=t({line:r.line,column:r.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(o.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:i,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 o=n(523),r=i(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")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return i.types.isFunctionDeclaration(t)?o.EntityType.FunctionDeclaration:i.types.isFunctionExpression(t)?o.EntityType.FunctionExpression:i.types.isArrowFunctionExpression(t)?o.EntityType.FunctionArrow:i.types.isObjectMethod(t)?o.EntityType.ObjectMethod:i.types.isStaticBlock(t)||i.types.isClassMethod(t)?o.EntityType.ClassMethod:i.types.isClassPrivateMethod(t)?o.EntityType.ClassPrivateMethod:i.types.isClassDeclaration(t)?o.EntityType.ClassDeclaration:i.types.isClassExpression(t)?o.EntityType.ClassExpression:i.types.isForInStatement(t)||i.types.isForOfStatement(t)||i.types.isForStatement(t)?o.EntityType.ForLoop:i.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(i.types.isFunctionDeclaration(t)||i.types.isFunctionExpression(t)||i.types.isArrowFunctionExpression(t)||i.types.isClassMethod(t)||i.types.isObjectMethod(t)||i.types.isClassPrivateMethod(t)))if(i.types.isIfStatement(t)){if("consequent"===e.parentKey)return o.EntityType.IfConsequent;if("alternate"===e.parentKey)return o.EntityType.IfAlternate;if("test"===e.parentKey)return o.EntityType.IfTest}else{if(i.types.isBlockStatement(t)||i.types.isProgram(t))return o.EntityType.Block;if(i.types.isTryStatement(t)){if("block"===e.parentKey)return o.EntityType.Try;if("finalizer"===e.parentKey)return o.EntityType.Finally}else{if(i.types.isCatchClause(t))return;if(i.types.isWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(i.types.isDoWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(!(i.types.isForStatement(t)||i.types.isForInStatement(t)||i.types.isForOfStatement(t)))return;if("test"===e.parentKey)return o.EntityType.ForTest;if("body"===e.parentKey)return o.EntityType.ForBlock}}}(e):i.types.isProgram(t)?o.EntityType.Program:i.types.isDoWhileStatement(t)?o.EntityType.DoWhile:i.types.isWhileStatement(t)?o.EntityType.While:i.types.isCatchClause(t)?o.EntityType.Catch:i.types.isObjectExpression(t)?o.EntityType.ObjectExpression:i.types.isWithStatement(t)?o.EntityType.With:i.types.isSwitchStatement(t)?o.EntityType.Switch:i.types.isSwitchCase(t)?o.EntityType.SwitchCase:i.types.isTryStatement(t)?o.EntityType.TryCatch:i.types.isIfStatement(t)?o.EntityType.If:o.EntityType.Other},t.getEntityIdentity=function(e){return i.types.isFunctionDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Function declaration without an identifier"):i.types.isClassDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Class declaration without an identifier"):i.types.isFunctionExpression(e)||i.types.isClassExpression(e)?i.types.isIdentifier(e.id)?e.id:void 0:i.types.isClassMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Class method without an identifier"):i.types.isObjectMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Object method without an identifier"):i.types.isClassPrivateMethod(e)?i.types.isIdentifier(e.key.id)?e.key.id:void r.worker_logger.info("Class private method without an identifier"):void 0};const i=n(6346),o=n(8528),r=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(9850),t),o(n(1145),t),o(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}: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}),s=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),s=0;s<n.length;s++)"default"!==n[s]&&o(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 p(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 p(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,i){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,left:t,right:i}}(e,p(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 i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,elements:t}}(e,e.elements.map(e=>p(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 i=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:p(e.key,t);n.push(function(e,t,n,i){const o=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,key:n,value:i}}(e,t,i,p(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,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 i.types.isArrowFunctionExpression(e)||i.types.isBlockStatement(e)||i.types.isCatchClause(e)||i.types.isClassMethod(e)||i.types.isClassPrivateMethod(e)||i.types.isDeclareModule(e)||i.types.isDoExpression(e)||i.types.isDoWhileStatement(e)||i.types.isForInStatement(e)||i.types.isForOfStatement(e)||i.types.isForStatement(e)||i.types.isFunctionDeclaration(e)||i.types.isFunctionExpression(e)||i.types.isIfStatement(e)||i.types.isLabeledStatement(e)||i.types.isObjectMethod(e)||i.types.isProgram(e)||i.types.isStaticBlock(e)||i.types.isSwitchCase(e)||i.types.isTSModuleBlock(e)||i.types.isTryStatement(e)||i.types.isWhileStatement(e)||i.types.isWithStatement(e)||i.types.isClassDeclaration(e)||i.types.isClassExpression(e)||i.types.isObjectExpression(e)||i.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return i.types.isFunction(e)||i.types.isClass(e)||i.types.isObjectExpression(e)};const i=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 i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}: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}),s=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),s=0;s<n.length;s++)"default"!==n[s]&&o(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=g,t.getContextualData=function(e,t){let n,i;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[i,o]of n.node.arguments.entries())if(o===e.node){const o=n.node.callee;let r;try{r=y(o,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${o.type}-${e.node.type}`;v.has(n)||(p.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:o.type,nodeType:e.node.type}),v.add(n))}}const s=_(n.node,t);return{callee:{symbol:r,argsCount:n.node.arguments.length,args:s},index:i}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(i=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const o=g(e,t);return o&&(o.name=(0,f.getSymbolName)(o)),{symbol:o,callback:n,immediatelyInvoked:i}},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),p=n(523),d=n(9772),f=n(2535);function m(e,t,n){const i=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:i?.name??t,sourcemap_location_hints:i?[i]:[],format:"%s"}}function y(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)]:[]}:y(e.object,t);const i=y(e.property,t),o=e.computed?n.name+"["+i.name+"]":n.name+"."+i.name,r=n.format??"%s",s=i.format??"%s",a=e.computed?`${r}[${s}]`:`${r}.${s}`;return{name:o,sourcemap_location_hints:[...n.sourcemap_location_hints,...i.sourcemap_location_hints],format:a}}if(c.types.isOptionalCallExpression(e)||c.types.isCallExpression(e))return y(e.callee,t);if(c.types.isSequenceExpression(e))return(0,d.isHudAwaitSequence)(e)?y((0,d.getHudAwaitSequenceElement)(e),t):y(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 h=new Set;function g(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 m(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isAssignmentExpression(n))return y(n.left,t);if(c.types.isAssignmentPattern(n))return y(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(h.has(n)||(p.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),h.add(n)))}throw t}p.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function _(e,t){const n=[];return e.arguments.forEach((e,i)=>{let o,r;if(c.types.isStringLiteral(e)?(o=l.ArgumentTypes.StringLiteral,r=e.value):c.types.isTemplateLiteral(e)?(o=l.ArgumentTypes.TemplateString,r=function(e){let t="";const n=e.quasis,i=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<i.length&&(t+=`\${${b(i[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(o=l.ArgumentTypes.Identifier,r=e.name),o&&r){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:i,type:o,value:a?.name??r,sourcemap_location_hint:a})}}),n}function b(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 v=new Set},9772:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHudAwaitSequence=function(e){if(e.expressions.length<2)return!1;const t=e.expressions[e.expressions.length-1];return!!i.types.isIdentifier(t)&&!!t.name.startsWith(o.hudConfig.wrapVarPrefix)},t.getHudAwaitSequenceElement=function(e){const t=e.expressions[0];if(!i.types.isAssignmentExpression(t))throw new r.HudUnsupportedError("Expected assignment expression");const{left:n,right:s}=t;if(!i.types.isIdentifier(n)||!n.name.startsWith(o.hudConfig.wrapVarPrefix))throw new r.HudUnsupportedError("Expected identifier starting with "+o.hudConfig.wrapVarPrefix);return s};const i=n(6346),o=n(5809),r=n(2546)},9850:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}: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}),s=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),s=0;s<n.length;s++)"default"!==n[s]&&o(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=O,t.getRealPositionNothingFunc=P,t.getRealPositionOffsetsFunc=M,t.getRealPositionSourceMapFunc=F,t.parseDeclarations=async function(e,t,n=null,i){const{filename:o,bundlerBuildId:r,bundlerBuildIdGenerated:s,lineOffset:a,columnOffset:P,file_path_checksum:T,file_checksum:D,functionIds:A,sourceCodeHash:B,moduleBase:N,isNextJsApp:q,marksCount:$}=e;if(h.worker_logger.debug("Parsing code",{filename:o}),i)try{if(!j){const e=(0,y.myRequire)("ts-node");j=e.create({...i,transpileOnly:!0,typeCheck:!1})}const e=function(e,t,n){try{return n.compile(e,t)}catch(e){return void h.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,o,j);if(!e)return{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};t=e}catch(e){return h.worker_logger.error("Failed to require and compile ts file",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}}}else if(o.endsWith(".ts")||o.endsWith(".mts"))return h.worker_logger.error("ts file pass, but not found ts-options"),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};const W=(0,g.default)(t).readUInt32BE();if(W!==D)return h.worker_logger.warning("File checksum mismatch",{filename:o,file_path_checksum:T,diskFileChecksum:W,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};let L,U,K=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(a&&P)K=M(a,P);else{const e=(0,_.getSourceMap)(o,t);try{null!==e&&(U=(0,g.default)(e).readUInt32BE(),d.hudConfig.userConfig.disableSourceMapsResolution?.value||(L=JSON.parse(e),L&&(K=F(await new u.SourceMapConsumer(O(L))))))}catch(e){h.worker_logger.error("Failed to parse source map",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}h.worker_logger.debug("Parsing code",{filename:o});const H=[],R=new S(t,N),J=R.getRemainingMarksCount(),V=await c.parseAsync(t,C);if(null===V)return h.worker_logger.warning("Failed parsing code to tree",{filename:o,file_path_checksum:T,diskFileChecksum:W,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};h.worker_logger.debug("Parsed code to tree",{filename:o});const z=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],G=new Set,Q=new Map;h.worker_logger.debug("Traversing declarations",{filename:o}),n?.postMessage("eventlooptime"),c.traverse(V,{[w.NamespaceScopeAlias]:{enter(e){const{node:n}=e;if(!(0,w.isNamespaceScopeable)(n))return;const i=z[z.length-1],r=(0,x.getScope)(e,o,K);if(!r)return;const s=i.childrenCount[r.type]||0,a={...r,childrenCount:{},siblingIndex:s};if(i.childrenCount[r.type]=s+1,z.push(a),G.add(n),e.isFunction()){const i=function(e,t,n,i,o,r,s){try{const c=(0,y.getInstrumentedThirdPartyModuleInfo)(n);let l;if(c){if(!function(e,t){const n=(0,p.getFunctionIdentifier)(e);if(!n)return!1;const i=n.name;return t.functions.includes(i)}(e,c))return;l=c.moduleName}const u=I(e);if(!u)throw new Error("Function node has no block start location");const _=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");const x=function(e,t,n,i){const o=i.slice(0,n),r=`${e}_${t}_${Buffer.byteLength(o,"utf8")}`;return(0,b.v5)(r,d.hudConfig.functionUuidNamespace).toString()}(t,n,u.start-(o-1),r),w=(a=r.slice(e.node.start,e.node.end),(0,g.default)(a).readUInt32BE().toString());if(!w)return void h.worker_logger.warning("Function hash not found",{functionID:x,filename:n});const C=_.node.async||!1,S=_.node.loc?s(_.node.loc.start,void 0,n):void 0,O=_.node.loc?s(_.node.loc.end,void 0,n):void 0,P=S?.source??n,M=(0,v.getEntityType)(_),F=(0,p.getMethodKind)(_.node),j=(0,p.getContextualData)(_,s),T=(0,k.getParameterInfo)(_,s),{siblingIndex:D,childrenCount:A}=i[i.length-1],B=i.slice(0,-1),N=(0,p.getFunctionIdentifier)(_),q=N?N.loc?[s(N.loc.start,N.name,P)]:[]:_.node.loc?[s(_.node.loc.start,void 0,P)]:[],$=q[0]?.name??N?.name,W={name:$,sourcemap_location_hints:q,format:$?"%s":void 0};return W.name&&(W.name=(0,E.getSymbolName)(W)),{module:f.default.parse(P).name,symbol:W,context:j,file:P,type:M,format:m.Format.cjs,parameters:T,async:C,start_line:S?.line??-1,end_line:O?.line??-1,start_column:S?.column??-1,source_code_hash:w,runtime_function_id:x,scope_chain:B,methodKind:F,siblingIndex:D,childrenCount:A,third_party_module:l,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}}}catch(e){h.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 a}(e,B,o,z,N,t,K);i&&(q?Q.set(n,i):H.push(i))}},exit(e){const{node:t}=e;if(q&&e.isFunction()&&Q.has(t)){const n=Q.get(t),i=I(e);i&&R.functionContainsMark(i.start,i.end)&&H.push(n),Q.delete(t)}G.has(t)&&(z.pop(),G.delete(t))}}}),h.worker_logger.debug("Traversed declarations",{filename:o}),q&&$!==H.length&&h.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:o,marksCount:$,declarationsCount:H.length,remainingMarks:R.getRemainingMarksCount(),initialMarkCount:J});const{declarations:X,blacklist:Y}=function(e,t,n,i,o,r,s,a,c){const l=new Set(t),u=new Set(e.map(e=>e.runtime_function_id));let p=[];const d=[];e.forEach(e=>{l.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:i,has_input_map:void 0!==o,sourcemap_crc:r,file_path_checksum:s,file_checksum:a}):d.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),d.length>0&&h.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t});const f=new Set;l.forEach(e=>{u.has(e)||f.add(e)});const m=f.size>0;return m&&h.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...f]}),{declarations:p,blacklist:m?{file_path_checksum:s,file_checksum:a,uuids:[...f]}:void 0}}(H,A,r,s,L,U,T,D,o);return{declarations:X,blacklist:Y}};const c=s(n(6346)),l=n(8528),u=n(4634),p=n(9127),d=n(5809),f=a(n(6760)),m=n(8528),y=n(2546),h=n(523),g=a(n(3176)),_=n(2784),b=n(3903),v=n(5203),k=n(6864),x=n(1602),E=n(2535),w=n(9011),C={babelrc:!1,configFile:!1};class S{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=d.hudConfig.nextJsMarkVarName;let n=0,i=e.indexOf(t,n);for(;-1!==i;)this.markPositions.push(i),n=i+t.length,i=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,i=t-this.moduleBase;let o=!1,r=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=i){o=!0,r=e;break}}return o&&this.markPositions.splice(r,1),o}getRemainingMarksCount(){return this.markPositions.length}}function O(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function P(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function M(e,t){return(n,i,o)=>({name:i??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:o??void 0})}function F(e){return(t,n,i)=>{const o=e.originalPositionFor({line:t.line,column:t.column});return o?{name:o.name??n,line:o.line??-1,column:o.column??-1,source:o.source??i,resolved:!0,server:{name:n,line:t.line,column:t.column,source:i}}:{name:n??void 0,line:t.line,column:t.column,source:i??void 0,resolved:!1}}}function I(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}},t={};return function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].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 r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,r;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"}(r||(t.HudSessionInitStatus=r={}))},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 r=this&&this.__createBinding||(Object.create?function(e,t,o,r){void 0===r&&(r=o);var n=Object.getOwnPropertyDescriptor(t,o);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,n)}:function(e,t,o,r){void 0===r&&(r=o),e[r]=t[o]}),n=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||r(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),n(o(7789),t),n(o(7935),t),n(o(6910),t),n(o(2176),t),n(o(9107),t),n(o(7022),t),n(o(6604),t),n(o(4909),t),n(o(878),t),n(o(8377),t),n(o(8054),t),n(o(6328),t),n(o(6413),t),n(o(6364),t),n(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 r=o(1569),n=o(7789);t.HudOptionsSchema=r.z.object({includeModules:r.z.array(r.z.string()).optional(),enableFrameworks:n.availableFrameworksSchema.optional(),maxMappedFunctions:r.z.number().optional(),minPodMemoryMB:r.z.number().optional(),maxFileSizeBytes:r.z.number().optional(),maxTimeUntilInitSessionMs:r.z.number().optional(),verbose:r.z.boolean().optional(),disableSourceMapsResolution:r.z.boolean().optional(),disableRuntimeInstrumentation:r.z.boolean().optional(),disableParametersExtraction:r.z.boolean().optional(),customOptions:r.z.record(r.z.string(),r.z.string()).optional()}),t.HudSessionOptionsSchema=r.z.object({tags:r.z.record(r.z.string(),r.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,r,n;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"}(r||(t.ArgumentTypes=r={})),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"}(n||(t.EntityType=n={}))},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.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 r=o(1569);t.availableFrameworks={express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp"},t.availableFrameworksSchema=r.z.union([r.z.map(r.z.nativeEnum(t.availableFrameworks),r.z.boolean()),r.z.record(r.z.nativeEnum(t.availableFrameworks),r.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,r,n,a,i){this.flow_id=e,this.methods=t,this.framework=r,this.partial_path=i,n||(n=""),this.path=o(n,a),this.partial_path=o(n,i)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,r;Object.defineProperty(t,"__esModule",{value:!0}),t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql"}(r||(t.InvestigationType=r={}))},9107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})}},t={};return function o(r){var n=t[r];if(void 0!==n)return n.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,o),a.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(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(),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(),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.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",nodeFetch:"nodeFetch",express:"express",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp"},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,a,i){this.flow_id=e,this.methods=t,this.framework=n,this.partial_path=i,r||(r=""),this.path=o(r,a),this.partial_path=o(r,i)}}},8054:(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"}(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"}(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 a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,o),a.exports}(3487)})());
2
2
  //# sourceMappingURL=dto.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 r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=async function(e,t,r,o=!1){const n=[],i=[];return await Promise.all(Array.from({length:t},async function(){for(;e.length>0;){const t=e.shift();try{const e=await r(t);n.push(e)}catch(e){if(i.push(e),o)throw e}}})),{results:n,errors:i}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=async function(e,t,r,o=3){for(let n=0;n<o;n++)try{return await u.default.post(e,t,r)}catch(t){if(t instanceof u.AxiosError&&401===t.response?.status)throw new s.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,l.logToHud)(`Failed request to ${e}, attempt ${n+1} of ${o}. Error: ${t}`),await new Promise(e=>setTimeout(e,1))}throw new s.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)};const s=r(2546),u=a(r(8938)),l=r(5231)},3903:e=>{e.exports=require("uuid")},4414:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadSourceMap=h,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,f.logToHud)("Skipping source map upload due to env var");else{(0,f.logToHud)(`Uploading source maps for ${e.length} files`);try{const r=[];for(const{buildId:o,filepath:n}of e){const e=`${n}.map`;try{await c.promises.access(e,c.constants.F_OK),r.push({buildId:o,filePath:e,hudKey:t})}catch{(0,f.logToHud)(`No source map found for file: ${n}`)}}await(0,p.limitedParallel)(r,10,h,!0),(0,f.logToHud)("Finished uploading source maps")}catch{return(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,f.setDontSendLogs)()}}};const u=r(5809),l=r(2546),d=s(r(2305)),c=a(r(9896)),f=r(5231),p=r(870),g=r(3066);async function h(e){const{buildId:t,filePath:r,hudKey:o}=e,n=new d.default;n.append("build_id",t),n.append("token",o);try{const e=await c.promises.readFile(r,"utf8"),t=JSON.parse(e);delete t.sourcesContent,n.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,f.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,g.requestRelentless)(`${u.hudConfig.sink.url}/${u.hudConfig.endpoints.sourceMap}`,n,{headers:{"Content-Type":"multipart/form-data"},timeout:u.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,f.logToHud)(`failed uploading source map. File: ${r}, Error: ${e}`),(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemap(r))}}},5231:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logToUser=function(e){let t="";t="string"==typeof e?(0,n.formatLogMessage)(`${u}${e}`):(0,n.formatLogMessage)(`${u}${e.message}`,e.errCode,e.moreInfo),console.log(t),f(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&f(e,t)},t.logToHud=f,t.exportBuildLogs=async function(e){const t=[];for(let r=0;r<d.length;r+=o.hudConfig.esbuildPluginLogsBatchSize){const n=d.slice(r,r+o.hudConfig.esbuildPluginLogsBatchSize).map(t=>({...t,accessToken:e}));t.push(n)}await(0,a.limitedParallel)(t,10,p)},t.setDontSendLogs=function(){c=!1},t.getShouldSendLogs=function(){return c};const o=r(5809),n=r(523),i=r(6982),a=r(870),s=r(3066),u=o.hudConfig.esbuildPluginMessagePrefix,l=(0,i.randomUUID)(),d=[];let c=!0;function f(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,n.formatLogMessage)(`${u}${e}`)),console.log(e)),d.push({message:e,SessionID:l,timestamp:Date.now()})}async function p(e){await(0,s.requestRelentless)(o.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},6932:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudBuildError=void 0,t.verifyAndMarkFinalFiles=async function(e,t,r){const o=[];for(const n of e){if(!n.path.endsWith(".js")){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}if(!n.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}const e=(0,c.v5)(n.contents,s.hudConfig.bundlerBuildUuidNamespace);o.push({filepath:n.path,buildId:e});const i=m(n.text,e);process.env.HUD_SKIP_FILE_VALIDATION||y(i,n.path,r),n.contents=new Uint8Array(Buffer.from(i,"utf8")),t&&await(0,p.writeFileAndFolder)(n.path,n.contents)}return o},t.markFileAsHudModified=m,t.markFile=function(e,t){const r=d.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[b(e,!0)],suffixStatements:[b(e,!1)]});if(!r||!r.code||!r.map)throw new Error("Failed generating ast");return(0,l.appendInlineSourceMap)(r.code,r.map)},t.createMark=b,t.verifyFileContent=y;const s=r(5809),u=r(2030),l=r(2546),d=a(r(2784)),c=r(3903),f=a(r(9154)),p=r(7085),g=r(5231);class h extends Error{}function m(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function b(e,t){const r=t?"Start":"End";return`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${r}:${e}");`}function y(e,t,r){try{(0,g.logToHud)(`Verifying file content: ${t}, with marks`),new f.Script(e),(0,g.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:o,editedChunksSizes:n}=(0,u.editInSplits)(e,t,r,!0,!0,e=>!e.includes("node_modules"));if(!o)throw new h(`Failed verify file content, ${t}`);for(let e=0;e<n.length;e+=p.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(n.slice(e,e+p.LOG_CHUNKS_SIZE_BATCH));(0,g.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,g.logToHud)(`Verifying new file content: ${t}`),new f.Script(o),(0,g.logToHud)(`Verified new file content: ${t}`),(0,g.logToHud)(`${t}: Original code size: ${e.length}, new code size: ${o.length}`)}catch(e){throw(0,g.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new h(`Failed verify file content, ${t}`)}}t.HudBuildError=h},6982:e=>{e.exports=require("crypto")},7085:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.LOG_CHUNKS_SIZE_BATCH=void 0,t.writeFileAndFolder=async function(e,t){const r=f.dirname(e);try{await d.promises.stat(r)}catch{await d.promises.mkdir(r,{recursive:!0})}await d.promises.writeFile(e,t)},t.getModuleRoot=_;const s=r(8528),u=r(2030),l=r(6982),d=a(r(9896)),c=a(r(857)),f=a(r(6928)),p=r(5809),g=r(2546),h=r(9929),m=r(5231),b=r(6932),y=r(4414),w=30;async function v(e,t,r,o,n){if(!(r&&o&&n&&o.test(e)))return;const i=f.join(n,e),a=f.dirname(i);try{await d.promises.access(a)}catch{await d.promises.mkdir(a,{recursive:!0})}await d.promises.writeFile(i,t,"utf8");const s=await r(i);return s?.contents&&(t=s.contents),t}async function _(e){let t=f.dirname(e);for(let e=0;e<w&&"/"!==t;e++){const e=f.join(t,"package.json");try{return await d.promises.access(e),t}catch{t=f.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=p.hudConfig.esbuildPluginLogsChunkSize;const O="hud-esbuild-plugin";t.plugin=e=>({name:O,async setup(t){if("inline"===t.initialOptions.sourcemap||"both"===t.initialOptions.sourcemap)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildSourceMapInline());if("node"!==t.initialOptions.platform)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===c.platform())return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedWindows());const r=e?.hudKey??process.env.HUD_KEY;if(!r)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildMissingKey());const o=e?.includeModules??(0,p.getModulesToTraceFromEnv)()??[],n=(0,u.createCheckers)(o);(0,m.logToUser)("started running");const i=t.initialOptions.write??!0;t.initialOptions.write=!1;const a="esm"===t.initialOptions?.format?s.Format.esm:s.Format.cjs,{callback:w,filter:T,tempDir:S}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const r=t.plugins.findIndex(e=>e.name===O),o=t.plugins[r+1];if(!o||"datadog-esbuild"!==o.name)return;let n;(0,m.logToHud)("datadog-esbuild plugin detected");const i={...e,onLoad:(...e)=>{n=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(o.setup(i),!n)return void(0,m.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=f.join(c.tmpdir(),`hud-${(0,l.randomUUID)()}`);try{return await d.promises.access(a),void(0,m.logToUser)("temp dir already exists, try rerunning the build.")}catch{}return(0,m.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await d.promises.mkdir(a,{recursive:!0}),{filter:n[0].filter,callback:n[1],tempDir:a}}(t)??{},$=new Set(t.initialOptions.external||[]),U=new Map;t.onResolve({filter:/.*/},async e=>{if(e.pluginData?.hud?.calledFromHud)return;if($.has(e.path))return;const r=p.hudConfig.frameworksToPatch.get(e.path);if(!r)return;if(!r.enable||!r.enableEsbuild)return;const o={...e};delete o.path;const n=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await _(n.path);i&&(U.set(i,e.path),(0,m.logToHud)(`mapping framework: ${i} => ${e.path}`))}),t.onLoad({filter:/.*\.(js|ts)$/},async e=>{try{const t=w?async t=>await w({...e,path:t}):void 0;if((0,u.skip)(e.path,n)){const r=await(0,h.getFrameworkContentSuffix)(e.path,U);if(!r)return;let o=await d.promises.readFile(e.path,"utf8");return o=await v(e.path,o,t,T,S)??o,o+=r,{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}let r=await d.promises.readFile(e.path,"utf8");return r=(0,b.markFile)(e.path,r),r=await v(e.path,r,t,T,S)??r,r+=await(0,h.getFrameworkContentSuffix)(e.path,U)??"",{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}catch(t){return(0,m.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,m.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}}),t.onEnd(async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,b.verifyAndMarkFinalFiles)(e.outputFiles,i,a),(0,m.logToUser)("finished")}catch(e){throw(0,m.logToHud)(`failed validating. Error: ${e}`),(0,m.logToUser)(g.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,y.uploadAllSourceMaps)(t,r)}catch(e){(0,m.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(S)try{await d.promises.access(S),(0,m.logToHud)("cleaning temp dir"),await d.promises.rm(S,{recursive:!0,force:!0})}catch{}}catch(e){(0,m.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,m.getShouldSendLogs)()&&await(0,m.exportBuildLogs)(r)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,m.logToUser)(`Failed exporting build logs. Error: ${e}`)}}})}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=async function(e,t){const r=[...t.entries()].find(([t,r])=>e.startsWith(t));if(!r)return;const[u,l]=r;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=o.hudConfig.frameworksToPatch.get(d);if(!(c?.enable&&c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${n.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)};const o=r(5809),n=r(8528),i=r(2030),a=r(7085),s=r(5231)}},t={};return function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}(7085)})());
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 r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=async function(e,t,r,o=!1){const n=[],i=[];return await Promise.all(Array.from({length:t},async function(){for(;e.length>0;){const t=e.shift();try{const e=await r(t);n.push(e)}catch(e){if(i.push(e),o)throw e}}})),{results:n,errors:i}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=async function(e,t,r,o=3){for(let n=0;n<o;n++)try{return await u.default.post(e,t,r)}catch(t){if(t instanceof u.AxiosError&&401===t.response?.status)throw new s.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,l.logToHud)(`Failed request to ${e}, attempt ${n+1} of ${o}. Error: ${t}`),await new Promise(e=>setTimeout(e,1))}throw new s.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)};const s=r(2546),u=a(r(8938)),l=r(5231)},3903:e=>{e.exports=require("uuid")},4414:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadSourceMap=h,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,f.logToHud)("Skipping source map upload due to env var");else{(0,f.logToHud)(`Uploading source maps for ${e.length} files`);try{const r=[];for(const{buildId:o,filepath:n}of e){const e=`${n}.map`;try{await c.promises.access(e,c.constants.F_OK),r.push({buildId:o,filePath:e,hudKey:t})}catch{(0,f.logToHud)(`No source map found for file: ${n}`)}}await(0,p.limitedParallel)(r,10,h,!0),(0,f.logToHud)("Finished uploading source maps")}catch{return(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,f.setDontSendLogs)()}}};const u=r(5809),l=r(2546),d=s(r(2305)),c=a(r(9896)),f=r(5231),p=r(870),g=r(3066);async function h(e){const{buildId:t,filePath:r,hudKey:o}=e,n=new d.default;n.append("build_id",t),n.append("token",o);try{const e=await c.promises.readFile(r,"utf8"),t=JSON.parse(e);delete t.sourcesContent,n.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,f.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,g.requestRelentless)(`${u.hudConfig.sink.url}/${u.hudConfig.endpoints.sourceMap}`,n,{headers:{"Content-Type":"multipart/form-data"},timeout:u.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,f.logToHud)(`failed uploading source map. File: ${r}, Error: ${e}`),(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemap(r))}}},5231:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logToUser=function(e){let t="";t="string"==typeof e?(0,n.formatLogMessage)(`${u}${e}`):(0,n.formatLogMessage)(`${u}${e.message}`,e.errCode,e.moreInfo),console.log(t),f(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&f(e,t)},t.logToHud=f,t.exportBuildLogs=async function(e){const t=[];for(let r=0;r<d.length;r+=o.hudConfig.esbuildPluginLogsBatchSize){const n=d.slice(r,r+o.hudConfig.esbuildPluginLogsBatchSize).map(t=>({...t,accessToken:e}));t.push(n)}await(0,a.limitedParallel)(t,10,p)},t.setDontSendLogs=function(){c=!1},t.getShouldSendLogs=function(){return c};const o=r(5809),n=r(523),i=r(6982),a=r(870),s=r(3066),u=o.hudConfig.esbuildPluginMessagePrefix,l=(0,i.randomUUID)(),d=[];let c=!0;function f(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,n.formatLogMessage)(`${u}${e}`)),console.log(e)),d.push({message:e,SessionID:l,timestamp:Date.now()})}async function p(e){await(0,s.requestRelentless)(o.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},6932:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudBuildError=void 0,t.verifyAndMarkFinalFiles=async function(e,t,r){const o=[];for(const n of e){if(!n.path.endsWith(".js")){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}if(!n.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}const e=(0,c.v5)(n.contents,s.hudConfig.bundlerBuildUuidNamespace);o.push({filepath:n.path,buildId:e});const i=m(n.text,e);process.env.HUD_SKIP_FILE_VALIDATION||y(i,n.path,r),n.contents=new Uint8Array(Buffer.from(i,"utf8")),t&&await(0,p.writeFileAndFolder)(n.path,n.contents)}return o},t.markFileAsHudModified=m,t.markFile=function(e,t){const r=d.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[b(e,!0)],suffixStatements:[b(e,!1)]});if(!r||!r.code||!r.map)throw new Error("Failed generating ast");return(0,l.appendInlineSourceMap)(r.code,r.map)},t.createMark=b,t.verifyFileContent=y;const s=r(5809),u=r(2030),l=r(2546),d=a(r(2784)),c=r(3903),f=a(r(9154)),p=r(7085),g=r(5231);class h extends Error{}function m(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function b(e,t){const r=t?"Start":"End";return`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${r}:${e}");`}function y(e,t,r){try{(0,g.logToHud)(`Verifying file content: ${t}, with marks`),new f.Script(e),(0,g.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:o,editedChunksSizes:n}=(0,u.editInSplits)(e,t,r,!0,!0,e=>!e.includes("node_modules"));if(!o)throw new h(`Failed verify file content, ${t}`);for(let e=0;e<n.length;e+=p.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(n.slice(e,e+p.LOG_CHUNKS_SIZE_BATCH));(0,g.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,g.logToHud)(`Verifying new file content: ${t}`),new f.Script(o),(0,g.logToHud)(`Verified new file content: ${t}`),(0,g.logToHud)(`${t}: Original code size: ${e.length}, new code size: ${o.length}`)}catch(e){throw(0,g.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new h(`Failed verify file content, ${t}`)}}t.HudBuildError=h},6982:e=>{e.exports=require("crypto")},7085:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.LOG_CHUNKS_SIZE_BATCH=void 0,t.writeFileAndFolder=async function(e,t){const r=f.dirname(e);try{await d.promises.stat(r)}catch{await d.promises.mkdir(r,{recursive:!0})}await d.promises.writeFile(e,t)},t.getModuleRoot=_;const s=r(8528),u=r(2030),l=r(6982),d=a(r(9896)),c=a(r(857)),f=a(r(6928)),p=r(5809),g=r(2546),h=r(9929),m=r(5231),b=r(6932),y=r(4414),w=30;async function v(e,t,r,o,n){if(!(r&&o&&n&&o.test(e)))return;const i=f.join(n,e),a=f.dirname(i);try{await d.promises.access(a)}catch{await d.promises.mkdir(a,{recursive:!0})}await d.promises.writeFile(i,t,"utf8");const s=await r(i);return s?.contents&&(t=s.contents),t}async function _(e){let t=f.dirname(e);for(let e=0;e<w&&"/"!==t;e++){const e=f.join(t,"package.json");try{return await d.promises.access(e),t}catch{t=f.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=p.hudConfig.esbuildPluginLogsChunkSize;const O="hud-esbuild-plugin";t.plugin=e=>({name:O,async setup(t){if("inline"===t.initialOptions.sourcemap||"both"===t.initialOptions.sourcemap)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildSourceMapInline());if("node"!==t.initialOptions.platform)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===c.platform())return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedWindows());const r=e?.hudKey??process.env.HUD_KEY;if(!r)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildMissingKey());const o=e?.includeModules??(0,p.getModulesToTraceFromEnv)()??[],n=(0,u.createCheckers)(o);(0,m.logToUser)("started running");const i=t.initialOptions.write??!0;t.initialOptions.write=!1;const a="esm"===t.initialOptions?.format?s.Format.esm:s.Format.cjs,{callback:w,filter:T,tempDir:S}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const r=t.plugins.findIndex(e=>e.name===O),o=t.plugins[r+1];if(!o||"datadog-esbuild"!==o.name)return;let n;(0,m.logToHud)("datadog-esbuild plugin detected");const i={...e,onLoad:(...e)=>{n=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(o.setup(i),!n)return void(0,m.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=f.join(c.tmpdir(),`hud-${(0,l.randomUUID)()}`);try{return await d.promises.access(a),void(0,m.logToUser)("temp dir already exists, try rerunning the build.")}catch{}return(0,m.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await d.promises.mkdir(a,{recursive:!0}),{filter:n[0].filter,callback:n[1],tempDir:a}}(t)??{},$=new Set(t.initialOptions.external||[]),U=new Map;t.onResolve({filter:/.*/},async e=>{if(e.pluginData?.hud?.calledFromHud)return;if($.has(e.path))return;const r=p.hudConfig.frameworksToPatch.get(e.path);if(!r)return;if(!r.enable||!r.enableEsbuild)return;const o={...e};delete o.path;const n=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await _(n.path);i&&(U.set(i,e.path),(0,m.logToHud)(`mapping framework: ${i} => ${e.path}`))}),t.onLoad({filter:/.*\.(js|ts|cjs)$/},async e=>{try{const t=w?async t=>await w({...e,path:t}):void 0;if((0,u.skip)(e.path,n)){const r=await(0,h.getFrameworkContentSuffix)(e.path,U);if(!r)return;let o=await d.promises.readFile(e.path,"utf8");return o=await v(e.path,o,t,T,S)??o,o+=r,{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}let r=await d.promises.readFile(e.path,"utf8");return r=(0,b.markFile)(e.path,r),r=await v(e.path,r,t,T,S)??r,r+=await(0,h.getFrameworkContentSuffix)(e.path,U)??"",{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}catch(t){return(0,m.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,m.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}}),t.onEnd(async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,b.verifyAndMarkFinalFiles)(e.outputFiles,i,a),(0,m.logToUser)("finished")}catch(e){throw(0,m.logToHud)(`failed validating. Error: ${e}`),(0,m.logToUser)(g.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,y.uploadAllSourceMaps)(t,r)}catch(e){(0,m.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(S)try{await d.promises.access(S),(0,m.logToHud)("cleaning temp dir"),await d.promises.rm(S,{recursive:!0,force:!0})}catch{}}catch(e){(0,m.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,m.getShouldSendLogs)()&&await(0,m.exportBuildLogs)(r)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,m.logToUser)(`Failed exporting build logs. Error: ${e}`)}}})}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=async function(e,t){const r=[...t.entries()].find(([t,r])=>e.startsWith(t));if(!r)return;const[u,l]=r;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=o.hudConfig.frameworksToPatch.get(d);if(!(c?.enable&&c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${n.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)};const o=r(5809),n=r(8528),i=r(2030),a=r(7085),s=r(5231)}},t={};return function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}(7085)})());
2
2
  //# sourceMappingURL=esbuildPlugin.js.map