hud-sdk 1.8.12 → 1.8.13

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.d.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
- export type UserContext = {
4
- [key: string]: string | number | boolean | string[] | number[];
5
- };
3
+ export type UserContext = any;
6
4
  export type FlowHandler<Args extends unknown[], T> = (...args: Args) => T;
7
5
  export declare function setHttpFlow(route: string, method: string): void;
8
6
  export declare function startFlow(flowName: string): void;
package/dist/cjs/api.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var r=e();for(var o in r)("object"==typeof exports?exports:t)[o]=r[o]}}(global,()=>(()=>{"use strict";var t={523:t=>{t.exports=require("./logger")},2030:t=>{t.exports=require("./instrument")},2546:t=>{t.exports=require("./lib")},4074:(t,e,r)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.setHttpFlow=function(t,e){try{if(v())return;if(!c(t)||!c(e))return void p("setHttpFlow");if(void 0===(0,u.getFlowStateStorage)())return void w("setHttpFlow");const r=(0,u.getFlowState)();if(void 0===r?.httpMetric)return void f("setHttpFlow:no-http-context","setHttpFlow called outside an HTTP flow. Skipping.",s.UserErrorLogs.SetHttpFlowNoHttpContext());const o=e.toLowerCase(),a=e.toUpperCase(),l=(0,s.generateEndpointFlowId)(t,[o]),d=l;g.has(d)||(g.add(d),(0,i.storeEndpointDeclaration)(new n.EndpointDeclaration(l,[o],"manual","",t))),r.httpMetric.setFlowId(l),r.httpMetric.setRequestAttributes({method:a}),r.flowId=l}catch(t){(0,l.limitedLogger)("Failed to set http flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.startFlow=function(t){try{if(v())return;if(!c(t))return void p("startFlow");const e=(0,u.getFlowStateStorage)();if(void 0===e)return void w("startFlow");const r=(0,u.getFlowState)();if(F("startFlow",r))return;const o=function(t,e){const r=E(t);if(void 0===r)return;const o=a.CustomFlowMetric.createUsableMetric(r),n=e??{};return n.manualFlowMetric=o,n.manualFlowName=t,n.flowId=r,{state:n,metric:o}}(t,r);if(void 0===o)return;e.enterWith(o.state),o.metric.start(),(0,a.createNewInvestigation)()}catch(t){(0,l.limitedLogger)("Failed to start manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.endFlow=function(t){try{if(v())return;if(void 0===(0,u.getFlowStateStorage)())return void w("endFlow");const e=(0,u.getFlowState)(),r=e?.manualFlowMetric;if(void 0===e||void 0===r)return void f("endFlow:no-start-flow","endFlow called without an active startFlow flow. Skipping.",s.UserErrorLogs.EndFlowNoStartedFlow());m(e,t)}catch(t){(0,l.limitedLogger)("Failed to end manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.wrapFlow=function(t,e){try{if(v())return e;if(!c(t))return p("wrapFlow"),e;if(void 0===(0,u.getFlowStateStorage)())return w("wrapFlow"),e;const r=E(t);if(void 0===r)return e;const o=()=>{if(!v()&&!F("wrapFlow",(0,u.getFlowState)()))return r},n=(e,r)=>{if(!e)return;if(void 0===(0,u.getFlowStateStorage)())return;const o=a.CustomFlowMetric.createUsableMetric(e),n={};return n.manualFlowMetric=o,n.manualFlowName=t,r.state=n,o.start(),(0,a.createNewInvestigation)(),n},i=(t,e)=>{m(e.state)},s=(t,e,r)=>{m(e.state,function(t){return t instanceof Error&&t.name?t.name:"Error"}(r))};return(0,a.wrapFlow)(o,e,!0,n,i,s)}catch(t){return(0,l.limitedLogger)("Failed to wrap manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),e}};const o=r(5809),n=r(8528),i=r(8269),a=r(2030),s=r(2546),l=r(523),u=r(7131),g=new Set,d=new Set;function c(t){return"string"==typeof t&&t.length>0}function f(t,e,r){d.has(t)||(l.app_logger.warning(e),l.customer_logger.logEntry(r),d.add(t))}function w(t){f(`${t}:before-register`,`${t} called before register. Skipping.`,s.UserErrorLogs.ManualFlowApiBeforeRegister(t))}function p(t){f(`${t}:invalid-flow-name`,`${t} called with an invalid flow name. Skipping.`,s.UserErrorLogs.ManualFlowApiInvalidFlowName(t))}function F(t,e){return void 0!==e?.httpMetric?(function(t){f(`${t}:inside-http-flow`,`${t} called inside an HTTP flow. Skipping.`,s.UserErrorLogs.CustomFlowApiInsideHttpFlow(t))}(t),!0):(void 0!==e?.manualFlowMetric||void 0!==e?.flowId)&&(function(t){f(`${t}:inside-flow`,`${t} called inside another flow. Skipping.`,s.UserErrorLogs.CustomFlowApiInsideFlow(t))}(t),!0)}function m(t,e){const r=t?.manualFlowMetric;if(void 0!==t&&void 0!==r)try{void 0!==e&&e.length>0&&r.setFailureReason(e),r.calculateDuration(),(0,a.finishCustomFlowInvestigation)(r,t.manualFlowName??""),r.finish()}catch(t){(0,l.limitedLogger)("Failed to finish manual flow metric",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}finally{t.manualFlowMetric=void 0,t.manualFlowName=void 0,t.flowId=void 0,t.shouldLinkFunction=void 0}}function v(){return void 0!==hudRunningMode&&hudRunningMode!==n.HudRunningMode.enabled}function E(t){const e=o.hudConfig.dynamicConfig.maxCustomFlowIds,r=(0,s.generateCustomFlowId)(t);if((0,i.storeCustomFlowDeclarationOnce)({flow_id:r,flow_name:t},e))return r;(0,l.limitedLogger)("Custom flow id limit reached",{flowName:t,maxCustomFlowIds:e})}},5809:t=>{t.exports=require("./config")},7131:t=>{t.exports=require("./wrap")},8269:t=>{t.exports=require("./globalstate")},8528:t=>{t.exports=require("./dto")}},e={};function r(o){var n=e[o];if(void 0!==n)return n.exports;var i=e[o]={exports:{}};return t[o](i,i.exports,r),i.exports}var o={};return(()=>{var t=o;Object.defineProperty(t,"__esModule",{value:!0}),t.wrapFlow=t.startFlow=t.setHttpFlow=t.endFlow=void 0,t.setContext=S,t.setFailure=function(t,r){try{if(E())return;const o=(0,l.getInvestigationStorage)();if(void 0===o)return void(w||(s.app_logger.warning("setFailure - No Storage"),s.customer_logger.logEntry(a.UserErrorLogs.SetFailureBeforeRegister()),w=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const u=o.getStore();if(void 0===u||u.status!==n.InvestigationStatus.Open)return void(p||(s.app_logger.warning("setFailure called not inside async context. Skipping."),s.customer_logger.logEntry(a.UserErrorLogs.SetFailureNoAsyncContext()),p=!0));if("string"!=typeof t)return void s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorNotString());if(0===t.length)return void s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorEmpty());let g=t;if(t.length>m&&(s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorTooLong()),g=t.substring(0,m)),!(0,i.getUniqueSetFailureErrors)().has(g)){const t=e.hudConfig.dynamicConfig.investigationRateLimits.maxUniqueSetFailureErrors;(0,i.getUniqueSetFailureErrors)().size>=t&&(F||(s.customer_logger.logEntry(a.UserErrorLogs.SetFailureUniqueErrorLimitReached(t)),(0,s.limitedLogger)("setFailure: max unique errors reached",{error:g}),F=!0),g=v),(0,i.getUniqueSetFailureErrors)().add(g)}u.data.userDefinedError=g,void 0!==r&&S(r)}catch(t){s.app_logger.warning("failed to set failure. Skipping.",{error:t,stack:t instanceof Error&&null!==t?t.stack:void 0})}};const e=r(5809),n=r(8528),i=r(8269),a=r(2546),s=r(523),l=r(7131);var u=r(4074);Object.defineProperty(t,"endFlow",{enumerable:!0,get:function(){return u.endFlow}}),Object.defineProperty(t,"setHttpFlow",{enumerable:!0,get:function(){return u.setHttpFlow}}),Object.defineProperty(t,"startFlow",{enumerable:!0,get:function(){return u.startFlow}}),Object.defineProperty(t,"wrapFlow",{enumerable:!0,get:function(){return u.wrapFlow}});let g=!1,d=!1,c=!1,f=!1,w=!1,p=!1,F=!1;const m=1024,v="HUD_MAX_ERRORS_REACHED";function E(){return void 0!==hudRunningMode&&hudRunningMode!==n.HudRunningMode.enabled}function S(t){try{if(E())return;const r=(0,l.getInvestigationStorage)();if(void 0===r)return void(c||(s.app_logger.warning("HudContext warning: No Storage"),s.customer_logger.logEntry(a.UserErrorLogs.SetContextBeforeRegister()),c=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const o=r.getStore();if(void 0===o||o.status!==n.InvestigationStatus.Open)return void(g||(s.app_logger.warning("HudContext warning: setContext called not inside async context. Skipping."),s.customer_logger.logEntry(a.UserErrorLogs.SetContextNoAsyncContext()),g=!0));const i=(0,a.validateContext)(t);o.data.userContext={...o.data.userContext,...i}}catch(t){if(t instanceof a.HudContextValidationError)return void(f||(s.app_logger.warning("HudContext warning: failed to validate context. Skipping.",{error:t,stack:t instanceof Error&&null!==t?t.stack:void 0}),f=!0));d||(s.app_logger.warning("HudContext warning: failed to set context. Skipping.",{error:t,stack:t instanceof Error&&null!==t?t.stack:void 0}),d=!0)}}})(),o})());
1
+ !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o=e();for(var r in o)("object"==typeof exports?exports:t)[r]=o[r]}}(global,()=>(()=>{"use strict";var t={523:t=>{t.exports=require("./logger")},2030:t=>{t.exports=require("./instrument")},2546:t=>{t.exports=require("./lib")},4074:(t,e,o)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.setHttpFlow=function(t,e){try{if(v())return;if(!c(t)||!c(e))return void p("setHttpFlow");if(void 0===(0,u.getFlowStateStorage)())return void w("setHttpFlow");const o=(0,u.getFlowState)();if(void 0===o?.httpMetric)return void f("setHttpFlow:no-http-context","setHttpFlow called outside an HTTP flow. Skipping.",s.UserErrorLogs.SetHttpFlowNoHttpContext());const r=e.toLowerCase(),a=e.toUpperCase(),l=(0,s.generateEndpointFlowId)(t,[r]),d=l;g.has(d)||(g.add(d),(0,i.storeEndpointDeclaration)(new n.EndpointDeclaration(l,[r],"manual","",t))),o.httpMetric.setFlowId(l),o.httpMetric.setRequestAttributes({method:a}),o.flowId=l}catch(t){(0,l.limitedLogger)("Failed to set http flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.startFlow=function(t){try{if(v())return;if(!c(t))return void p("startFlow");const e=(0,u.getFlowStateStorage)();if(void 0===e)return void w("startFlow");const o=(0,u.getFlowState)();if(F("startFlow",o))return;const r=function(t,e){const o=E(t);if(void 0===o)return;const r=a.CustomFlowMetric.createUsableMetric(o),n=e??{};return n.manualFlowMetric=r,n.manualFlowName=t,n.flowId=o,{state:n,metric:r}}(t,o);if(void 0===r)return;e.enterWith(r.state),r.metric.start(),(0,a.createNewInvestigation)()}catch(t){(0,l.limitedLogger)("Failed to start manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.endFlow=function(t){try{if(v())return;if(void 0===(0,u.getFlowStateStorage)())return void w("endFlow");const e=(0,u.getFlowState)(),o=e?.manualFlowMetric;if(void 0===e||void 0===o)return void f("endFlow:no-start-flow","endFlow called without an active startFlow flow. Skipping.",s.UserErrorLogs.EndFlowNoStartedFlow());m(e,t)}catch(t){(0,l.limitedLogger)("Failed to end manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}},e.wrapFlow=function(t,e){try{if(v())return e;if(!c(t))return p("wrapFlow"),e;if(void 0===(0,u.getFlowStateStorage)())return w("wrapFlow"),e;const o=E(t);if(void 0===o)return e;const r=()=>{if(!v()&&!F("wrapFlow",(0,u.getFlowState)()))return o},n=(e,o)=>{if(!e)return;if(void 0===(0,u.getFlowStateStorage)())return;const r=a.CustomFlowMetric.createUsableMetric(e),n={};return n.manualFlowMetric=r,n.manualFlowName=t,o.state=n,r.start(),(0,a.createNewInvestigation)(),n},i=(t,e)=>{m(e.state)},s=(t,e,o)=>{m(e.state,function(t){return t instanceof Error&&t.name?t.name:"Error"}(o))};return(0,a.wrapFlow)(r,e,!0,n,i,s)}catch(t){return(0,l.limitedLogger)("Failed to wrap manual flow",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),e}};const r=o(5809),n=o(8528),i=o(8269),a=o(2030),s=o(2546),l=o(523),u=o(7131),g=new Set,d=new Set;function c(t){return"string"==typeof t&&t.length>0}function f(t,e,o){d.has(t)||(l.app_logger.warning(e),l.customer_logger.logEntry(o),d.add(t))}function w(t){f(`${t}:before-register`,`${t} called before register. Skipping.`,s.UserErrorLogs.ManualFlowApiBeforeRegister(t))}function p(t){f(`${t}:invalid-flow-name`,`${t} called with an invalid flow name. Skipping.`,s.UserErrorLogs.ManualFlowApiInvalidFlowName(t))}function F(t,e){return void 0!==e?.httpMetric?(function(t){f(`${t}:inside-http-flow`,`${t} called inside an HTTP flow. Skipping.`,s.UserErrorLogs.CustomFlowApiInsideHttpFlow(t))}(t),!0):(void 0!==e?.manualFlowMetric||void 0!==e?.flowId)&&(function(t){f(`${t}:inside-flow`,`${t} called inside another flow. Skipping.`,s.UserErrorLogs.CustomFlowApiInsideFlow(t))}(t),!0)}function m(t,e){const o=t?.manualFlowMetric;if(void 0!==t&&void 0!==o)try{void 0!==e&&e.length>0&&o.setFailureReason(e),o.calculateDuration(),(0,a.finishCustomFlowInvestigation)(o,t.manualFlowName??""),o.finish()}catch(t){(0,l.limitedLogger)("Failed to finish manual flow metric",{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}finally{t.manualFlowMetric=void 0,t.manualFlowName=void 0,t.flowId=void 0,t.shouldLinkFunction=void 0}}function v(){return void 0!==globalThis.hudRunningMode&&globalThis.hudRunningMode!==n.HudRunningMode.enabled}function E(t){const e=r.hudConfig.dynamicConfig.maxCustomFlowIds,o=(0,s.generateCustomFlowId)(t);if((0,i.storeCustomFlowDeclarationOnce)({flow_id:o,flow_name:t},e))return o;(0,l.limitedLogger)("Custom flow id limit reached",{flowName:t,maxCustomFlowIds:e})}},5809:t=>{t.exports=require("./config")},7131:t=>{t.exports=require("./wrap")},8269:t=>{t.exports=require("./globalstate")},8528:t=>{t.exports=require("./dto")}},e={};function o(r){var n=e[r];if(void 0!==n)return n.exports;var i=e[r]={exports:{}};return t[r](i,i.exports,o),i.exports}var r={};return(()=>{var t=r;Object.defineProperty(t,"__esModule",{value:!0}),t.wrapFlow=t.startFlow=t.setHttpFlow=t.endFlow=void 0,t.setContext=E,t.setFailure=function(t,o){try{if(v())return;const r=(0,l.getInvestigationStorage)();if(void 0===r)return void(f||(s.app_logger.warning("setFailure - No Storage"),s.customer_logger.logEntry(a.UserErrorLogs.SetFailureBeforeRegister()),f=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const u=r.getStore();if(void 0===u||u.status!==n.InvestigationStatus.Open)return void(w||(s.app_logger.warning("setFailure called not inside async context. Skipping."),s.customer_logger.logEntry(a.UserErrorLogs.SetFailureNoAsyncContext()),w=!0));if("string"!=typeof t)return void s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorNotString());if(0===t.length)return void s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorEmpty());let g=t;if(t.length>F&&(s.customer_logger.logEntry(a.UserErrorLogs.SetFailureErrorTooLong()),g=t.substring(0,F)),!(0,i.getUniqueSetFailureErrors)().has(g)){const t=e.hudConfig.dynamicConfig.investigationRateLimits.maxUniqueSetFailureErrors;(0,i.getUniqueSetFailureErrors)().size>=t&&(p||(s.customer_logger.logEntry(a.UserErrorLogs.SetFailureUniqueErrorLimitReached(t)),(0,s.limitedLogger)("setFailure: max unique errors reached",{error:g}),p=!0),g=m),(0,i.getUniqueSetFailureErrors)().add(g)}u.data.userDefinedError=g,void 0!==o&&E(o)}catch(t){s.app_logger.warning("failed to set failure. Skipping.",{error:t,stack:t instanceof Error&&null!==t?t.stack:void 0})}};const e=o(5809),n=o(8528),i=o(8269),a=o(2546),s=o(523),l=o(7131);var u=o(4074);Object.defineProperty(t,"endFlow",{enumerable:!0,get:function(){return u.endFlow}}),Object.defineProperty(t,"setHttpFlow",{enumerable:!0,get:function(){return u.setHttpFlow}}),Object.defineProperty(t,"startFlow",{enumerable:!0,get:function(){return u.startFlow}}),Object.defineProperty(t,"wrapFlow",{enumerable:!0,get:function(){return u.wrapFlow}});let g=!1,d=!1,c=!1,f=!1,w=!1,p=!1;const F=1024,m="HUD_MAX_ERRORS_REACHED";function v(){return void 0!==globalThis.hudRunningMode&&globalThis.hudRunningMode!==n.HudRunningMode.enabled}function E(t){try{if(v())return;const o=(0,l.getInvestigationStorage)();if(void 0===o)return void(c||(s.app_logger.warning("HudContext warning: No Storage"),s.customer_logger.logEntry(a.UserErrorLogs.SetContextBeforeRegister()),c=!0));if(!e.hudConfig.dynamicConfig.enableInvestigation)return;const r=o.getStore();if(void 0===r||r.status!==n.InvestigationStatus.Open)return void(g||(s.app_logger.warning("HudContext warning: setContext called not inside async context. Skipping."),s.customer_logger.logEntry(a.UserErrorLogs.SetContextNoAsyncContext()),g=!0));r.data.userContext={...r.data.userContext,...t}}catch(t){d||(s.app_logger.warning("HudContext warning: failed to set context. Skipping.",{error:t,stack:t instanceof Error&&null!==t?t.stack:void 0}),d=!0)}}})(),r})());
2
2
  //# sourceMappingURL=api.js.map
@@ -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 a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),a=this&&this.__exportStar||function(e,n){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(n,t)||i(n,e,t)};Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=n.SDK_MODULE_NAME=void 0,a(t(2887),n),a(t(2570),n);var o=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return o.SDK_MODULE_NAME}}),a(t(7089),n);var r=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.refreshInvestigationErrorStatusCodeRegex=function(e,n,t){if(null==e)return;const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return;const r=o.data?.investigationErrorStatusCodeRegex;void 0!==r&&r!==n.dynamicConfig.investigationErrorStatusCodeRegex&&a(r,n,t,"Periodic refresh - Dynamic configuration updated - investigationErrorStatusCodeRegex")},n.refreshInvestigationEnabled=function(e,n,t){if(null==e)return;const a=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!a.success)return;const o=a.data?.enableInvestigation;if(void 0===o)return;o!==globalThis.hudEnableInvestigation&&(n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o,t.info("Periodic refresh - Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o})))},n.updateDynamicConfig=function(e,n,t){const 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 s=o(n.dynamicConfig,r.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),void 0!==s?.investigationRateLimits?.executionFlowMaxLength&&s?.investigationRateLimits?.executionFlowMaxLength!==n.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=s.investigationRateLimits.executionFlowMaxLength),void 0!==s?.investigationRateLimits?.exceptionMaxLength&&s?.investigationRateLimits?.exceptionMaxLength!==n.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=s.investigationRateLimits.exceptionMaxLength),void 0!==r.data.investigationErrorStatusCodeRegex&&s.investigationErrorStatusCodeRegex!==n.dynamicConfig.investigationErrorStatusCodeRegex&&a(s.investigationErrorStatusCodeRegex,n,t,"Dynamic configuration updated - investigationErrorStatusCodeRegex",s),s};const i=t(2887);function a(e,n,t,a,o){const{appliedRegex:r,usedDefault:s}=(0,i.updateInvestigationErrorStatusCodePatternGlobal)(e);n.dynamicConfig.investigationErrorStatusCodeRegex=r,o&&(o.investigationErrorStatusCodeRegex=r),s&&e!==r?t.warning("Invalid investigationErrorStatusCodeRegex, using default",{investigationErrorStatusCodeRegex:e,appliedRegex:r}):t.info(a,{investigationErrorStatusCodeRegex:r})}function o(e,n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(e)&&Array.isArray(n))return n;const t={...e};for(const i in n){const a=e[i],r=n[i];t[i]=o(a,r)}return t}},2887:function(e,n,t){var i,a=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var n=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[n.length]=t);return n},i(e)},function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t=i(e),r=0;r<t.length;r++)"default"!==t[r]&&a(n,e,t[r]);return o(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.loggerConfig=n.hudConfig=n.HudDynamicConfigSchema=n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX=void 0,n.functionUuidToBase64=c,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{n=new Map}return n},n.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},n.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)},n.updateInvestigationErrorStatusCodePatternGlobal=function(e=n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX){try{return globalThis.hudInvestigationErrorStatusCodePattern=new RegExp(`^(?:${e})$`),{appliedRegex:e,usedDefault:e===n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX}}catch{return globalThis.hudInvestigationErrorStatusCodePattern=new RegExp(`^(?:${n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX})$`),{appliedRegex:n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX,usedDefault:!0}}},n.matchesInvestigationErrorStatusCode=function(e){return null!=e&&globalThis.hudInvestigationErrorStatusCodePattern.test(String(e))};const s=t(8528),l=r(t(6928)),u=t(3903),d=t(1569);function c(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX="^5\\d\\d$",n.HudDynamicConfigSchema=d.z.object({aggregationInterval:d.z.number(),aggregationFirstSendTimeout:d.z.number(),investigationInterval:d.z.number(),investigationFirstSendTimeout:d.z.number(),enableInvestigation:d.z.boolean(),investigationErrorStatusCodeRegex:d.z.string(),enableInvestigationArgsSending:d.z.boolean(),investigationRateLimits:d.z.object({maxSameInvestigations:d.z.number().int().positive(),sameInvestigationTimeWindowMs:d.z.number().int().positive(),maxTotalInvestigations:d.z.number().int().positive(),maxTotalInvestigationsErrorBased:d.z.number().int().positive(),maxTotalInvestigationsDurationBased:d.z.number().int().positive(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs:d.z.number().int().positive(),maxStringLength:d.z.number().int().positive(),maxArrayLength:d.z.number().int().positive(),maxObjectDepth:d.z.number().int().positive(),maxKeyLength:d.z.number().int().positive(),executionFlowMaxLength:d.z.number().int().positive(),exceptionMaxLength:d.z.number().int().positive(),maxUniqueSetFailureErrors:d.z.number().int().positive()}),machineMetricsInterval:d.z.number().int().positive(),blacklistParams:d.z.array(d.z.string()),forensicsBlacklistFields:d.z.array(d.z.string()),forensicsWhitelistFields:d.z.array(d.z.string()),censorshipRegexes:d.z.array(d.z.object({regex:d.z.string(),replacement:d.z.string()})),reingestInterval:d.z.number().int().positive(),extraHeaders:d.z.array(d.z.string()),performanceMetricsInterval:d.z.number().int().positive(),enableOutboundData:d.z.boolean(),maxTotalOutbounds:d.z.number().int().positive(),maxOutboundCountWithData:d.z.number().int().positive(),maxHTTPRequestBodySize:d.z.number().int().positive(),maxHTTPResponseBodySize:d.z.number().int().positive(),functionDetachEnabled:d.z.boolean(),functionDetachThresholdPerSecond:d.z.number().int().positive(),enableMongoDocumentData:d.z.boolean(),enableTeardown:d.z.boolean(),flushOnUncaughtException:d.z.boolean(),fileTimestampsLogDelayMs:d.z.number().int().positive(),maxCustomFlowIds:d.z.number().int().positive()});const g=process.env.HUD_ENABLE_INVESTIGATION,v="_HUD",p="94a210f3-861c-4e18-ab27-6b6c19437c9d",b={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration",getKnownDetachedFunctions:"sink/known-detached-functions/get",setDetachedFunctions:"sink/known-detached-functions/set"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{lean:{value:!1,source:"DEFAULT"},minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},disableDetachedFunctions:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,remoteConfigRefreshInterval:3e5,workerStateCollectionDelay:1e4,workerGrace:6e4,teardownGrace:5e3,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:p,wrapVarPrefix:v,functionInitFunctionName:`${v}i`,functionCatchFunctionName:`${v}c`,functionFinallyFunctionName:`${v}n`,callContextVarName:`${v}x`,fixStackFunctionName:`${v}s`,asyncIteratorWrapperFunctionName:`${v}w`,wrapperUserCatchFunctionName:`${v}u`,asyncWrapperFunctionName:`${v}a`,internalAsyncWrapperFunctionName:`${v}b`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",enableEsbuild:!0}],[l.join("express","lib","router","layer.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<5",patcher:"expressLayer",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","router","index.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<5",patcher:"expressRouter",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"expressRouterInRouter",enableEsbuild:!0}],[l.join("router","lib","layer.js"),{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"expressLayerInRouter",enableEsbuild:!0}],["@hapi/hapi",{framework:s.availableFrameworks.hapi,enable:!0,version:">=20.0.0 <22.0.0",patcher:"hapi"}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0 || ^3.0.0",patcher:"koa"}],["fastify",{framework:s.availableFrameworks.fastify,enable:!0,version:">=4.0.0 <6",patcher:"fastify"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/compiled/next-server/pages-api-turbo.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=16.0.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:">=7.5.0",patcher:"sqsConsumer"}],[["@mondaydotcomorg/monday-sqs-consumer","sqs-consumer"].join(l.sep),{framework:s.availableFrameworks.sqs,enable:"win32"!==process.platform,version:">=5.2.2 <6",patcher:"sqsConsumer",extraInfo:{isMondayVersion:!0,srcHash:"bd9064befbf3abb9ad0e6a53b0cf721d5612d5b8d8790875c994b7ff40b951c5"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["@clickhouse/client-common",{framework:s.availableFrameworks.clickhouse,enable:!1,version:"^1.10.0",patcher:"outbound/clickhouse",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["mongodb",{framework:s.availableFrameworks.mongodb,enable:!0,version:">=5.0.0 <8.0.0",patcher:"outbound/mongodb",extraInfo:{isOutbound:!0}}],["mongoose",{framework:s.availableFrameworks.mongoose,enable:!0,version:">=5.0.0 <7.0.0",patcher:"outbound/mongoose",extraInfo:{isOutbound:!0,coveredByFramework:{frameworkKey:"mongodb",versionRange:">=7.0.0 <10.0.0"}}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,investigationErrorStatusCodeRegex:n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX,enableInvestigationArgsSending:!1,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30,maxUniqueSetFailureErrors:100},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20,functionDetachEnabled:!1,functionDetachThresholdPerSecond:5833,enableMongoDocumentData:!1,enableTeardown:!1,flushOnUncaughtException:!1,fileTimestampsLogDelayMs:12e4,maxCustomFlowIds:1e3},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:c((0,u.v5)("axios",p)),nodeFetchFunctionId:c((0,u.v5)("node-fetch",p)),nodeFetchBodiesFunctionIds:{json:c((0,u.v5)("node-fetch-body-json",p)),text:c((0,u.v5)("node-fetch-body-text",p)),arrayBuffer:c((0,u.v5)("node-fetch-body-arrayBuffer",p)),blob:c((0,u.v5)("node-fetch-body-blob",p))},requestFunctionId:c((0,u.v5)("request-request",p)),requestMethodFunctionIds:{get:c((0,u.v5)("request-get",p)),head:c((0,u.v5)("request-head",p)),options:c((0,u.v5)("request-options",p)),post:c((0,u.v5)("request-post",p)),put:c((0,u.v5)("request-put",p)),patch:c((0,u.v5)("request-patch",p)),del:c((0,u.v5)("request-del",p)),delete:c((0,u.v5)("request-delete",p))},pgConnectFunctionId:c((0,u.v5)("pg-connect",p)),pgQueryFunctionId:c((0,u.v5)("pg-query",p)),pgEndFunctionId:c((0,u.v5)("pg-end",p)),clickhouseQueryFunctionId:c((0,u.v5)("clickhouse-query",p)),clickhouseExecFunctionId:c((0,u.v5)("clickhouse-exec",p)),clickhouseCommandFunctionId:c((0,u.v5)("clickhouse-command",p)),clickhouseInsertFunctionId:c((0,u.v5)("clickhouse-insert",p)),clickhouseCloseFunctionId:c((0,u.v5)("clickhouse-close",p)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};n.hudConfig=function(e={}){return{...b,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),n.default=n.hudConfig;const f=process.env.HUD_DEBUG?n.hudConfig.logger.debug:n.hudConfig.logger.default;n.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.8.12"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),a=i.z.object({type:i.z.literal("s3")}),o=i.z.object({type:i.z.literal("disk"),path:i.z.string()}),r=i.z.object({type:i.z.literal("customer_s3"),bucket:i.z.string(),region:i.z.string(),prefix:i.z.string().optional()});n.ObjectStoreConfigSchema=i.z.union([a,o,r])},8528:e=>{e.exports=require("./dto")}},n={};return function t(i){var a=n[i];if(void 0!==a)return a.exports;var o=n[i]={exports:{}};return e[i].call(o.exports,o,o.exports,t),o.exports}(2509)})());
1
+ !function(e,n){if("object"==typeof exports&&"object"==typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var t=n();for(var i in t)("object"==typeof exports?exports:e)[i]=t[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_MODULE_NAME=void 0,n.SDK_MODULE_NAME="hud-sdk"},2509:function(e,n,t){var i=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),a=this&&this.__exportStar||function(e,n){for(var t in e)"default"===t||Object.prototype.hasOwnProperty.call(n,t)||i(n,e,t)};Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=n.SDK_MODULE_NAME=void 0,a(t(2887),n),a(t(2570),n);var o=t(2210);Object.defineProperty(n,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return o.SDK_MODULE_NAME}}),a(t(7089),n);var r=t(5453);Object.defineProperty(n,"SDK_VERSION",{enumerable:!0,get:function(){return r.SDK_VERSION}})},2570:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.refreshInvestigationErrorStatusCodeRegex=function(e,n,t){if(null==e)return;const o=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!o.success)return;const r=o.data?.investigationErrorStatusCodeRegex;void 0!==r&&r!==n.dynamicConfig.investigationErrorStatusCodeRegex&&a(r,n,t,"Periodic refresh - Dynamic configuration updated - investigationErrorStatusCodeRegex")},n.refreshInvestigationEnabled=function(e,n,t){if(null==e)return;const a=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!a.success)return;const o=a.data?.enableInvestigation;if(void 0===o)return;o!==globalThis.hudEnableInvestigation&&(n.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o,t.info("Periodic refresh - Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o})))},n.updateDynamicConfig=function(e,n,t){const 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 s=o(n.dynamicConfig,r.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),void 0!==s?.investigationRateLimits?.executionFlowMaxLength&&s?.investigationRateLimits?.executionFlowMaxLength!==n.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=s.investigationRateLimits.executionFlowMaxLength),void 0!==s?.investigationRateLimits?.exceptionMaxLength&&s?.investigationRateLimits?.exceptionMaxLength!==n.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=s.investigationRateLimits.exceptionMaxLength),void 0!==r.data.investigationErrorStatusCodeRegex&&s.investigationErrorStatusCodeRegex!==n.dynamicConfig.investigationErrorStatusCodeRegex&&a(s.investigationErrorStatusCodeRegex,n,t,"Dynamic configuration updated - investigationErrorStatusCodeRegex",s),s};const i=t(2887);function a(e,n,t,a,o){const{appliedRegex:r,usedDefault:s}=(0,i.updateInvestigationErrorStatusCodePatternGlobal)(e);n.dynamicConfig.investigationErrorStatusCodeRegex=r,o&&(o.investigationErrorStatusCodeRegex=r),s&&e!==r?t.warning("Invalid investigationErrorStatusCodeRegex, using default",{investigationErrorStatusCodeRegex:e,appliedRegex:r}):t.info(a,{investigationErrorStatusCodeRegex:r})}function o(e,n){if(null===n||"object"!=typeof n)return n;if(Array.isArray(e)&&Array.isArray(n))return n;const t={...e};for(const i in n){const a=e[i],r=n[i];t[i]=o(a,r)}return t}},2887:function(e,n,t){var i,a=this&&this.__createBinding||(Object.create?function(e,n,t,i){void 0===i&&(i=t);var a=Object.getOwnPropertyDescriptor(n,t);a&&!("get"in a?!n.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,a)}:function(e,n,t,i){void 0===i&&(i=t),e[i]=n[t]}),o=this&&this.__setModuleDefault||(Object.create?function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}:function(e,n){e.default=n}),r=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var n=[];for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[n.length]=t);return n},i(e)},function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var t=i(e),r=0;r<t.length;r++)"default"!==t[r]&&a(n,e,t[r]);return o(n,e),n});Object.defineProperty(n,"__esModule",{value:!0}),n.HudFailedReadConfigError=n.loggerConfig=n.hudConfig=n.HudDynamicConfigSchema=n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX=void 0,n.functionUuidToBase64=c,n.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},n.getExcludeDirsFromEnv=function(){const e=process.env.HUD_EXCLUDE_DIRS;if(e)return e.split(",")},n.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let n;if(e)try{n=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{n=new Map}return n},n.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},n.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=n.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(n.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)},n.updateInvestigationErrorStatusCodePatternGlobal=function(e=n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX){try{return globalThis.hudInvestigationErrorStatusCodePattern=new RegExp(`^(?:${e})$`),{appliedRegex:e,usedDefault:e===n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX}}catch{return globalThis.hudInvestigationErrorStatusCodePattern=new RegExp(`^(?:${n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX})$`),{appliedRegex:n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX,usedDefault:!0}}},n.matchesInvestigationErrorStatusCode=function(e){return null!=e&&globalThis.hudInvestigationErrorStatusCodePattern.test(String(e))};const s=t(8528),l=r(t(6928)),u=t(3903),d=t(1569);function c(e){return Buffer.from((0,u.parse)(e)).toString("base64").slice(0,22)}const m="globalThis._hudMark";n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX="^5\\d\\d$",n.HudDynamicConfigSchema=d.z.object({aggregationInterval:d.z.number(),aggregationFirstSendTimeout:d.z.number(),investigationInterval:d.z.number(),investigationFirstSendTimeout:d.z.number(),enableInvestigation:d.z.boolean(),investigationErrorStatusCodeRegex:d.z.string(),enableInvestigationArgsSending:d.z.boolean(),investigationRateLimits:d.z.object({maxSameInvestigations:d.z.number().int().positive(),sameInvestigationTimeWindowMs:d.z.number().int().positive(),maxTotalInvestigations:d.z.number().int().positive(),maxTotalInvestigationsErrorBased:d.z.number().int().positive(),maxTotalInvestigationsDurationBased:d.z.number().int().positive(),totalInvestigationTimeWindowMs:d.z.number().int().positive(),maxUniqLogs:d.z.number().int().positive(),maxStringLength:d.z.number().int().positive(),maxArrayLength:d.z.number().int().positive(),maxObjectDepth:d.z.number().int().positive(),maxKeyLength:d.z.number().int().positive(),executionFlowMaxLength:d.z.number().int().positive(),exceptionMaxLength:d.z.number().int().positive(),maxUniqueSetFailureErrors:d.z.number().int().positive()}),machineMetricsInterval:d.z.number().int().positive(),blacklistParams:d.z.array(d.z.string()),forensicsBlacklistFields:d.z.array(d.z.string()),forensicsWhitelistFields:d.z.array(d.z.string()),censorshipRegexes:d.z.array(d.z.object({regex:d.z.string(),replacement:d.z.string()})),reingestInterval:d.z.number().int().positive(),extraHeaders:d.z.array(d.z.string()),performanceMetricsInterval:d.z.number().int().positive(),enableOutboundData:d.z.boolean(),maxTotalOutbounds:d.z.number().int().positive(),maxOutboundCountWithData:d.z.number().int().positive(),maxHTTPRequestBodySize:d.z.number().int().positive(),maxHTTPResponseBodySize:d.z.number().int().positive(),functionDetachEnabled:d.z.boolean(),functionDetachThresholdPerSecond:d.z.number().int().positive(),enableMongoDocumentData:d.z.boolean(),enableTeardown:d.z.boolean(),flushOnUncaughtException:d.z.boolean(),fileTimestampsLogDelayMs:d.z.number().int().positive(),maxCustomFlowIds:d.z.number().int().positive()});const g=process.env.HUD_ENABLE_INVESTIGATION,v="_HUD",p="94a210f3-861c-4e18-ab27-6b6c19437c9d",b={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration",getKnownDetachedFunctions:"sink/known-detached-functions/get",setDetachedFunctions:"sink/known-detached-functions/set"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{lean:{value:!1,source:"DEFAULT"},minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},excludeDirs:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"},disableDetachedFunctions:{value:!1,source:"DEFAULT"},enableVarHoisting:{value:!1,source:"DEFAULT"},instrumentOneLiners:{value:!0,source:"DEFAULT"},forensicsOnly:{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,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,remoteConfigRefreshInterval:3e5,workerStateCollectionDelay:1e4,workerGrace:6e4,teardownGrace:5e3,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:p,wrapVarPrefix:v,functionInitFunctionName:`${v}i`,functionCatchFunctionName:`${v}c`,functionFinallyFunctionName:`${v}n`,callContextVarName:`${v}x`,fixStackFunctionName:`${v}s`,asyncIteratorWrapperFunctionName:`${v}w`,wrapperUserCatchFunctionName:`${v}u`,asyncWrapperFunctionName:`${v}a`,internalAsyncWrapperFunctionName:`${v}b`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",enableEsbuild:!0}],[l.join("express","lib","router","layer.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<5",patcher:"expressLayer",enableEsbuild:!0}],[l.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[l.join("express","lib","router","index.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<5",patcher:"expressRouter",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"expressRouterInRouter",enableEsbuild:!0}],[l.join("router","lib","layer.js"),{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"expressLayerInRouter",enableEsbuild:!0}],["@hapi/hapi",{framework:s.availableFrameworks.hapi,enable:!0,version:">=20.0.0 <22.0.0",patcher:"hapi"}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0 || ^3.0.0",patcher:"koa"}],["fastify",{framework:s.availableFrameworks.fastify,enable:!0,version:">=4.0.0 <6",patcher:"fastify"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/compiled/next-server/pages-api-turbo.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=16.0.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(l.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:">=7.5.0",patcher:"sqsConsumer"}],[["@mondaydotcomorg/monday-sqs-consumer","sqs-consumer"].join(l.sep),{framework:s.availableFrameworks.sqs,enable:"win32"!==process.platform,version:">=5.2.2 <6",patcher:"sqsConsumer",extraInfo:{isMondayVersion:!0,srcHash:"bd9064befbf3abb9ad0e6a53b0cf721d5612d5b8d8790875c994b7ff40b951c5"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[l.join("serverless-http","lib","framework","get-framework.js"),{framework:s.availableFrameworks.serverlessHttp,enable:!0,version:"^2.7.0",patcher:"serverlessHttp",enableEsbuild:!0}],["axios",{framework:s.availableFrameworks.axios,enable:!0,version:">0.18.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs",extraInfo:{isOutbound:!0}}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js",extraInfo:{isOutbound:!0}}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request",extraInfo:{isOutbound:!0}}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg",extraInfo:{isOutbound:!0}}],["@clickhouse/client-common",{framework:s.availableFrameworks.clickhouse,enable:!1,version:"^1.10.0",patcher:"outbound/clickhouse",extraInfo:{isOutbound:!0}}],["ioredis",{framework:s.availableFrameworks.ioredis,enable:!0,version:"^4.0.0 || ^5.0.0",patcher:"outbound/ioredis",extraInfo:{isOutbound:!0}}],["mongodb",{framework:s.availableFrameworks.mongodb,enable:!0,version:">=5.0.0 <8.0.0",patcher:"outbound/mongodb",extraInfo:{isOutbound:!0}}],["mongoose",{framework:s.availableFrameworks.mongoose,enable:!0,version:">=5.0.0 <7.0.0",patcher:"outbound/mongoose",extraInfo:{isOutbound:!0,coveredByFramework:{frameworkKey:"mongodb",versionRange:">=7.0.0 <10.0.0"}}}],["p-limit",{framework:"p-limit",enable:!0,version:"^3.0.0",patcher:"internal/pLimit"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,investigationErrorStatusCodeRegex:n.DEFAULT_INVESTIGATION_ERROR_STATUS_CODE_REGEX,enableInvestigationArgsSending:!1,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30,maxUniqueSetFailureErrors:100},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20,functionDetachEnabled:!1,functionDetachThresholdPerSecond:5833,enableMongoDocumentData:!1,enableTeardown:!1,flushOnUncaughtException:!1,fileTimestampsLogDelayMs:12e4,maxCustomFlowIds:1e3},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:"true"!==process.env.HUD_DISABLE_SUPPRESS_TRACES,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:c((0,u.v5)("axios",p)),nodeFetchFunctionId:c((0,u.v5)("node-fetch",p)),nodeFetchBodiesFunctionIds:{json:c((0,u.v5)("node-fetch-body-json",p)),text:c((0,u.v5)("node-fetch-body-text",p)),arrayBuffer:c((0,u.v5)("node-fetch-body-arrayBuffer",p)),blob:c((0,u.v5)("node-fetch-body-blob",p))},requestFunctionId:c((0,u.v5)("request-request",p)),requestMethodFunctionIds:{get:c((0,u.v5)("request-get",p)),head:c((0,u.v5)("request-head",p)),options:c((0,u.v5)("request-options",p)),post:c((0,u.v5)("request-post",p)),put:c((0,u.v5)("request-put",p)),patch:c((0,u.v5)("request-patch",p)),del:c((0,u.v5)("request-del",p)),delete:c((0,u.v5)("request-delete",p))},pgConnectFunctionId:c((0,u.v5)("pg-connect",p)),pgQueryFunctionId:c((0,u.v5)("pg-query",p)),pgEndFunctionId:c((0,u.v5)("pg-end",p)),clickhouseQueryFunctionId:c((0,u.v5)("clickhouse-query",p)),clickhouseExecFunctionId:c((0,u.v5)("clickhouse-exec",p)),clickhouseCommandFunctionId:c((0,u.v5)("clickhouse-command",p)),clickhouseInsertFunctionId:c((0,u.v5)("clickhouse-insert",p)),clickhouseCloseFunctionId:c((0,u.v5)("clickhouse-close",p)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[l.join(l.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildFunctionIdVar:"hudFI",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};n.hudConfig=function(e={}){return{...b,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),n.default=n.hudConfig;const f=process.env.HUD_DEBUG?n.hudConfig.logger.debug:n.hudConfig.logger.default;n.loggerConfig={...f,console:"true"===process.env.HUD_VERBOSE};class h extends Error{path;code;constructor(e,n){super(),this.path=e,this.code=n}}n.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SDK_VERSION=void 0,n.SDK_VERSION="1.8.13"},6928:e=>{e.exports=require("path")},7089:(e,n,t)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ObjectStoreConfigSchema=void 0;const i=t(1569),a=i.z.object({type:i.z.literal("s3")}),o=i.z.object({type:i.z.literal("disk"),path:i.z.string()}),r=i.z.object({type:i.z.literal("customer_s3"),bucket:i.z.string(),region:i.z.string(),prefix:i.z.string().optional()});n.ObjectStoreConfigSchema=i.z.union([a,o,r])},8528:e=>{e.exports=require("./dto")}},n={};return function t(i){var a=n[i];if(void 0!==a)return a.exports;var o=n[i]={exports:{}};return e[i].call(o.exports,o,o.exports,t),o.exports}(2509)})());
2
2
  //# sourceMappingURL=config.js.map
package/dist/cjs/core.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1427:e=>{e.exports=require("./nativerequire")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=o(n(523)),c=n(8528),d=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==c.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.updateTsNodeConfig=t.tryFlushPendingLogs=t.init=void 0;const a=o(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}}),Object.defineProperty(t,"updateTsNodeConfig",{enumerable:!0,get:function(){return a.updateTsNodeConfig}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const s=n(8167),r=n(2546),o=n(5809),a=n(8269),c=n(523),d=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&c.customer_logger.logEntry(r.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;lifecycleHooksRegistered=!1;teardownInFlight;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof r.HudSessionThrottle?(c.customer_logger.logEntry(r.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof r.HudInitNetworkError&&e.originalAxiosErrorCode?(c.customer_logger.logEntry((0,r.getNetworkError)(e.originalAxiosErrorCode)),c.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(c.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,r.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,r.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),this.registerLifecycleTeardown(),c.customer_logger.logEntry(r.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(s.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();c.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,r.next)(e).then(async()=>{c.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{c.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new r.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(o.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),o.hudConfig.dynamicConfig.functionDetachEnabled&&!o.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,d.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,o.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof r.HudSessionThrottle)throw e;throw c.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=r.myRequire.resolve(`${o.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new s.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:o.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(o.hudConfig.workerTimeout)}catch(e){if(e instanceof r.HudSessionThrottle)throw c.app_logger.info("Worker started in idle mode - session throttled"),e;throw c.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(c.app_logger.info("Remote configuration exists"),o.hudConfig.dynamicConfig=(0,o.updateDynamicConfig)(e,o.hudConfig,c.app_logger),(0,o.updateInvestigationRateLimitGlobals)(),c.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:o.hudConfig.dynamicConfig})):c.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:o.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}registerLifecycleTeardown(){if(this.lifecycleHooksRegistered)return;if(this.lifecycleHooksRegistered=!0,globalThis.hudRuningInsideLambda)return;const e=o.hudConfig.dynamicConfig.enableTeardown||o.hudConfig.userConfig.flushOnExit?.value,t=o.hudConfig.userConfig.flushOnUncaughtException?.value||o.hudConfig.dynamicConfig.flushOnUncaughtException;if(!e&&!t)return;const n=async()=>{try{if(this.teardownInFlight)return void await this.teardownInFlight;this.teardownInFlight=this.gracefulShutdown(),await this.teardownInFlight}catch{}};e&&(process.once("beforeExit",()=>{n()}),process.prependOnceListener("SIGTERM",async()=>{const e=process.listenerCount("SIGTERM")>0;try{await n()}catch{}e||process.kill(process.pid,"SIGTERM")}),process.prependOnceListener("SIGINT",async()=>{const e=process.listenerCount("SIGINT")>0;try{await n()}catch{}e||process.kill(process.pid,"SIGINT")})),t&&(process.prependOnceListener("uncaughtException",e=>{const t=process.listenerCount("uncaughtException")>0;(async()=>{try{await n()}catch{}if(!t)throw e})()}),process.prependOnceListener("unhandledRejection",e=>{const t=process.listenerCount("unhandledRejection")>0;(async()=>{try{await n()}catch{}if(!t)throw e})()}))}async gracefulShutdown(){if(this.messenger){try{await this.messenger.gracefulShutdown()}catch{}this.messenger=void 0,(0,a.detachHud)(!1,!1)}}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void s.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,c.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,c.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void s.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(s.app_logger.info("Initializing hud",{userConfig:Object.entries(o.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new r.MainThread(g.apiKey,g.service,globalThis.hudStartTime,o.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,d.safeCall)(s.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;s.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof d.HudSessionThrottle)return;s.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{s.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.updateTsNodeConfig=function(){try{return!!l?.messenger&&l.messenger.updateTsNodeConfig()}catch(e){return s.app_logger.error("Failed to update ts-node config",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),!1}},t.tryFlushPendingLogs=async function(e,t){(0,c.getShouldFlushOnInit)()&&((0,c.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),s=n(523),r=n(5994),o=n(5809),a=n(8528),c=n(8269),d=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,c.detachHud)(e,t),n&&(0,d.safeCall)(s.app_logger,f()),l&&(0,d.safeCall)(s.app_logger,l.terminateMessenger());const r=(0,c.getLambdaExtensionId)();r&&!u&&(u=!0,(0,d.safeCall)(s.app_logger,(0,i.nextLoopDummy)(r))),(0,c.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,c.getSessionInfo)(),r=(0,c.getStoredApiKey)(),o=(0,c.getStoredService)();try{const a=e||r;if(!a||"string"!=typeof a)return;const c=t||o||"unknown",d=(0,s.getSavedLogs)();for(const e of d){const{HudClient:t}=n(4672),r=new t;i?(s.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:c}),r.setSession(i),await r.logs(e)):(s.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:c}),await r.sessionslessLogs(e,a)),s.app_logger.info("Successfully flushed logs")}}catch(e){try{s.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=c,t.getLastPrepCallsTimestamp=function(){return a},t._liftExceptions=g,t.prepCalls=function(e,t){const n=process.hrtime.bigint();let d;d=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(n-a)/1e6,c(n);let l=null;i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&(l=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(d/1e3));const u=(new Date).toISOString(),h=[];return Object.entries(hudCalls).map(([n,s])=>{const a=s.shouldDetach;let c=0;var d;Object.entries(s).forEach(([s,o])=>{"shouldDetach"!==s&&Object.entries(o).forEach(([o,d])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||a||(c+=d.count),0===d.sampledCount)return;const r={function_id:n,wrapped_flow_id:o||void 0,wrapped_caller_id:s||void 0,timestamp:u,timeslice:e,exceptions:g(d.exceptions),count:d.count,sampled_count:d.sampledCount,sum_duration:d.sum,sum_squared_duration:d.squareSum,sketch:d.sketch?t.encode(d.sketch):void 0,is_linked_function:d.isLinkedFunction};h.push(r),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(d)}catch(e){r.app_logger.error("Failed preparing invocation, skipping",{func:n,wrappedCaller:s,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==l&&c>l&&(hudCalls[n].shouldDetach=!0,d=n,o.push(d),r.app_logger.info("Detaching function",{func:n,totalFunctionCalls:c}))}),h.length>0&&(0,s.clearMetricsIndicator)(),h},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])d(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=o;return o=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(r.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){r.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),s=n(8269),r=n(523);let o=[],a=null;function c(e){a=e}function d(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(523)),c=o(n(6460)),d=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),w=n(8269),C=n(1427),y=n(6281),k=n(8269),b=n(2546),E=n(6261),T=a.app_logger,_=m.safeCall.bind(m.safeCall,T);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;gracefulShutdownDone=!1;threadStatsBaseline=(0,g.createThreadStatsBaseline)();abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,T.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this.updateTsNodeConfig()&&T.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),T.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,y._detachAndTerminate)(!0,!1,!0)}catch(e){T.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){try{this.abortWorker()}catch{}d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),T.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw T.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:T.info("Enabled mode"),_(this.getMode()),_(this.periodicGetEndpointsDurationsInvestigationThresholds()),_(this.periodicRefreshRemoteConfig()),_(this.startPeriodicTasks()),_(this.periodicSendMetrics()),_(this.periodicSendDetachedFunctions()),_(this.periodicFetchKnownDetachedFunctions()),_(this.highFrequencySendInvestigations()),_(this.periodicSendProcessedFiles()),_(this.delayedStateCollection()),_(this.periodicSendEndpoints()),_(this.periodicSendOutbounds()),_(this.periodicSendKafkaJS()),_(this.periodicSendSqs()),_(this.periodicSendGraphQL()),_(this.periodicSendCustomFlowDeclarations()),_(this.sendStaticNextJsEndpointsOnce()),_(this.periodicSaveMachineMetrics()),_(this.periodicSendReingest()),_(this.resetCallerCounters()),_(this.periodicResetGlobalInvestigationCounter()),_(this.periodicResetInvestigationDedupingCache()),_(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),_(this.sendRuntime()),_(this.sendPatchedModules()),_(this.sendPreloadedModules()),_(this.dumpModulesAfterWhile(6e4)),_(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:T.info("Disabled mode"),_(this.getMode());break;case l.HudRunningMode.detached:T.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:T.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let s;e=Array.isArray(e)?e:[e];const r=this.consumeMessageFromQueue(e);if(r)return T.info("Found message in queue",{msg:r.msg}),r;const o=new AbortController,a=()=>{o.abort()};this.abortController.signal.addEventListener("abort",a);const d=c.setTimeout(t,void 0,{signal:o.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(s=t,o.abort(),this.consumeMessageFromQueue([t.msg]),T.info("Received message from worker (canceling timeout)",t))}catch(e){T.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await d,T.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return s}async getMode(){await(0,u.safeUnrefInterval)(async()=>{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,d.hudConfig.workerMessageTimeout,!1,e);t?.msg===e.msg&&void 0!==t?.content.mode?t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode):T.error("Unexpected message from worker",t)},d.hudConfig.modeInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed getting mode from worker",{msg:e.message,stack:e.stack})})}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){T.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return T.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)(),await(0,u.safeUnrefInterval)(()=>(0,f.saveMachineMetric)(),d.hudConfig.dynamicConfig.machineMetricsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed saving machine metrics",{msg:e.message,stack:e.stack})})}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting caller",{interval:e}),(0,p.resetCallers)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed reseting caller counters",{msg:e.message,stack:e.stack})})}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),T.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){T.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds(),await(0,u.safeUnrefInterval)(()=>this.updateEndpointDurationsInvestigationThresholds(),d.hudConfig.endpointsDurationsInvestigationThresholdsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed updating endpoints durations investigation thresholds",{msg:e.message,stack:e.stack})})}async updateRefreshRemoteConfig(){const e="RefreshRemoteConfig",t={msg:"RefreshRemoteConfig"};try{const n=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!1,t);if(n?.msg!==e||void 0===n?.content)return;(0,d.refreshInvestigationEnabled)(n.content,d.hudConfig,T),(0,d.refreshInvestigationErrorStatusCodeRegex)(n.content,d.hudConfig,T)}catch(e){T.error("Failed refreshing remote config from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicRefreshRemoteConfig(){await(0,u.safeUnrefInterval)(()=>this.updateRefreshRemoteConfig(),d.hudConfig.remoteConfigRefreshInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed refreshing remote config",{msg:e.message,stack:e.stack})})}async delayedStateCollection(){await this.setupPeriodicTask(0,d.hudConfig.workerStateCollectionDelay,()=>{try{this.updateTsNodeConfig()&&T.info("ts-node config updated from delayed task")}catch(e){T.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollection",2)}sendProcessedFiles(){const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();this._sendArray("ProcessedFiles",e)}sendKafkaTopics(){const e=(0,w.getKafkaJSTopics)();this._sendArray("KafkaJSTopics",e)}sendSqsQueues(){const e=(0,w.getSqsQueues)();e.length>0&&this._sendArray("SqsQueue",e)}sendGraphQLOperations(){const e=Object.values((0,w.getGraphQLOperations)());e.length>0&&this._sendArray("GraphQLDeclaration",e)}sendCustomFlowDeclarations(){const e=(0,w.getCustomFlowDeclarations)();e.length>0&&this._sendArray("CustomFlowDeclaration",e)}sendInvocations(e,t){const n=(0,p.prepCalls)(e,t);n.length>0&&this._sendArray("Invocations",n)}sendFlowMetrics(e){const t=(0,f.getFlowMetrics)(e);Object.keys(t).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:t})}sendThreadPerformanceMetrics(){const e=(0,m.collectThreadPerformance)(this.threadStatsBaseline,T,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}sendStaticNextJsEndpointsIfReady(){return!(!(0,g.isNextJsApp)()||!(0,w.isNextConfigExtracted)()||this.staticNextJsEndpointsSent||(this.staticNextJsEndpointsSent=!0,this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify((0,w.getNextConfig)())}),0))}async periodicSendProcessedFiles(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendProcessedFiles(),!0),"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendKafkaTopics(),!0),"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendSqsQueues(),!0),"periodicSendSqs")}async periodicSendGraphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGraphQLOperations(),!0),"periodicSendGraphQL")}async periodicSendCustomFlowDeclarations(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendCustomFlowDeclarations(),!0),"periodicSendCustomFlowDeclarations")}async periodicSendMetrics(){const e=new h.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){T.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{this.sendInvocations(t,e)}catch(e){T.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{this.sendFlowMetrics(t)}catch(e){T.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!d.hudConfig.dynamicConfig.functionDetachEnabled||d.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){T.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){T.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){d.hudConfig.dynamicConfig.functionDetachEnabled&&!d.hudConfig.userConfig.disableDetachedFunctions?.value&&await(0,u.safeUnrefInterval)(()=>this.fetchKnownDetachedFunctions(),d.hudConfig.dynamicConfig.aggregationInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed fetching known detached functions",{msg:e.message,stack:e.stack})})}async highFrequencySendInvestigations(){if(!d.hudConfig.dynamicConfig.enableInvestigation)return;const e=d.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=d.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}sendEndpoints(){(0,f.collectExpressEndpointDeclarations)();const e=(0,f.getEndpointDeclarationsFromStorage)();e.length>0&&this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,k.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,k.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}flushAllPendingData(){const e=(0,p.getLastPrepCallsTimestamp)(),t=null===e?d.hudConfig.dynamicConfig.aggregationInterval:Number(process.hrtime.bigint()-e)/1e6,n=Math.max(1,t),i=new h.SketchManager(d.hudConfig.huddBinWidth),s=[{label:"investigations",fn:()=>this.refreshInvestigations()},{label:"invocations",fn:()=>this.sendInvocations(n,i)},{label:"flow metrics",fn:()=>this.sendFlowMetrics(n)},{label:"processed files",fn:()=>this.sendProcessedFiles()},{label:"endpoints",fn:()=>{this.sendEndpoints(),this.sendOutbounds()}},{label:"Kafka topics",fn:()=>this.sendKafkaTopics()},{label:"SQS queues",fn:()=>this.sendSqsQueues()},{label:"GraphQL declarations",fn:()=>this.sendGraphQLOperations()},{label:"custom flow declarations",fn:()=>this.sendCustomFlowDeclarations()},{label:"static Next.js endpoints",fn:()=>{this.sendStaticNextJsEndpointsIfReady()}},{label:"thread performance metrics",fn:()=>this.sendThreadPerformanceMetrics()}];for(const e of s)try{e.fn()}catch(t){T.error(`Failed flushing ${e.label}`,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}}async sendTerminateAndAwait(e){const t=a.getSavedLogs();try{await this.getMessageFromWorker("terminated",e.grace,e.shouldRef,{msg:"Terminate",content:{grace:e.grace,logBuffers:t}})}catch(t){t instanceof m.HudTimeoutError?(T.critical(e.timeoutLogMsg,{error:t.message}),await this.worker.terminate()):(T.critical(e.unexpectedLogMsg,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),await this.worker.terminate())}}async gracefulShutdown(){if(!this.gracefulShutdownDone){this.gracefulShutdownDone=!0;try{this.abortController.abort(),this.abortController=new AbortController,d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.worker.ref(),this.flushAllPendingData(),await this.sendTerminateAndAwait({grace:d.hudConfig.teardownGrace,shouldRef:!0,timeoutLogMsg:"Teardown grace timeout - terminating worker",unexpectedLogMsg:"Unexpected error during SDK graceful shutdown"})}finally{try{this.worker.unref()}catch{}this.stop()}}}async terminateWorker(){await this.sendTerminateAndAwait({grace:d.hudConfig.workerGrace,shouldRef:!1,timeoutLogMsg:"Grace period timeout - terminating worker",unexpectedLogMsg:"Unexpected error during worker termination"}),T.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):T.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=d.hudConfig.dynamicConfig.performanceMetricsInterval;await(0,u.safeUnrefInterval)(()=>this.sendThreadPerformanceMetrics(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending thread performance metrics",{msg:e.message,stack:e.stack})})}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(C.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void T.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){await(0,u.safeUnrefInterval)(()=>this.handleLogsTask(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending logs periodically",{msg:e.message,stack:e.stack})})}async setupPeriodicTask(e,t,n,i,s=0){function r(e){let t=!0;try{t=n(e)}catch(e){T.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),!r(e))return void T.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i});if(1===s)return;let o=s>0?s-1:0;await(0,u.safeUnrefInterval)(e=>{if(!r(t))return T.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i}),void e();o>0&&0===--o&&e()},t,{signal:this.abortController.signal,onError:e=>T.error("Failed in periodic task interval",{taskName:i,msg:e.message,stack:e.stack})})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting global investigation counter",{msg:e.message,stack:e.stack})})}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)(),(0,f.getUniqueSetFailureErrors)().clear()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting investigation deduping cache",{msg:e.message,stack:e.stack})})}updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,T.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=d.hudConfig.staticNextJsEndpointsInterval,t=d.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;await(0,u.safeUnrefInterval)(e=>{if(n++,T.debug("Attempting to send static next.js endpoints",{attemptCount:n}),this.sendStaticNextJsEndpointsIfReady())return T.info("Sent static next.js endpoints"),void e();n>t&&(T.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:n}),e())},e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending static next.js endpoints",{msg:e.message,stack:e.stack})})}async periodicSendReingest(){await(0,u.safeUnrefInterval)(()=>{const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))},d.hudConfig.dynamicConfig.reingestInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed sending reingest",{msg:e.message,stack:e.stack})})}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}return n.c=t,n(n.s=5119)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1427:e=>{e.exports=require("./nativerequire")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=o(n(523)),c=n(8528),d=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==c.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){d.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.updateTsNodeConfig=t.tryFlushPendingLogs=t.init=void 0;const a=o(n(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}}),Object.defineProperty(t,"updateTsNodeConfig",{enumerable:!0,get:function(){return a.updateTsNodeConfig}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const s=n(8167),r=n(2546),o=n(5809),a=n(8269),c=n(523),d=n(7274),g=n(6281),l=i(n(7320));function u(){globalThis.hudInstrumentationOccured&&c.customer_logger.logEntry(r.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;lifecycleHooksRegistered=!1;teardownInFlight;constructor(e,t,n,i){this.apiKey=e,this.service=t,this.startTime=n,this.tags=i,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof r.HudSessionThrottle?(c.customer_logger.logEntry(r.UserLogs.InitIdleMode()),(0,g._detachAndTerminate)(!1,!1,!0)):e instanceof r.HudInitNetworkError&&e.originalAxiosErrorCode?(c.customer_logger.logEntry((0,r.getNetworkError)(e.originalAxiosErrorCode)),c.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,g._detachAndTerminate)(!1,!1,!0)):(c.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,r.setFirstError)(e.code),(0,g._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,r.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),this.registerLifecycleTeardown(),c.customer_logger.logEntry(r.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(s.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();c.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,r.next)(e).then(async()=>{c.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{c.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new r.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(o.hudConfig.workerTimeout),t=e?.content?.sessionInfo;if(t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),o.hudConfig.dynamicConfig.functionDetachEnabled&&!o.hudConfig.userConfig.disableDetachedFunctions?.value){const e=await(this.messenger?.getKnownDetachedFunctions(!0));e&&(0,d.applyKnownDetachedFunctions)(e)}globalThis.hudMetricsIndicator=setTimeout(u,o.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof r.HudSessionThrottle)throw e;throw c.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=r.myRequire.resolve(`${o.SDK_MODULE_NAME}/worker`),n={...process.env};delete n.NODE_OPTIONS;const i=new s.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:o.hudConfig.userConfig},execArgv:[],env:n});let a;try{a=new l.default(i),await a.checkWorker(o.hudConfig.workerTimeout)}catch(e){if(e instanceof r.HudSessionThrottle)throw c.app_logger.info("Worker started in idle mode - session throttled"),e;throw c.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{i.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(c.app_logger.info("Remote configuration exists"),o.hudConfig.dynamicConfig=(0,o.updateDynamicConfig)(e,o.hudConfig,c.app_logger),(0,o.updateInvestigationRateLimitGlobals)(),c.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:o.hudConfig.dynamicConfig})):c.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:o.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}registerLifecycleTeardown(){if(this.lifecycleHooksRegistered)return;if(this.lifecycleHooksRegistered=!0,globalThis.hudRuningInsideLambda)return;const e=o.hudConfig.dynamicConfig.enableTeardown||o.hudConfig.userConfig.flushOnExit?.value,t=o.hudConfig.userConfig.flushOnUncaughtException?.value||o.hudConfig.dynamicConfig.flushOnUncaughtException;if(!e&&!t)return;const n=async()=>{try{if(this.teardownInFlight)return void await this.teardownInFlight;this.teardownInFlight=this.gracefulShutdown(),await this.teardownInFlight}catch{}};e&&(process.once("beforeExit",()=>{n()}),process.prependOnceListener("SIGTERM",async()=>{const e=process.listenerCount("SIGTERM")>0;try{await n()}catch{}e||process.kill(process.pid,"SIGTERM")}),process.prependOnceListener("SIGINT",async()=>{const e=process.listenerCount("SIGINT")>0;try{await n()}catch{}e||process.kill(process.pid,"SIGINT")})),t&&(process.prependOnceListener("uncaughtException",e=>{const t=process.listenerCount("uncaughtException")>0;(async()=>{try{await n()}catch{}if(!t)throw e})()}),process.prependOnceListener("unhandledRejection",e=>{const t=process.listenerCount("unhandledRejection")>0;(async()=>{try{await n()}catch{}if(!t)throw e})()}))}async gracefulShutdown(){if(this.messenger){try{await this.messenger.gracefulShutdown()}catch{}this.messenger=void 0,(0,a.detachHud)(!1,!1)}}}},6261:e=>{e.exports=require("events")},6281:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,n){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void s.app_logger.warning("Already ran init!");globalThis.hudRunMutex=!0,(0,c.clearInitGuard)(),(0,i.updateUserConfigFromInit)(e,t,n);const g=(0,c.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void s.app_logger.critical("SDK running mode is not enabled - initialization aborted");if((0,i.setForensicsOnly)(!0===o.hudConfig.userConfig.forensicsOnly?.value),(0,i.isForensicsOnly)()&&((0,i.applyForensicsOnlyLogFloor)(),s.app_logger.info("SDK running in forensics-only mode")),s.app_logger.info("Initializing hud",{userConfig:Object.entries(o.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new r.MainThread(g.apiKey,g.service,globalThis.hudStartTime,o.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,d.safeCall)(s.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;s.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof d.HudSessionThrottle)return;s.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{s.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.updateTsNodeConfig=function(){try{return!!l?.messenger&&l.messenger.updateTsNodeConfig()}catch(e){return s.app_logger.error("Failed to update ts-node config",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),!1}},t.tryFlushPendingLogs=async function(e,t){(0,c.getShouldFlushOnInit)()&&((0,c.markShouldFlushOnInit)(!1),await f(e,t))};const i=n(2546),s=n(523),r=n(5994),o=n(5809),a=n(8528),c=n(8269),d=n(2546),g=n(7274);let l,u=!1;function h(e=!0,t=!1,n=!1){(0,c.detachHud)(e,t),n&&(0,d.safeCall)(s.app_logger,f()),l&&(0,d.safeCall)(s.app_logger,l.terminateMessenger());const r=(0,c.getLambdaExtensionId)();r&&!u&&(u=!0,(0,d.safeCall)(s.app_logger,(0,i.nextLoopDummy)(r))),(0,c.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const i=(0,c.getSessionInfo)(),r=(0,c.getStoredApiKey)(),o=(0,c.getStoredService)();try{const a=e||r;if(!a||"string"!=typeof a)return;const c=t||o||"unknown",d=(0,s.getSavedLogs)();for(const e of d){const{HudClient:t}=n(4672),r=new t;i?(s.app_logger.info("Flushing logs with session",{size:e.length,sessionId:i.sessionId,service:c}),r.setSession(i),await r.logs(e)):(s.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:c}),await r.sessionslessLogs(e,a)),s.app_logger.info("Successfully flushed logs")}}catch(e){try{s.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==i})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._setLastPrepCallsTimestamp=c,t.getLastPrepCallsTimestamp=function(){return a},t._liftExceptions=g,t.prepCalls=function(e,t){const n=process.hrtime.bigint();let d;d=null===a?i.hudConfig.dynamicConfig.aggregationInterval:Number(n-a)/1e6,c(n);let l=null;i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&(l=i.hudConfig.dynamicConfig.functionDetachThresholdPerSecond*(d/1e3));const u=(new Date).toISOString(),h=[];return Object.entries(hudCalls).map(([n,s])=>{const a=s.shouldDetach;let c=0;var d;Object.entries(s).forEach(([s,o])=>{"shouldDetach"!==s&&Object.entries(o).forEach(([o,d])=>{try{if(!i.hudConfig.dynamicConfig.functionDetachEnabled||i.hudConfig.userConfig.disableDetachedFunctions?.value||a||(c+=d.count),0===d.sampledCount)return;const r={function_id:n,wrapped_flow_id:o||void 0,wrapped_caller_id:s||void 0,timestamp:u,timeslice:e,exceptions:g(d.exceptions),count:d.count,sampled_count:d.sampledCount,sum_duration:d.sum,sum_squared_duration:d.squareSum,sketch:d.sketch?t.encode(d.sketch):void 0,is_linked_function:d.isLinkedFunction};h.push(r),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(d)}catch(e){r.app_logger.error("Failed preparing invocation, skipping",{func:n,wrappedCaller:s,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})}),i.hudConfig.dynamicConfig.functionDetachEnabled&&!i.hudConfig.userConfig.disableDetachedFunctions?.value&&null!==l&&c>l&&(hudCalls[n].shouldDetach=!0,d=n,o.push(d),r.app_logger.info("Detaching function",{func:n,totalFunctionCalls:c}))}),h.length>0&&(0,s.clearMetricsIndicator)(),h},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])if("shouldDetach"!==t)for(const n in globalThis.hudCalls[e][t])d(globalThis.hudCalls[e][t][n])},t.getAndClearDetachedFunctions=function(){const e=o;return o=[],e},t.applyKnownDetachedFunctions=function(e){if(e&&0!==e.length&&!i.hudConfig.userConfig.disableDetachedFunctions?.value){l!==e.length&&(r.app_logger.info("Applying known detached functions from host",{count:e.length}),l=e.length);for(const t of e)try{globalThis.hudCalls[t]?globalThis.hudCalls[t].shouldDetach=!0:globalThis.hudCalls[t]={shouldDetach:!0}}catch(e){r.app_logger.error("Failed to apply detached function, skipping",{rawFunctionId:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}};const i=n(5809),s=n(8269),r=n(523);let o=[],a=null;function c(e){a=e}function d(e){e.samplingCounter=0}function g(e){const t={};for(const n in e)t[n]=[{count:e[n]}];return t}let l=0},7320:function(e,t,n){var i,s=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),o=0;o<n.length;o++)"default"!==n[o]&&s(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=o(n(523)),c=o(n(6460)),d=n(5809),g=n(2546),l=n(8528),u=n(2546),h=n(7131),f=n(8269),m=n(2546),p=n(7274),v=n(2702),y=n(8269),C=n(1427),w=n(6281),k=n(8269),b=n(2546),E=n(6261),T=a.app_logger,F=m.safeCall.bind(m.safeCall,T);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;gracefulShutdownDone=!1;threadStatsBaseline=(0,g.createThreadStatsBaseline)();abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new E.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,E.setMaxListeners)(25,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,T.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,d.hudConfig.communicationKeepaliveGrace),this.updateTsNodeConfig()&&T.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.logEntry(m.UserErrorLogs.ApiKeyDenied(d.hudConfig.userConfig.key?.source)),T.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,w._detachAndTerminate)(!0,!1,!0)}catch(e){T.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){try{this.abortWorker()}catch{}d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),T.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const n={msg:e,content:t};this.worker.postMessage(n)}async checkWorker(e){const t=["started"];let n;try{n=await this.getMessageFromWorker(t,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;n=await this.getMessageFromWorker(t,e/2,!1)}if(!n)throw new m.HudInitError("Worker not started");return n}async checkWorkerInitialized(e){let t;const n=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(n,e,!0)}catch(i){if(!(i instanceof m.HudTimeoutError))throw i;t=await this.getMessageFromWorker(n,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw T.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:T.info("Enabled mode"),(0,u.applyForensicsDeclarationDelay)(),F(this.getMode()),F(this.periodicGetEndpointsDurationsInvestigationThresholds()),F(this.periodicRefreshRemoteConfig()),F(this.startPeriodicTasks()),F(this.periodicSendMetrics()),F(this.periodicSendDetachedFunctions()),F(this.periodicFetchKnownDetachedFunctions()),F(this.highFrequencySendInvestigations()),F(this.periodicSendProcessedFiles()),F(this.delayedStateCollection()),F(this.periodicSendEndpoints()),F(this.periodicSendOutbounds()),F(this.periodicSendKafkaJS()),F(this.periodicSendSqs()),F(this.periodicSendGraphQL()),F(this.periodicSendGenericDeclarations()),F(this.periodicSendCustomFlowDeclarations()),F(this.sendStaticNextJsEndpointsOnce()),F(this.periodicSaveMachineMetrics()),F(this.periodicSendReingest()),F(this.resetCallerCounters()),F(this.periodicResetGlobalInvestigationCounter()),F(this.periodicResetInvestigationDedupingCache()),F(this.sendLogsPeriodically(d.hudConfig.logsSendInterval)),F(this.sendRuntime()),F(this.sendPatchedModules()),F(this.sendPreloadedModules()),F(this.dumpModulesAfterWhile(6e4)),F(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:T.info("Disabled mode"),F(this.getMode());break;case l.HudRunningMode.detached:T.info("Detached"),(0,w._detachAndTerminate)(!1,!1),this.stop();break;default:T.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,n=!1,i){let s;e=Array.isArray(e)?e:[e];const r=this.consumeMessageFromQueue(e);if(r)return T.info("Found message in queue",{msg:r.msg}),r;const o=new AbortController,a=()=>{o.abort()};this.abortController.signal.addEventListener("abort",a);const d=c.setTimeout(t,void 0,{signal:o.signal,ref:n}),g=t=>{try{e.includes(t.msg)&&(s=t,o.abort(),this.consumeMessageFromQueue([t.msg]),T.info("Received message from worker (canceling timeout)",t))}catch(e){T.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),i&&this.worker.postMessage(i);try{throw await d,T.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return s}async getMode(){await(0,u.safeUnrefInterval)(async()=>{const e=globalThis.hudRunningMode,t={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:e}},n=await this.getMessageFromWorker(t.msg,d.hudConfig.workerMessageTimeout,!1,t);if(n?.msg!==t.msg||void 0===n?.content.mode)return void T.error("Unexpected message from worker",n);let i=n.content.mode;i===l.HudRunningMode.reservedForForensicsOnlyDontUse&&((0,u.isForensicsOnly)()||((0,u.setForensicsOnly)(!0),(0,u.applyForensicsOnlyLogFloor)()),i=l.HudRunningMode.enabled),i!==e&&await this.restart(i)},d.hudConfig.modeInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed getting mode from worker",{msg:e.message,stack:e.stack})})}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){T.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getKnownDetachedFunctions(e=!1){const t="KnownDetachedFunctions",n={msg:"GetKnownDetachedFunctions",content:{}};try{const i=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,e,n);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);return i?.content}catch(e){return T.error("Failed getting known detached functions from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)(),await(0,u.safeUnrefInterval)(()=>(0,f.saveMachineMetric)(),d.hudConfig.dynamicConfig.machineMetricsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed saving machine metrics",{msg:e.message,stack:e.stack})})}async resetCallerCounters(){const e=d.hudConfig.callerResetInterval;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting caller",{interval:e}),(0,p.resetCallers)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed reseting caller counters",{msg:e.message,stack:e.stack})})}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const n=await this.getMessageFromWorker(t,d.hudConfig.workerMessageTimeout,!1,e);if(n?.msg!==t||void 0===n?.content)throw new Error(`Unexpected message from worker: ${n}`);(0,f.setInvestigationDurationThresholds)(n?.content),T.debug("Endpoints durations investigation thresholds updated",{thresholds:n?.content})}catch(e){T.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds(),await(0,u.safeUnrefInterval)(()=>this.updateEndpointDurationsInvestigationThresholds(),d.hudConfig.endpointsDurationsInvestigationThresholdsInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed updating endpoints durations investigation thresholds",{msg:e.message,stack:e.stack})})}async updateRefreshRemoteConfig(){const e="RefreshRemoteConfig",t={msg:"RefreshRemoteConfig"};try{const n=await this.getMessageFromWorker(e,d.hudConfig.workerMessageTimeout,!1,t);if(n?.msg!==e||void 0===n?.content)return;(0,d.refreshInvestigationEnabled)(n.content,d.hudConfig,T),(0,d.refreshInvestigationErrorStatusCodeRegex)(n.content,d.hudConfig,T)}catch(e){T.error("Failed refreshing remote config from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicRefreshRemoteConfig(){await(0,u.safeUnrefInterval)(()=>this.updateRefreshRemoteConfig(),d.hudConfig.remoteConfigRefreshInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed refreshing remote config",{msg:e.message,stack:e.stack})})}async delayedStateCollection(){await this.setupPeriodicTask(0,d.hudConfig.workerStateCollectionDelay,()=>{try{this.updateTsNodeConfig()&&T.info("ts-node config updated from delayed task")}catch(e){T.error("Failed collecting state from delayed task",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"delayedStateCollection",2)}sendProcessedFiles(){const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();this._sendArray("ProcessedFiles",e)}sendKafkaTopics(){const e=(0,y.getKafkaJSTopics)();this._sendArray("KafkaJSTopics",e)}sendSqsQueues(){const e=(0,y.getSqsQueues)();e.length>0&&this._sendArray("SqsQueue",e)}sendGenericDeclarations(){const e=(0,y.getGenericDeclarationsFromStorage)();e.length>0&&this._sendArray("GenericFlowDeclaration",e)}sendGraphQLOperations(){const e=Object.values((0,y.getGraphQLOperations)());e.length>0&&this._sendArray("GraphQLDeclaration",e)}sendCustomFlowDeclarations(){const e=(0,y.getCustomFlowDeclarations)();e.length>0&&this._sendArray("CustomFlowDeclaration",e)}sendInvocations(e,t){const n=(0,p.prepCalls)(e,t);n.length>0&&this._sendArray("Invocations",n)}sendFlowMetrics(e){const t=(0,f.getFlowMetrics)(e);Object.keys(t).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:t})}sendThreadPerformanceMetrics(){const e=(0,m.collectThreadPerformance)(this.threadStatsBaseline,T,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}sendStaticNextJsEndpointsIfReady(){return!(!(0,g.isNextJsApp)()||!(0,y.isNextConfigExtracted)()||this.staticNextJsEndpointsSent||(this.staticNextJsEndpointsSent=!0,this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify((0,y.getNextConfig)())}),0))}async periodicSendProcessedFiles(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendProcessedFiles(),!0),"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendKafkaTopics(),!0),"periodicSendKafkaJS")}async periodicSendSqs(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendSqsQueues(),!0),"periodicSendSqs")}async periodicSendGraphQL(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGraphQLOperations(),!0),"periodicSendGraphQL")}async periodicSendGenericDeclarations(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendGenericDeclarations(),!0),"periodicSendGenericDeclarations")}async periodicSendCustomFlowDeclarations(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendCustomFlowDeclarations(),!0),"periodicSendCustomFlowDeclarations")}async periodicSendMetrics(){const e=new h.SketchManager(d.hudConfig.huddBinWidth),t=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,n=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,n,t=>{try{this.refreshInvestigations()}catch(e){T.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}const n=(0,u.isForensicsOnly)();try{const i=(0,p.prepCalls)(t,e);!n&&i.length>0&&this._sendArray("Invocations",i)}catch(e){T.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);!n&&Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){T.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async periodicSendDetachedFunctions(){if(!d.hudConfig.dynamicConfig.functionDetachEnabled||d.hudConfig.userConfig.disableDetachedFunctions?.value)return;const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{try{const e=(0,p.getAndClearDetachedFunctions)();e.length>0&&this._sendArray("DetachedFunctions",e)}catch(e){T.error("Failed sending detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendDetachedFunctions")}async fetchKnownDetachedFunctions(){try{const e=await this.getKnownDetachedFunctions();e&&e.length>0&&(0,p.applyKnownDetachedFunctions)(e)}catch(e){T.error("Failed fetching known detached functions",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicFetchKnownDetachedFunctions(){d.hudConfig.dynamicConfig.functionDetachEnabled&&!d.hudConfig.userConfig.disableDetachedFunctions?.value&&await(0,u.safeUnrefInterval)(()=>this.fetchKnownDetachedFunctions(),d.hudConfig.dynamicConfig.aggregationInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed fetching known detached functions",{msg:e.message,stack:e.stack})})}async highFrequencySendInvestigations(){if(!d.hudConfig.dynamicConfig.enableInvestigation)return;const e=d.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=d.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,y.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=d.hudConfig.endpointsFirstSendWaitTime,t=d.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=d.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=d.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}sendEndpoints(){(0,f.collectExpressEndpointDeclarations)();const e=(0,f.getEndpointDeclarationsFromStorage)();e.length>0&&this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,k.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e);const t=(0,k.getIoredisCommandsFromStorage)();t.length>0&&this._sendArray("IoredisCommands",t)}flushAllPendingData(){const e=(0,p.getLastPrepCallsTimestamp)(),t=null===e?d.hudConfig.dynamicConfig.aggregationInterval:Number(process.hrtime.bigint()-e)/1e6,n=Math.max(1,t),i=new h.SketchManager(d.hudConfig.huddBinWidth),s=[{label:"investigations",fn:()=>this.refreshInvestigations()},{label:"invocations",fn:()=>this.sendInvocations(n,i)},{label:"flow metrics",fn:()=>this.sendFlowMetrics(n)},{label:"processed files",fn:()=>this.sendProcessedFiles()},{label:"endpoints",fn:()=>{this.sendEndpoints(),this.sendOutbounds()}},{label:"Kafka topics",fn:()=>this.sendKafkaTopics()},{label:"SQS queues",fn:()=>this.sendSqsQueues()},{label:"Generic declarations",fn:()=>this.sendGenericDeclarations()},{label:"GraphQL declarations",fn:()=>this.sendGraphQLOperations()},{label:"custom flow declarations",fn:()=>this.sendCustomFlowDeclarations()},{label:"static Next.js endpoints",fn:()=>{this.sendStaticNextJsEndpointsIfReady()}},{label:"thread performance metrics",fn:()=>this.sendThreadPerformanceMetrics()}];for(const e of s)try{e.fn()}catch(t){T.error(`Failed flushing ${e.label}`,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0})}}async sendTerminateAndAwait(e){const t=a.getSavedLogs();try{await this.getMessageFromWorker("terminated",e.grace,e.shouldRef,{msg:"Terminate",content:{grace:e.grace,logBuffers:t}})}catch(t){t instanceof m.HudTimeoutError?(T.critical(e.timeoutLogMsg,{error:t.message}),await this.worker.terminate()):(T.critical(e.unexpectedLogMsg,{msg:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),await this.worker.terminate())}}async gracefulShutdown(){if(!this.gracefulShutdownDone){this.gracefulShutdownDone=!0;try{this.abortController.abort(),this.abortController=new AbortController,d.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.worker.ref(),this.flushAllPendingData(),await this.sendTerminateAndAwait({grace:d.hudConfig.teardownGrace,shouldRef:!0,timeoutLogMsg:"Teardown grace timeout - terminating worker",unexpectedLogMsg:"Unexpected error during SDK graceful shutdown"})}finally{try{this.worker.unref()}catch{}this.stop()}}}async terminateWorker(){await this.sendTerminateAndAwait({grace:d.hudConfig.workerGrace,shouldRef:!1,timeoutLogMsg:"Grace period timeout - terminating worker",unexpectedLogMsg:"Unexpected error during worker termination"}),T.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:n.c[n.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):T.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=d.hudConfig.dynamicConfig.performanceMetricsInterval;await(0,u.safeUnrefInterval)(()=>this.sendThreadPerformanceMetrics(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending thread performance metrics",{msg:e.message,stack:e.stack})})}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(C.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void T.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){T.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){await(0,u.safeUnrefInterval)(()=>this.handleLogsTask(),e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending logs periodically",{msg:e.message,stack:e.stack})})}async setupPeriodicTask(e,t,n,i,s=0){function r(e){let t=!0;try{t=n(e)}catch(e){T.error("Failed in periodic task",{taskName:i,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),!r(e))return void T.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:i});if(1===s)return;let o=s>0?s-1:0;await(0,u.safeUnrefInterval)(e=>{if(!r(t))return T.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:i}),void e();o>0&&0===--o&&e()},t,{signal:this.abortController.signal,onError:e=>T.error("Failed in periodic task interval",{taskName:i,msg:e.message,stack:e.stack})})}async periodicResetGlobalInvestigationCounter(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting global investigation counter",{interval:e}),(0,y.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting global investigation counter",{msg:e.message,stack:e.stack})})}async periodicResetInvestigationDedupingCache(){const e=d.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;await(0,u.safeUnrefInterval)(()=>{T.info("Resetting investigation deduping cache",{interval:e}),(0,y.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)(),(0,f.getUniqueSetFailureErrors)().clear()},e,{signal:this.abortController.signal,onError:e=>T.error("Failed resetting investigation deduping cache",{msg:e.message,stack:e.stack})})}updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,b.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,T.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,w._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=d.hudConfig.staticNextJsEndpointsInterval,t=d.hudConfig.staticNextJsEndpointsMaxAttempts;let n=0;await(0,u.safeUnrefInterval)(e=>{if(n++,T.debug("Attempting to send static next.js endpoints",{attemptCount:n}),this.sendStaticNextJsEndpointsIfReady())return T.info("Sent static next.js endpoints"),void e();n>t&&(T.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,y.isNextConfigExtracted)(),attemptCount:n}),e())},e,{signal:this.abortController.signal,onError:e=>T.error("Failed sending static next.js endpoints",{msg:e.message,stack:e.stack})})}async periodicSendReingest(){await(0,u.safeUnrefInterval)(()=>{const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))},d.hudConfig.dynamicConfig.reingestInterval,{signal:this.abortController.signal,onError:e=>T.error("Failed sending reingest",{msg:e.message,stack:e.stack})})}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}return n.c=t,n(n.s=5119)})());
2
2
  //# sourceMappingURL=core.js.map
package/dist/cjs/dto.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var n in o)("object"==typeof exports?exports:e)[n]=o[n]}}(global,()=>(()=>{"use strict";var e={765:(e,t)=>{var o,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionInitStatus=t.HudRunningMode=t.KeepAliveMessage=void 0,t.KeepAliveMessage={msg:"keep-alive"},function(e){e[e.detached=0]="detached",e[e.disabled=1]="disabled",e[e.enabled=2]="enabled"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(n||(t.HudSessionInitStatus=n={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(o(7789),t),r(o(8086),t),r(o(7935),t),r(o(6910),t),r(o(2176),t),r(o(9107),t),r(o(7022),t),r(o(6604),t),r(o(4909),t),r(o(878),t),r(o(8377),t),r(o(8054),t),r(o(6328),t),r(o(6413),t),r(o(6364),t),r(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const n=o(1569),r=o(7789);t.HudOptionsSchema=n.z.object({includeModules:n.z.array(n.z.string()).optional(),excludeDirs:n.z.array(n.z.string()).optional(),enableFrameworks:r.availableFrameworksSchema.optional(),maxMappedFunctions:n.z.number().optional(),minPodMemoryMB:n.z.number().optional(),maxFileSizeBytes:n.z.number().optional(),maxTimeUntilInitSessionMs:n.z.number().optional(),verbose:n.z.boolean().optional(),disableSourceMapsResolution:n.z.boolean().optional(),disableRuntimeInstrumentation:n.z.boolean().optional(),disableParametersExtraction:n.z.boolean().optional(),disableDetachedFunctions:n.z.boolean().optional(),customForensicsStorage:n.z.object({bucket:n.z.string(),region:n.z.string(),prefix:n.z.string().optional()}).optional(),flushOnExit:n.z.boolean().optional(),flushOnUncaughtException: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(),deploymentId:n.z.string().optional()})},6413:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6604:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6910:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.EntityType=t.ArgumentTypes=t.ParameterTypes=void 0,function(e){e.Identifier="Identifier",e.RestElement="RestElement",e.ArrayPattern="ArrayPattern",e.AssignmentPattern="AssignmentPattern",e.ObjectPattern="ObjectPattern",e.ObjectProperty="ObjectProperty"}(o||(t.ParameterTypes=o={})),function(e){e.StringLiteral="StringLiteral",e.Identifier="Identifier",e.TemplateString="TemplateString"}(n||(t.ArgumentTypes=n={})),function(e){e.FunctionDeclaration="functionDeclaration",e.FunctionExpression="functionExpression",e.FunctionArrow="functionArrow",e.ClassMethod="classMethod",e.ObjectMethod="objectMethod",e.ClassPrivateMethod="classPrivateMethod",e.ClassDeclaration="classDeclaration",e.ClassExpression="classExpression",e.ObjectExpression="objectExpression",e.Program="program",e.ForLoop="forLoop",e.ForBlock="forBlock",e.ForTest="forTest",e.Block="block",e.While="while",e.DoWhile="doWhile",e.Do="Do",e.WhileTest="whileTest",e.Switch="switch",e.SwitchCase="switchCase",e.Catch="catch",e.With="with",e.If="if",e.IfTest="ifTest",e.IfConsequent="ifConsequent",e.IfAlternate="ifAlternate",e.TryCatch="tryCatch",e.Try="try",e.Finally="finally",e.Other="other",e.File="file"}(r||(t.EntityType=r={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const n=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",fastify:"fastify",hapi:"hapi",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp",mongodb:"mongodb",mongoose:"mongoose",clickhouse:"clickhouse"},t.availableFrameworksSchema=n.z.union([n.z.map(n.z.nativeEnum(t.availableFrameworks),n.z.boolean()),n.z.record(n.z.nativeEnum(t.availableFrameworks),n.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,n,r,i,s){this.flow_id=e,this.methods=t,this.framework=n,this.partial_path=s,r||(r=""),this.path=o(r,i),this.partial_path=o(r,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Cleared=3]="Cleared"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql",e.CustomFlow="custom_flow"}(n||(t.InvestigationType=n={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis",e.MONGO="mongo"}(r||(t.OutboundType=r={}))},9107:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndReason=void 0,function(e){e.ServerTimeout="http.server_timeout",e.ClientTimeout="http.client_timeout",e.ResponseAborted="http.response_aborted"}(o||(t.HttpEndReason=o={}))}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(3487)})());
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",e[e.reservedForForensicsOnlyDontUse=3]="reservedForForensicsOnlyDontUse"}(o||(t.HudRunningMode=o={})),function(e){e[e.success=0]="success",e[e.throttled=1]="throttled"}(n||(t.HudSessionInitStatus=n={}))},878:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.GraphQLSupportedOperations=void 0,function(e){e.query="query",e.mutation="mutation",e.subscription="subscription"}(o||(t.GraphQLSupportedOperations=o={}))},1569:e=>{e.exports=require("zod")},2176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3487:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(o(7789),t),r(o(8086),t),r(o(7935),t),r(o(6910),t),r(o(2176),t),r(o(9107),t),r(o(7022),t),r(o(6604),t),r(o(4909),t),r(o(878),t),r(o(8377),t),r(o(8054),t),r(o(6328),t),r(o(6413),t),r(o(6364),t),r(o(765),t)},4909:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6328:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},6364:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HudSessionOptionsSchema=t.HudOptionsSchema=void 0;const n=o(1569),r=o(7789);t.HudOptionsSchema=n.z.object({includeModules:n.z.array(n.z.string()).optional(),excludeDirs:n.z.array(n.z.string()).optional(),enableFrameworks:r.availableFrameworksSchema.optional(),maxMappedFunctions:n.z.number().optional(),minPodMemoryMB:n.z.number().optional(),maxFileSizeBytes:n.z.number().optional(),maxTimeUntilInitSessionMs:n.z.number().optional(),verbose:n.z.boolean().optional(),disableSourceMapsResolution:n.z.boolean().optional(),disableRuntimeInstrumentation:n.z.boolean().optional(),disableParametersExtraction:n.z.boolean().optional(),disableDetachedFunctions:n.z.boolean().optional(),customForensicsStorage:n.z.object({bucket:n.z.string(),region:n.z.string(),prefix:n.z.string().optional()}).optional(),flushOnExit:n.z.boolean().optional(),flushOnUncaughtException: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(),deploymentId:n.z.string().optional(),forensicsOnly:n.z.boolean().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,i,s;Object.defineProperty(t,"__esModule",{value:!0}),t.FlowFramework=t.FlowType=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={})),function(e){e.Queue="queue",e.WebSocket="websocket"}(i||(t.FlowType=i={})),function(e){e.BullMQ="bullmq",e.SocketIO="socket.io"}(s||(t.FlowFramework=s={}))},7022:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.Format=t.FUNCTION_DECLARATION_VERSION=void 0,t.isSupportedFormat=function(e){return Object.values(o).includes(e)},t.FUNCTION_DECLARATION_VERSION="1.1.3",function(e){e.cjs="commonjs",e.esm="module",e.ts="typescript",e.moduleTypescript="module-typescript",e.commonjsTypescript="commonjs-typescript"}(o||(t.Format=o={}))},7789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.availableFrameworksSchema=t.availableFrameworks=void 0;const n=o(1569);t.availableFrameworks={axios:"axios",pg:"pg",ioredis:"ioredis",nodeFetch:"nodeFetch",request:"request",express:"express",fastify:"fastify",hapi:"hapi",koa:"koa",graphql:"graphql",http:"http",https:"https",nextjs:"nextjs",nestjs:"nestjs",kafkajs:"kafkajs",confluentKafkaJs:"confluentKafkaJs",codegenieServerlessExpress:"codegenieServerlessExpress",sqs:"sqs",serverlessHttp:"serverlessHttp",mongodb:"mongodb",mongoose:"mongoose",clickhouse:"clickhouse"},t.availableFrameworksSchema=n.z.union([n.z.map(n.z.nativeEnum(t.availableFrameworks),n.z.boolean()),n.z.record(n.z.nativeEnum(t.availableFrameworks),n.z.boolean())]).transform(e=>e instanceof Map?e:new Map(Object.entries(e)))},7935:(e,t)=>{function o(e,t){return t?t instanceof RegExp?e+t.toString():("/"===t[t.length-1]&&t.length>1&&(t=t.slice(0,-1)),(t=e+t).replace(/\/{2,}/g,"/")):t}Object.defineProperty(t,"__esModule",{value:!0}),t.EndpointDeclaration=void 0,t.EndpointDeclaration=class{flow_id;methods;framework;partial_path;path;constructor(e,t,n,r,i,s){this.flow_id=e,this.methods=t,this.framework=n,this.partial_path=s,r||(r=""),this.path=o(r,i),this.partial_path=o(r,s)}}},8054:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8086:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},8377:(e,t)=>{var o,n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.OutboundType=t.InvestigationType=t.InvestigationStatus=void 0,function(e){e[e.Open=1]="Open",e[e.Closed=2]="Closed",e[e.Cleared=3]="Cleared"}(o||(t.InvestigationStatus=o={})),function(e){e.HTTP="http",e.SQS="sqs",e.Kafka="kafka",e.GraphQL="graphql",e.Queue="queue",e.WebSocket="websocket",e.CustomFlow="custom_flow"}(n||(t.InvestigationType=n={})),function(e){e.HTTP="http",e.DB="db",e.REDIS="redis",e.MONGO="mongo"}(r||(t.OutboundType=r={}))},9107:(e,t)=>{var o;Object.defineProperty(t,"__esModule",{value:!0}),t.HttpEndReason=void 0,function(e){e.ServerTimeout="http.server_timeout",e.ClientTimeout="http.client_timeout",e.ResponseAborted="http.response_aborted"}(o||(t.HttpEndReason=o={}))}},t={};return function o(n){var r=t[n];if(void 0!==r)return r.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,o),i.exports}(3487)})());
2
2
  //# sourceMappingURL=dto.js.map
@@ -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 n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(global,()=>(()=>{"use strict";var e={290:e=>{e.exports=require("async_hooks")},395:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addReingestValue=function(e){r.add(e)},t.getAndClearReingestValues=function(){const e=new Set;for(const t of r)n.has(t)||e.add(t);for(const t of e)n.add(t);return r=new Set,e};let r=new Set;const n=new Set},523:e=>{e.exports=require("./logger")},754:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeEndpointDeclaration=function(e){r.push(e)},t.getEndpointDeclarationsFromStorage=function(){const e=r;return r=[],e};let r=[]},820:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),o(r(3165),t),o(r(7764),t),o(r(4821),t),o(r(4583),t),o(r(3025),t),o(r(8714),t),o(r(4988),t),o(r(2525),t),o(r(3973),t),o(r(1757),t),o(r(1364),t),o(r(7398),t),o(r(8708),t),o(r(7918),t),o(r(395),t)},1364:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudInstrumentationOccured=!1,globalThis.hudNextJsPluginIndicator=void 0,globalThis.hudStartTime=new Date,globalThis.hudRunningMode=o.HudRunningMode.enabled,globalThis.hudExecutionFlowMaxLength=n.hudConfig.dynamicConfig.investigationRateLimits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=n.hudConfig.dynamicConfig.investigationRateLimits.exceptionMaxLength,globalThis.hudEnableInvestigation=n.hudConfig.dynamicConfig.enableInvestigation,globalThis.hudEnableInvestigationArgsSending=n.hudConfig.dynamicConfig.enableInvestigationArgsSending,(0,n.updateInvestigationErrorStatusCodePatternGlobal)(n.hudConfig.dynamicConfig.investigationErrorStatusCodeRegex),(0,a.setInvestigationStorage)(new u.AsyncLocalStorage),(0,a.setFlowStateStorage)(new u.AsyncLocalStorage),function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[r,n]of e){for(let e=t;e<r;e++)globalThis.hudSampleTable.push(e%n===0);t=r}}(),l())},t.resetGlobals=l,t.hookMessageChannel=function(){const{port1:e,port2:t}=new c.MessageChannel;return e.on("message",e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)}),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=h,t.clearMetricsIndicator=g,t.clearInstrumentationIndicator=f,t.clearUserIndicatorsTimeouts=function(){h(),g(),f()},t.detachHud=p,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return n.hudConfig.userConfig.key||n.hudConfig.userConfig.service?n.hudConfig.userConfig.key?(0,n.isValidParam)(n.hudConfig.userConfig.key.value)?n.hudConfig.userConfig.service?(0,n.isValidParam)(n.hudConfig.userConfig.service.value)?{apiKey:n.hudConfig.userConfig.key.value,service:n.hudConfig.userConfig.service.value}:(s.app_logger.critical("Service name is invalid - SDK cannot initialize",{source:n.hudConfig.userConfig.service.source}),n.hudConfig.disableOnBadServiceName&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudServiceInvalid(n.hudConfig.userConfig.service.source))):(s.app_logger.critical("Service name is missing - SDK cannot initialize"),n.hudConfig.disableOnBadServiceName&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(s.app_logger.critical("API key is invalid - SDK cannot initialize",{source:n.hudConfig.userConfig.key.source}),n.hudConfig.disableOnBadApiKey&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyInvalid(n.hudConfig.userConfig.key.source))):(s.app_logger.critical("API key is missing - SDK cannot initialize"),n.hudConfig.disableOnBadApiKey&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):(s.app_logger.critical("Both API key and service name are missing - SDK cannot initialize"),(n.hudConfig.disableOnBadApiKey||n.hudConfig.disableOnBadServiceName)&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))};const n=r(5809),o=r(8528),i=r(2546),s=r(523),a=r(7131),u=r(290),c=r(8167),d=r(3165);function l(){globalThis.hudProcessedFiles=[],globalThis.hudStack=new Array(1e3).fill(""),globalThis.hudStackIndex={value:0},globalThis.hudStackPop=!1,globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[],globalThis.hudCalls={}}function h(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function g(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function f(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0,globalThis.hudInstrumentationOccured=!0}function p(e=!0,t=!1){if(s.app_logger.warning("Detaching hud"),(0,d.getAsyncHook)()?.disable(),t||e&&hudRunningMode!==o.HudRunningMode.detached){const e=(0,i.getFirstError)();s.customer_logger.logEntry(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=o.HudRunningMode.detached}},1757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.markShouldFlushOnInit=function(e){o=e},t.storeCredentials=function(e,t){r=e,n=t},t.storeSessionInfo=function(e){i=e},t.getSessionInfo=function(){return i},t.getStoredApiKey=function(){return r},t.getStoredService=function(){return n},t.getShouldFlushOnInit=function(){return o};let r,n,o=!1,i=null},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSqsQueues=function(){const e=r;return r=[],e},t.storeSqsQueueDeclaration=function(e){r.push(e)};let r=[]},2546:e=>{e.exports=require("./lib")},2987:e=>{e.exports=require("perf_hooks")},3025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getGraphQLOperations=function(){const e=r;return r={},e},t.storeGraphQLOperation=function(e){r[e.flow_id]||(r[e.flow_id]=e)};let r={}},3165:(e,t)=>{let r;Object.defineProperty(t,"__esModule",{value:!0}),t.getAsyncHook=function(){return r},t.setAsyncHook=function(e){r=e}},3973:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFlowMetrics=function(e){const t=(new Date).toISOString(),r={};for(const n in a){const i=[];let s;for(const r in a[n]){const o=a[n][r];s||(s=o.getEventVersion()),i.push(o.finalize(u,t,e))}delete a[n],s?r[n]={eventVersion:s,metrics:i}:o.app_logger.error("No event version found for metric type",n)}return r},t.storeFlowMetric=function(e){const t=function(e){if(void 0!==e.flow_id)switch(e.type){case"EndpointMetric":{const t=e;return`${e.flow_id}|${t.method}|${t.status_code??""}|${t.end_reason??""}`}case"KafkaJSMetric":{const t=e;return`${e.flow_id}|${t.partition}`}case"GraphQLMetric":{const t=e;return`${e.flow_id}|${t.status_code}`}default:return e.flow_id}}(e);if(!t)return;a[e.type]||(a[e.type]={});const r=a[e.type][t];if(r)r.update(e,u);else{const r=s.MetricFactory.createMetric(e,u);a[e.type][t]=r}};const n=r(5809),o=r(523),i=r(7131),s=r(7859),a={},u=new i.SketchManager(n.hudConfig.huddBinWidth)},4583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizePath=s,t.collectExpressEndpointsForApp=d,t.collectExpressEndpointDeclarations=function(){const e=globalThis.hudExpressState.length;-1===h&&o.app_logger.info("First time iterating over express apps",{expressAppCount:e}),e!==h&&o.app_logger.info("Express app count changed",{expressAppCount:e}),h=e,globalThis.hudExpressState.forEach(e=>d(e).forEach(e=>{l.has(e.flow_id)||(l.add(e.flow_id),(0,i.storeEndpointDeclaration)(e))}))};const n=r(2546),o=r(523),i=r(754);function s(e){return e.replace(/\/+/g,"/")}function a(e){return e[n.HUD_PATH_SYMBOL]?Array.isArray(e[n.HUD_PATH_SYMBOL])?0===e[n.HUD_PATH_SYMBOL].length?((0,o.limitedLogger)("Layer has empty array HUD_PATH_SYMBOL",{layerName:e.name,layerPath:e.path},`${e.name}:${e.path}`),[""]):e[n.HUD_PATH_SYMBOL]:[e[n.HUD_PATH_SYMBOL]]:((0,o.limitedLogger)("Layer has no HUD_PATH_SYMBOL",{layerName:e.name,layerPath:e.path},`${e.name}:${e.path}`),[""])}function u(e,t){const r=new Array;for(const i of e)if(i[n.HUD_PATH_IGNORE_SYMBOL])(0,o.limitedLogger)("Skipped layer due to array with regexes",{prefix:t,layerPath:i.path,hudPath:i[n.HUD_PATH_SYMBOL]},`${t}:${i.path}`);else if(i.route)Object.keys(i.route.methods).forEach(e=>{let u=[e];if(i[n.HUD_USE_ALL_METHODS_SYMBOL]?u=(0,n.getMethods)():"_all"!==e&&"all"!==e||(u=["all"]),i[n.HUD_PATH_SYMBOL]){const e=a(i);e.length>1&&(0,o.limitedLogger)("Express layer with array path",{prefix:t,layerPaths:e},`${t}:${e.join(",")}`),e.forEach(e=>{const o=s(t+e);r.push({path:o,methods:u,flow_id:(0,n.generateEndpointFlowId)(o,u),framework:"express"})})}else(0,o.limitedLogger)("No HUD_PATH_SYMBOL",{prefix:t,layerName:i.name,layerPath:i.path,method:e},`${t}:${i.name}:${i.path}:${e}`)});else if("router"===i.name&&i[n.HUD_STACK_SYMBOL]){if(i.handle[n.HUD_SEEN_ROUTER_SYMBOL])continue;i.handle[n.HUD_SEEN_ROUTER_SYMBOL]=!0;try{const e=a(i);e&&e.length>0&&e.forEach(e=>{try{r.push(...u(i[n.HUD_STACK_SYMBOL],t+e))}catch(r){o.app_logger.error("Failed to collect endpoints from router",{path:t+e,msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}})}finally{delete i.handle[n.HUD_SEEN_ROUTER_SYMBOL]}}else"router"===i.name&&(0,o.limitedLogger)("Router without HUD_STACK_SYMBOL");return r}function c(e){const t=e.parent?c(e.parent):[],r=e.mountpath??"/",n=(Array.isArray(r)?r:[r]).map(e=>"/"===e?"":e);return t.length>0?t.flatMap(e=>n.map(t=>e+t)):n}function d(e){let t;try{const r=c(e);if(0===r.length)return(0,o.limitedLogger)("Express application without mount paths, can't extract endpoints"),[];if(t=e._router||e.router,!t?.stack)return(0,o.limitedLogger)("Express application without router or router without stack, can't extract endpoints"),[];const i=[];for(const e of r){t[n.HUD_SEEN_ROUTER_SYMBOL]=!0;try{i.push(...u(t.stack,e))}finally{delete t[n.HUD_SEEN_ROUTER_SYMBOL]}}return 0===i.length&&(0,o.limitedLogger)("No endpoints found for express application"),function(e){const t=new Set;return e.filter(e=>!t.has(e.flow_id)&&(t.add(e.flow_id),!0))}(i)}catch(e){return o.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}const l=new Set;let h=-1},4821:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getCustomFlowDeclarations=function(){const e=i;return i=[],e},t.storeCustomFlowDeclarationOnce=function(e,t){return!!o.has(e.flow_id)||(void 0!==t&&o.size>=t?((0,n.limitedLogger)("Custom flow id limit reached",{maxDeclarations:t}),!1):(o.add(e.flow_id),i.push(e),!0))};const n=r(523),o=new Set;let i=[]},4988:function(e,t,r){var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.pageManifest=t.apiManifest=void 0,t.setNextConfig=function(e){h=e,g=!0},t.getNextConfig=function(){return h},t.isNextConfigExtracted=function(){return g},t.extractNextEndpointDeclarations=async function(e){const r=[];if(!e)return r;d.worker_logger.info("Extracting next.js endpoint declarations in worker");const n=e.distDir,o=a.join(n,t.apiManifest),i=await(0,c.readFile)(o);if(i){const e=JSON.parse(i),t=await async function(e,t){const r=[];for(const n of Object.keys(t))if(n.endsWith("/route")){const o=a.join(e,"server",t[n]),i=await _(o),s=m(n,"/route");for(const e of i){const t=(0,c.generateEndpointFlowId)(s,[e]);r.push(new u.EndpointDeclaration(t,[e],"nextjs","",s))}}else if(n.endsWith("/page")){const e=["GET"],t=m(n,"/page"),o=(0,c.generateEndpointFlowId)(t,e);r.push(new u.EndpointDeclaration(o,e,"nextjs","",t))}else d.worker_logger.warning("Unknown Next.js manifest key type",{key:n});return r}(n,e);r.push(...t)}const s=a.join(n,t.pageManifest),h=await(0,c.readFile)(s);if(h){const e=JSON.parse(h),t=await async function(e,t){const r=[];for(const e of Object.keys(t))if(e.startsWith("/api/")){const t=(0,c.generateEndpointFlowId)(e,l);r.push(new u.EndpointDeclaration(t,l,"nextjs","",e))}else{const t=["GET"],n=(0,c.generateEndpointFlowId)(e,t);r.push(new u.EndpointDeclaration(n,t,"nextjs","",e))}return r}(0,e);r.push(...t)}return r};const a=s(r(6928)),u=r(8528),c=r(2546),d=r(523),l=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];let h;t.apiManifest="server/app-paths-manifest.json",t.pageManifest="server/pages-manifest.json";let g=!1;const f=new RegExp(`\\b(${l.join("|")})\\b`,"g");function p(e){const t=e.matchAll(f),r=Array.from(t,e=>e[1]);return Array.from(new Set(r))}async function _(e){const t=await(0,c.readFile)(e);return t?(r=t).includes('require("../../chunks/[turbopack]_runtime.js")')&&r.includes("R.c(")&&r.includes("R.m(")?async function(e,t){const r=function(e){if(!e.match(/R\.m\(\d+\)/))return null;const t=e.matchAll(/R\.c\("([^"]+)"\)/g);return{chunkPaths:Array.from(t,e=>e[1])}}(t);if(!r||0===r.chunkPaths.length)return[];const n=a.resolve(e,"..","..",".."),o=a.resolve(n,"..");let i="";for(const e of r.chunkPaths){const t=a.join(o,e),r=await(0,c.readFile)(t);r&&(i+=r)}return p(i)}(e,t):p(t):[];var r}function m(e,t){return e.length===t.length?"/":e.length>t.length?e.slice(0,0-t.length):e}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},7131:e=>{e.exports=require("./wrap")},7398:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalInvestigationTracking=void 0,t.getClosedInvestigations=function(){const e=i;return i=[],e},t.storeClosedInvestigation=function(e){globalThis.hudEnableInvestigation&&i.push(e)},t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++},t.getGlobalInvestigationTracking=function(){return t.globalInvestigationTracking},t.increaseInvestigationDedupingCache=function(e,t){const r=s.get(e)??new Map,n=(r.get(t)??0)+1;r.set(t,n),s.set(e,r)},t.resetInvestigationDedupingCache=function(){s.clear()},t.getInvestigationDedupingCache=function(e){return s.get(e)??new Map},t.saveMachineMetric=function(){const e=process.cpuUsage(),t=o.performance.eventLoopUtilization();a.push({cpuUsage:e,elu:t,timestamp:Date.now()}),a.length>n.hudConfig.machineMetricsSavedLength&&a.shift()},t.getLastMetrics=function(){return a[0]},t.setInvestigationDurationThresholds=function(e){u=e},t.getFlowIdDurationThresholdAndCount=function(e){return u[e]},t.increaseInvestigationDurationCount=function(e){const t=c.get(e)??0;c.set(e,t+1)},t.getInvestigationDurationCount=function(e){return c.get(e)??0},t.resetInvestigationDurationCounts=function(){c.clear()},t.increaseTotalInvestigationsErrorBased=function(){d++},t.getTotalInvestigationsErrorBased=function(){return d},t.resetTotalInvestigationsErrorBased=function(){d=0},t.increaseTotalInvestigationsDurationBased=function(){l++},t.getTotalInvestigationsDurationBased=function(){return l},t.resetTotalInvestigationsDurationBased=function(){l=0},t.getUniqueSetFailureErrors=function(){return h};const n=r(5809),o=r(2987);let i=[];t.globalInvestigationTracking=0;const s=new Map,a=[];let u={};const c=new Map;let d=0,l=0;const h=new Set},7764:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),o(r(4821),t),o(r(754),t),o(r(3025),t),o(r(8714),t),o(r(4988),t),o(r(4583),t)},7859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricFactory=t.BaseMetric=void 0;class r{}class n extends r{flowId;count;sumDuration;sumSquaredDuration;sketchBuilder;errorBreakdown;constructor(e,t){super(),this.flowId=e.flow_id,this.count=1,this.sumDuration=e.duration,this.sumSquaredDuration=e.duration**2,this.sketchBuilder=t.newSketchDataWithValue(e.duration),this.errorBreakdown=new Map,e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}getEventVersion(){return"1.0.0"}updateErrorBreakdown(e){let t=this.errorBreakdown.get(e.key);void 0===t&&(t={errors:e.errors,count:0,caught:e.caught,key:e.key,framework_result:e.framework_result,user_error:e.user_error},this.errorBreakdown.set(e.key,t)),t.count+=1}update(e,t){this.sumDuration+=e.duration,this.sumSquaredDuration+=e.duration**2,this.count+=1,t.add(this.sketchBuilder,e.duration),void 0!==e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}finalize(e,t,r){return{flow_id:this.flowId,count:this.count,sum_duration:this.sumDuration,sum_squared_duration:this.sumSquaredDuration,timestamp:t,timeslice:r,sketch:e.encode(this.sketchBuilder),error_breakdown:Array.from(this.errorBreakdown.values()).map(e=>({errors:e.errors,count:e.count,caught:e.caught,framework_result:e.framework_result,user_error:e.user_error}))}}}t.BaseMetric=n;class o{static registry={};static registerMetric(e,t){o.registry[e]=t}static createMetric(e,t){const r=o.registry[e.type];if(!r)throw new Error(`Unknown metric type: ${e.type}`);return new r(e,t)}}t.MetricFactory=o,o.registerMetric("EndpointMetric",class extends n{method;statusCode;errors;endReason;constructor(e,t){super(e,t),this.method=e.method,this.statusCode=e.status_code,this.endReason=e.end_reason,this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}getEventVersion(){return"2.0.1"}finalize(e,t,r){return{...super.finalize(e,t,r),method:this.method,...void 0!==this.statusCode?{status_code:this.statusCode}:{},errors:this.errors,...void 0!==this.endReason?{end_reason:this.endReason}:{}}}}),o.registerMetric("GraphQLMetric",class extends n{statusCode;errorsCount;constructor(e,t){super(e,t),this.statusCode=e.status_code,this.errorsCount=e.error_occurred?1:0}update(e,t){super.update(e,t),this.errorsCount+=e.error_occurred?1:0}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),status_code:this.statusCode,errors_count:this.errorsCount}}}),o.registerMetric("KafkaJSMetric",class extends n{partition;errors;ConsumeSketchBuilder;sumConsumedDuration;sumSquaredConsumedDuration;constructor(e,t){super(e,t),this.partition=e.partition,this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1),e.total_consume_duration&&(this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration)),this.sumConsumedDuration=e.total_consume_duration??0,this.sumSquaredConsumedDuration=(e.total_consume_duration??0)**2}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1),e.total_consume_duration&&(this.sumConsumedDuration+=e.total_consume_duration,this.sumSquaredConsumedDuration+=e.total_consume_duration**2,this.ConsumeSketchBuilder?t.add(this.ConsumeSketchBuilder,e.total_consume_duration):this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration))}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),partition:this.partition,errors:this.errors,sum_consumed_duration:this.sumConsumedDuration,sum_squared_consumed_duration:this.sumSquaredConsumedDuration,sketch_consume:e.encode(this.ConsumeSketchBuilder)}}}),o.registerMetric("SqsMetric",class extends n{msgCount;errors;e2eData;constructor(e,t){super(e,t),this.msgCount=e.msg_count,this.errors=e.errors,e.e2e_duration&&(this.e2eData={duration:e.e2e_duration,squaredDuration:e.e2e_duration**2,sketchBuilder:t.newSketchDataWithValue(e.e2e_duration)})}update(e,t){super.update(e,t),this.msgCount&&e.msg_count&&(this.msgCount+=e.msg_count),Object.entries(e.errors).forEach(([e,t])=>{this.errors[e]=(this.errors[e]??0)+t}),this.e2eData&&e.e2e_duration&&(this.e2eData.duration+=e.e2e_duration,this.e2eData.squaredDuration+=e.e2e_duration**2,t.add(this.e2eData.sketchBuilder,e.e2e_duration))}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),errors:this.errors,msg_count:this.msgCount,...this.e2eData?{e2e_sum_duration:this.e2eData.duration,e2e_sum_squared_duration:this.e2eData.squaredDuration,e2e_sketch:e.encode(this.e2eData.sketchBuilder)}:{}}}}),o.registerMetric("CustomFlowMetric",class extends n{errors;constructor(e,t){super(e,t),this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}getEventVersion(){return"1.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),errors:this.errors}}})},7918:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeLoadedOutbound=function(e){r.push(e)},t.getLoadedOutboundsFromStorage=function(){const e=r;return r=[],e},t.getIoredisFunctionId=function(e){return n.get(e)},t.storeIoredisCommand=function(e,t){n.has(e)||o.add(e),n.set(e,t)},t.getIoredisCommandsFromStorage=function(){const e=Array.from(o);return o=new Set,e};let r=[];const n=new Map;let o=new Set},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setLambdaExtensionId=function(e){o&&n.app_logger.warning("Lambda extension id already set"),o=e},t.getLambdaExtensionId=function(){return o};const n=r(523);let o},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKafkaJSTopics=function(){const e=r;return r=[],e},t.storeKafkaJSTopicDeclaration=function(e){r.push(e)};let r=[]}},t={};return function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}(820)})());
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 n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(global,()=>(()=>{"use strict";var e={290:e=>{e.exports=require("async_hooks")},395:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addReingestValue=function(e){r.add(e)},t.getAndClearReingestValues=function(){const e=new Set;for(const t of r)n.has(t)||e.add(t);for(const t of e)n.add(t);return r=new Set,e};let r=new Set;const n=new Set},523:e=>{e.exports=require("./logger")},754:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeEndpointDeclaration=function(e){r.push(e)},t.getEndpointDeclarationsFromStorage=function(){const e=r;return r=[],e};let r=[]},820:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),o(r(3165),t),o(r(7764),t),o(r(4821),t),o(r(4583),t),o(r(6649),t),o(r(3025),t),o(r(8714),t),o(r(4988),t),o(r(2525),t),o(r(3973),t),o(r(1757),t),o(r(1364),t),o(r(7398),t),o(r(8708),t),o(r(7918),t),o(r(395),t)},1364:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initGlobals=function(){globalThis.hudGlobalInitGuard||(globalThis.hudGlobalInitGuard=!0,globalThis.hudRunMutex=!1,globalThis.hudRanOnRequire=!1,globalThis.hudRanOnImport=!1,globalThis.hudInitGuard=void 0,globalThis.hudInstrumentationIndicator=void 0,globalThis.hudMetricsIndicator=void 0,globalThis.hudInstrumentationOccured=!1,globalThis.hudNextJsPluginIndicator=void 0,globalThis.hudStartTime=new Date,globalThis.hudRunningMode=o.HudRunningMode.enabled,globalThis.hudExecutionFlowMaxLength=n.hudConfig.dynamicConfig.investigationRateLimits.executionFlowMaxLength,globalThis.hudExceptionMaxLength=n.hudConfig.dynamicConfig.investigationRateLimits.exceptionMaxLength,globalThis.hudEnableInvestigation=n.hudConfig.dynamicConfig.enableInvestigation,globalThis.hudEnableInvestigationArgsSending=n.hudConfig.dynamicConfig.enableInvestigationArgsSending,(0,n.updateInvestigationErrorStatusCodePatternGlobal)(n.hudConfig.dynamicConfig.investigationErrorStatusCodeRegex),(0,a.setInvestigationStorage)(new u.AsyncLocalStorage),(0,a.setFlowStateStorage)(new u.AsyncLocalStorage),function(){globalThis.hudSampleTable=[];const e=[[10,1],[30,2],[100,3],[500,11],[1e3,23],[5e3,53]];let t=0;for(const[r,n]of e){for(let e=t;e<r;e++)globalThis.hudSampleTable.push(e%n===0);t=r}}(),l())},t.resetGlobals=l,t.hookMessageChannel=function(){const{port1:e,port2:t}=new c.MessageChannel;return e.on("message",e=>{"HudModulePatch"===e.key?(globalThis.hudPatched.add(e.hudPatched),globalThis.hudProcessedFiles.push(e.hudProcessedFiles)):"HudRetrieveFileCache"===e.key&&globalThis.HudSourceMapCache.set(e.filename,e.content)}),e.unref(),globalThis.hudHookPort=e,t},t.clearInitGuard=h,t.clearMetricsIndicator=g,t.clearInstrumentationIndicator=f,t.clearUserIndicatorsTimeouts=function(){h(),g(),f()},t.detachHud=p,t.forceHudEnable=function(){globalThis.forceHudEnable=!0},t.saveHudRunningFromSetup=function(){globalThis.hudIsRunningFromSetup=!0},t.saveInstrumentationIndicator=function(e){globalThis.hudInstrumentationIndicator=e,globalThis.hudInstrumentationIndicator.unref()},t.validateAndGetUserInput=function(){return n.hudConfig.userConfig.key||n.hudConfig.userConfig.service?n.hudConfig.userConfig.key?(0,n.isValidParam)(n.hudConfig.userConfig.key.value)?n.hudConfig.userConfig.service?(0,n.isValidParam)(n.hudConfig.userConfig.service.value)?{apiKey:n.hudConfig.userConfig.key.value,service:n.hudConfig.userConfig.service.value}:(s.app_logger.critical("Service name is invalid - SDK cannot initialize",{source:n.hudConfig.userConfig.service.source}),n.hudConfig.disableOnBadServiceName&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudServiceInvalid(n.hudConfig.userConfig.service.source))):(s.app_logger.critical("Service name is missing - SDK cannot initialize"),n.hudConfig.disableOnBadServiceName&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudServiceNotSet(globalThis.hudStartFromAutoInit))):(s.app_logger.critical("API key is invalid - SDK cannot initialize",{source:n.hudConfig.userConfig.key.source}),n.hudConfig.disableOnBadApiKey&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyInvalid(n.hudConfig.userConfig.key.source))):(s.app_logger.critical("API key is missing - SDK cannot initialize"),n.hudConfig.disableOnBadApiKey&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.HudApiKeyNotSet(globalThis.hudStartFromAutoInit))):(s.app_logger.critical("Both API key and service name are missing - SDK cannot initialize"),(n.hudConfig.disableOnBadApiKey||n.hudConfig.disableOnBadServiceName)&&p(!1),void s.customer_logger.logEntry(i.UserErrorLogs.BothApiKeyAndServiceNotSet(globalThis.hudStartFromAutoInit)))};const n=r(5809),o=r(8528),i=r(2546),s=r(523),a=r(7131),u=r(290),c=r(8167),d=r(3165);function l(){globalThis.hudProcessedFiles=[],globalThis.hudStack=new Array(1e3).fill(""),globalThis.hudStackIndex={value:0},globalThis.hudStackPop=!1,globalThis.hudLoadedModules=[],globalThis.hudPatched=new Set,globalThis.HudSourceMapCache=new Map,globalThis.hudExpressState=[],globalThis.hudCalls={}}function h(){clearTimeout(globalThis.hudInitGuard),globalThis.hudInitGuard=void 0}function g(){clearTimeout(globalThis.hudMetricsIndicator),globalThis.hudMetricsIndicator=void 0}function f(){clearTimeout(globalThis.hudInstrumentationIndicator),globalThis.hudInstrumentationIndicator=void 0,globalThis.hudInstrumentationOccured=!0}function p(e=!0,t=!1){if(s.app_logger.warning("Detaching hud"),(0,d.getAsyncHook)()?.disable(),t||e&&globalThis.hudRunningMode!==o.HudRunningMode.detached){const e=(0,i.getFirstError)();s.customer_logger.logEntry(i.UserErrorLogs.ShutdownGracefully(e))}globalThis.hudRunningMode=o.HudRunningMode.detached}},1757:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.markShouldFlushOnInit=function(e){o=e},t.storeCredentials=function(e,t){r=e,n=t},t.storeSessionInfo=function(e){i=e},t.getSessionInfo=function(){return i},t.getStoredApiKey=function(){return r},t.getStoredService=function(){return n},t.getShouldFlushOnInit=function(){return o};let r,n,o=!1,i=null},2525:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSqsQueues=function(){const e=r;return r=[],e},t.storeSqsQueueDeclaration=function(e){r.push(e)};let r=[]},2546:e=>{e.exports=require("./lib")},2987:e=>{e.exports=require("perf_hooks")},3025:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getGraphQLOperations=function(){const e=r;return r={},e},t.storeGraphQLOperation=function(e){r[e.flow_id]||(r[e.flow_id]=e)};let r={}},3165:(e,t)=>{let r;Object.defineProperty(t,"__esModule",{value:!0}),t.getAsyncHook=function(){return r},t.setAsyncHook=function(e){r=e}},3973:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFlowMetrics=function(e){const t=(new Date).toISOString(),r={};for(const n in a){const i=[];let s;for(const r in a[n]){const o=a[n][r];s||(s=o.getEventVersion()),i.push(o.finalize(u,t,e))}delete a[n],s?r[n]={eventVersion:s,metrics:i}:o.app_logger.error("No event version found for metric type",n)}return r},t.storeFlowMetric=function(e){const t=function(e){if(void 0!==e.flow_id)switch(e.type){case"EndpointMetric":{const t=e;return`${e.flow_id}|${t.method}|${t.status_code??""}|${t.end_reason??""}`}case"KafkaJSMetric":{const t=e;return`${e.flow_id}|${t.partition}`}case"GraphQLMetric":{const t=e;return`${e.flow_id}|${t.status_code}`}default:return e.flow_id}}(e);if(!t)return;a[e.type]||(a[e.type]={});const r=a[e.type][t];if(r)r.update(e,u);else{const r=s.MetricFactory.createMetric(e,u);a[e.type][t]=r}};const n=r(5809),o=r(523),i=r(7131),s=r(7859),a={},u=new i.SketchManager(n.hudConfig.huddBinWidth)},4583:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.normalizePath=s,t.collectExpressEndpointsForApp=d,t.collectExpressEndpointDeclarations=function(){const e=globalThis.hudExpressState.length;-1===h&&o.app_logger.info("First time iterating over express apps",{expressAppCount:e}),e!==h&&o.app_logger.info("Express app count changed",{expressAppCount:e}),h=e,globalThis.hudExpressState.forEach(e=>d(e).forEach(e=>{l.has(e.flow_id)||(l.add(e.flow_id),(0,i.storeEndpointDeclaration)(e))}))};const n=r(2546),o=r(523),i=r(754);function s(e){return e.replace(/\/+/g,"/")}function a(e){return e[n.HUD_PATH_SYMBOL]?Array.isArray(e[n.HUD_PATH_SYMBOL])?0===e[n.HUD_PATH_SYMBOL].length?((0,o.limitedLogger)("Layer has empty array HUD_PATH_SYMBOL",{layerName:e.name,layerPath:e.path},`${e.name}:${e.path}`),[""]):e[n.HUD_PATH_SYMBOL]:[e[n.HUD_PATH_SYMBOL]]:((0,o.limitedLogger)("Layer has no HUD_PATH_SYMBOL",{layerName:e.name,layerPath:e.path},`${e.name}:${e.path}`),[""])}function u(e,t){const r=new Array;for(const i of e)if(i[n.HUD_PATH_IGNORE_SYMBOL])(0,o.limitedLogger)("Skipped layer due to array with regexes",{prefix:t,layerPath:i.path,hudPath:i[n.HUD_PATH_SYMBOL]},`${t}:${i.path}`);else if(i.route)Object.keys(i.route.methods).forEach(e=>{let u=[e];if(i[n.HUD_USE_ALL_METHODS_SYMBOL]?u=(0,n.getMethods)():"_all"!==e&&"all"!==e||(u=["all"]),i[n.HUD_PATH_SYMBOL]){const e=a(i);e.length>1&&(0,o.limitedLogger)("Express layer with array path",{prefix:t,layerPaths:e},`${t}:${e.join(",")}`),e.forEach(e=>{const o=s(t+e);r.push({path:o,methods:u,flow_id:(0,n.generateEndpointFlowId)(o,u),framework:"express"})})}else(0,o.limitedLogger)("No HUD_PATH_SYMBOL",{prefix:t,layerName:i.name,layerPath:i.path,method:e},`${t}:${i.name}:${i.path}:${e}`)});else if("router"===i.name&&i[n.HUD_STACK_SYMBOL]){if(i.handle[n.HUD_SEEN_ROUTER_SYMBOL])continue;i.handle[n.HUD_SEEN_ROUTER_SYMBOL]=!0;try{const e=a(i);e&&e.length>0&&e.forEach(e=>{try{r.push(...u(i[n.HUD_STACK_SYMBOL],t+e))}catch(r){o.app_logger.error("Failed to collect endpoints from router",{path:t+e,msg:r instanceof Error?r.message:void 0,stack:r instanceof Error?r.stack:void 0})}})}finally{delete i.handle[n.HUD_SEEN_ROUTER_SYMBOL]}}else"router"===i.name&&(0,o.limitedLogger)("Router without HUD_STACK_SYMBOL");return r}function c(e){const t=e.parent?c(e.parent):[],r=e.mountpath??"/",n=(Array.isArray(r)?r:[r]).map(e=>"/"===e?"":e);return t.length>0?t.flatMap(e=>n.map(t=>e+t)):n}function d(e){let t;try{const r=c(e);if(0===r.length)return(0,o.limitedLogger)("Express application without mount paths, can't extract endpoints"),[];if(t=e._router||e.router,!t?.stack)return(0,o.limitedLogger)("Express application without router or router without stack, can't extract endpoints"),[];const i=[];for(const e of r){t[n.HUD_SEEN_ROUTER_SYMBOL]=!0;try{i.push(...u(t.stack,e))}finally{delete t[n.HUD_SEEN_ROUTER_SYMBOL]}}return 0===i.length&&(0,o.limitedLogger)("No endpoints found for express application"),function(e){const t=new Set;return e.filter(e=>!t.has(e.flow_id)&&(t.add(e.flow_id),!0))}(i)}catch(e){return o.app_logger.error("Failed to extract endpoints from express",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),[]}}const l=new Set;let h=-1},4821:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getCustomFlowDeclarations=function(){const e=i;return i=[],e},t.storeCustomFlowDeclarationOnce=function(e,t){return!!o.has(e.flow_id)||(void 0!==t&&o.size>=t?((0,n.limitedLogger)("Custom flow id limit reached",{maxDeclarations:t}),!1):(o.add(e.flow_id),i.push(e),!0))};const n=r(523),o=new Set;let i=[]},4988:function(e,t,r){var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&o(t,e,r[s]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.pageManifest=t.apiManifest=void 0,t.setNextConfig=function(e){h=e,g=!0},t.getNextConfig=function(){return h},t.isNextConfigExtracted=function(){return g},t.extractNextEndpointDeclarations=async function(e){const r=[];if(!e)return r;d.worker_logger.info("Extracting next.js endpoint declarations in worker");const n=e.distDir,o=a.join(n,t.apiManifest),i=await(0,c.readFile)(o);if(i){const e=JSON.parse(i),t=await async function(e,t){const r=[];for(const n of Object.keys(t))if(n.endsWith("/route")){const o=a.join(e,"server",t[n]),i=await _(o),s=m(n,"/route");for(const e of i){const t=(0,c.generateEndpointFlowId)(s,[e]);r.push(new u.EndpointDeclaration(t,[e],"nextjs","",s))}}else if(n.endsWith("/page")){const e=["GET"],t=m(n,"/page"),o=(0,c.generateEndpointFlowId)(t,e);r.push(new u.EndpointDeclaration(o,e,"nextjs","",t))}else d.worker_logger.warning("Unknown Next.js manifest key type",{key:n});return r}(n,e);r.push(...t)}const s=a.join(n,t.pageManifest),h=await(0,c.readFile)(s);if(h){const e=JSON.parse(h),t=await async function(e,t){const r=[];for(const e of Object.keys(t))if(e.startsWith("/api/")){const t=(0,c.generateEndpointFlowId)(e,l);r.push(new u.EndpointDeclaration(t,l,"nextjs","",e))}else{const t=["GET"],n=(0,c.generateEndpointFlowId)(e,t);r.push(new u.EndpointDeclaration(n,t,"nextjs","",e))}return r}(0,e);r.push(...t)}return r};const a=s(r(6928)),u=r(8528),c=r(2546),d=r(523),l=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"];let h;t.apiManifest="server/app-paths-manifest.json",t.pageManifest="server/pages-manifest.json";let g=!1;const f=new RegExp(`\\b(${l.join("|")})\\b`,"g");function p(e){const t=e.matchAll(f),r=Array.from(t,e=>e[1]);return Array.from(new Set(r))}async function _(e){const t=await(0,c.readFile)(e);return t?(r=t).includes('require("../../chunks/[turbopack]_runtime.js")')&&r.includes("R.c(")&&r.includes("R.m(")?async function(e,t){const r=function(e){if(!e.match(/R\.m\(\d+\)/))return null;const t=e.matchAll(/R\.c\("([^"]+)"\)/g);return{chunkPaths:Array.from(t,e=>e[1])}}(t);if(!r||0===r.chunkPaths.length)return[];const n=a.resolve(e,"..","..",".."),o=a.resolve(n,"..");let i="";for(const e of r.chunkPaths){const t=a.join(o,e),r=await(0,c.readFile)(t);r&&(i+=r)}return p(i)}(e,t):p(t):[];var r}function m(e,t){return e.length===t.length?"/":e.length>t.length?e.slice(0,0-t.length):e}},5809:e=>{e.exports=require("./config")},6649:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeGenericDeclaration=function(e){r.push(e)},t.getGenericDeclarationsFromStorage=function(){const e=r;return r=[],e};let r=[]},6928:e=>{e.exports=require("path")},7131:e=>{e.exports=require("./wrap")},7398:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.globalInvestigationTracking=void 0,t.getClosedInvestigations=function(){const e=i;return i=[],e},t.storeClosedInvestigation=function(e){globalThis.hudEnableInvestigation&&i.push(e)},t.setGlobalInvestigationTracking=function(e){t.globalInvestigationTracking=e},t.increaseGlobalInvestigationTracking=function(){t.globalInvestigationTracking++},t.getGlobalInvestigationTracking=function(){return t.globalInvestigationTracking},t.increaseInvestigationDedupingCache=function(e,t){const r=s.get(e)??new Map,n=(r.get(t)??0)+1;r.set(t,n),s.set(e,r)},t.resetInvestigationDedupingCache=function(){s.clear()},t.getInvestigationDedupingCache=function(e){return s.get(e)??new Map},t.saveMachineMetric=function(){const e=process.cpuUsage(),t=o.performance.eventLoopUtilization();a.push({cpuUsage:e,elu:t,timestamp:Date.now()}),a.length>n.hudConfig.machineMetricsSavedLength&&a.shift()},t.getLastMetrics=function(){return a[0]},t.setInvestigationDurationThresholds=function(e){u=e},t.getFlowIdDurationThresholdAndCount=function(e){return u[e]},t.increaseInvestigationDurationCount=function(e){const t=c.get(e)??0;c.set(e,t+1)},t.getInvestigationDurationCount=function(e){return c.get(e)??0},t.resetInvestigationDurationCounts=function(){c.clear()},t.increaseTotalInvestigationsErrorBased=function(){d++},t.getTotalInvestigationsErrorBased=function(){return d},t.resetTotalInvestigationsErrorBased=function(){d=0},t.increaseTotalInvestigationsDurationBased=function(){l++},t.getTotalInvestigationsDurationBased=function(){return l},t.resetTotalInvestigationsDurationBased=function(){l=0},t.getUniqueSetFailureErrors=function(){return h};const n=r(5809),o=r(2987);let i=[];t.globalInvestigationTracking=0;const s=new Map,a=[];let u={};const c=new Map;let d=0,l=0;const h=new Set},7764:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=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,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),o(r(4821),t),o(r(754),t),o(r(3025),t),o(r(8714),t),o(r(4988),t),o(r(4583),t)},7859:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricFactory=t.BaseMetric=void 0;class r{}class n extends r{flowId;count;sumDuration;sumSquaredDuration;sketchBuilder;errorBreakdown;constructor(e,t){super(),this.flowId=e.flow_id,this.count=1,this.sumDuration=e.duration,this.sumSquaredDuration=e.duration**2,this.sketchBuilder=t.newSketchDataWithValue(e.duration),this.errorBreakdown=new Map,e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}getEventVersion(){return"1.0.0"}updateErrorBreakdown(e){let t=this.errorBreakdown.get(e.key);void 0===t&&(t={errors:e.errors,count:0,caught:e.caught,key:e.key,framework_result:e.framework_result,user_error:e.user_error},this.errorBreakdown.set(e.key,t)),t.count+=1}update(e,t){this.sumDuration+=e.duration,this.sumSquaredDuration+=e.duration**2,this.count+=1,t.add(this.sketchBuilder,e.duration),void 0!==e.error_breakdown&&this.updateErrorBreakdown(e.error_breakdown)}finalize(e,t,r){return{flow_id:this.flowId,count:this.count,sum_duration:this.sumDuration,sum_squared_duration:this.sumSquaredDuration,timestamp:t,timeslice:r,sketch:e.encode(this.sketchBuilder),error_breakdown:Array.from(this.errorBreakdown.values()).map(e=>({errors:e.errors,count:e.count,caught:e.caught,framework_result:e.framework_result,user_error:e.user_error}))}}}t.BaseMetric=n;class o extends n{errors;flowType;constructor(e,t){super(e,t),this.errors={},this.flowType=e.flow_type,e.error&&(this.errors[e.error]=1)}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}getEventVersion(){return"1.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),errors:this.errors,flow_type:this.flowType}}}class i{static registry={};static registerMetric(e,t){i.registry[e]=t}static createMetric(e,t){const r=i.registry[e.type];if(!r)throw new Error(`Unknown metric type: ${e.type}`);return new r(e,t)}}t.MetricFactory=i,i.registerMetric("EndpointMetric",class extends n{method;statusCode;errors;endReason;constructor(e,t){super(e,t),this.method=e.method,this.statusCode=e.status_code,this.endReason=e.end_reason,this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}getEventVersion(){return"2.0.1"}finalize(e,t,r){return{...super.finalize(e,t,r),method:this.method,...void 0!==this.statusCode?{status_code:this.statusCode}:{},errors:this.errors,...void 0!==this.endReason?{end_reason:this.endReason}:{}}}}),i.registerMetric("GraphQLMetric",class extends n{statusCode;errorsCount;constructor(e,t){super(e,t),this.statusCode=e.status_code,this.errorsCount=e.error_occurred?1:0}update(e,t){super.update(e,t),this.errorsCount+=e.error_occurred?1:0}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),status_code:this.statusCode,errors_count:this.errorsCount}}}),i.registerMetric("KafkaJSMetric",class extends n{partition;errors;ConsumeSketchBuilder;sumConsumedDuration;sumSquaredConsumedDuration;constructor(e,t){super(e,t),this.partition=e.partition,this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1),e.total_consume_duration&&(this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration)),this.sumConsumedDuration=e.total_consume_duration??0,this.sumSquaredConsumedDuration=(e.total_consume_duration??0)**2}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1),e.total_consume_duration&&(this.sumConsumedDuration+=e.total_consume_duration,this.sumSquaredConsumedDuration+=e.total_consume_duration**2,this.ConsumeSketchBuilder?t.add(this.ConsumeSketchBuilder,e.total_consume_duration):this.ConsumeSketchBuilder=t.newSketchDataWithValue(e.total_consume_duration))}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),partition:this.partition,errors:this.errors,sum_consumed_duration:this.sumConsumedDuration,sum_squared_consumed_duration:this.sumSquaredConsumedDuration,sketch_consume:e.encode(this.ConsumeSketchBuilder)}}}),i.registerMetric("SqsMetric",class extends n{msgCount;errors;e2eData;constructor(e,t){super(e,t),this.msgCount=e.msg_count,this.errors=e.errors,e.e2e_duration&&(this.e2eData={duration:e.e2e_duration,squaredDuration:e.e2e_duration**2,sketchBuilder:t.newSketchDataWithValue(e.e2e_duration)})}update(e,t){super.update(e,t),this.msgCount&&e.msg_count&&(this.msgCount+=e.msg_count),Object.entries(e.errors).forEach(([e,t])=>{this.errors[e]=(this.errors[e]??0)+t}),this.e2eData&&e.e2e_duration&&(this.e2eData.duration+=e.e2e_duration,this.e2eData.squaredDuration+=e.e2e_duration**2,t.add(this.e2eData.sketchBuilder,e.e2e_duration))}getEventVersion(){return"2.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),errors:this.errors,msg_count:this.msgCount,...this.e2eData?{e2e_sum_duration:this.e2eData.duration,e2e_sum_squared_duration:this.e2eData.squaredDuration,e2e_sketch:e.encode(this.e2eData.sketchBuilder)}:{}}}}),i.registerMetric("GenericFlowMetric",o),i.registerMetric("GenericQueueMetric",class extends o{msgCount;e2eData;constructor(e,t){super(e,t),void 0!==e.msg_count&&(this.msgCount=e.msg_count),e.e2e_duration&&(this.e2eData={duration:e.e2e_duration,squaredDuration:e.e2e_duration**2,sketchBuilder:t.newSketchDataWithValue(e.e2e_duration)})}update(e,t){super.update(e,t),void 0!==e.msg_count&&(this.msgCount=(this.msgCount??0)+e.msg_count),this.e2eData&&e.e2e_duration&&(this.e2eData.duration+=e.e2e_duration,this.e2eData.squaredDuration+=e.e2e_duration**2,t.add(this.e2eData.sketchBuilder,e.e2e_duration))}finalize(e,t,r){return{...super.finalize(e,t,r),...void 0!==this.msgCount?{msg_count:this.msgCount}:{},...this.e2eData?{e2e_sum_duration:this.e2eData.duration,e2e_sum_squared_duration:this.e2eData.squaredDuration,e2e_sketch:e.encode(this.e2eData.sketchBuilder)}:{}}}}),i.registerMetric("CustomFlowMetric",class extends n{errors;constructor(e,t){super(e,t),this.errors={},e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}update(e,t){super.update(e,t),e.error&&(this.errors[e.error]=(this.errors[e.error]??0)+1)}getEventVersion(){return"1.0.0"}finalize(e,t,r){return{...super.finalize(e,t,r),errors:this.errors}}})},7918:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.storeLoadedOutbound=function(e){r.push(e)},t.getLoadedOutboundsFromStorage=function(){const e=r;return r=[],e},t.getIoredisFunctionId=function(e){return n.get(e)},t.storeIoredisCommand=function(e,t){n.has(e)||o.add(e),n.set(e,t)},t.getIoredisCommandsFromStorage=function(){const e=Array.from(o);return o=new Set,e};let r=[];const n=new Map;let o=new Set},8167:e=>{e.exports=require("worker_threads")},8528:e=>{e.exports=require("./dto")},8708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.setLambdaExtensionId=function(e){o&&n.app_logger.warning("Lambda extension id already set"),o=e},t.getLambdaExtensionId=function(){return o};const n=r(523);let o},8714:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKafkaJSTopics=function(){const e=r;return r=[],e},t.storeKafkaJSTopicDeclaration=function(e){r.push(e)};let r=[]}},t={};return function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}(820)})());
2
2
  //# sourceMappingURL=globalstate.js.map