hud-sdk 1.6.40 → 1.7.0

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/dist/cjs/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1638:e=>{e.exports=require("./declarations")},1943:e=>{e.exports=require("fs/promises")},1952:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createDirectoryExcludeCheckers=c,t.shouldExcludeDirectory=u,t.getAllFilesInDirectory=f,t.getNodeModulesFiles=p,t.getFiles=async function(e,t,i,r){const o=[],n=c(r||[]);for(const t of e){const e=await f(t,n);o.push(...e)}if(i){const e=await p(i,t);o.push(...e)}return o};const o=i(2030),n=i(1943),s=r(i(6928));function a(e){return e.endsWith(".js")}function l(e){return e.split(s.default.sep).join("/")}function c(e){const t=[];for(const i of e){let e,r=l(i);if(r.endsWith("/")||(r+="/"),r.startsWith("/")||s.default.isAbsolute(i)||(r="/"+r),r.includes("*")){const t=r.split(".").join("\\.").split("*").join(".*?"),i=new RegExp(t);e=e=>{const t=l(e),r=t.endsWith("/")?t:t+"/";return i.test(r)}}else e=e=>{const t=l(e);return(t.endsWith("/")?t:t+"/").includes(r)};t.push(e)}return t}function u(e,t){for(const i of t)if(i(e))return!0;return!1}async function d(e,t,i){const r=[];let o;try{o=await(0,n.readdir)(e,{withFileTypes:!0})}catch{return r}for(const n of o){const o=s.default.join(e,n.name);if(n.isFile())a(o)&&!t(o)&&r.push(n);else if(n.isDirectory()&&!i(o)){const e=await d(o,t,i);r.push(...e)}}return r}async function f(e,t){const i=t||[];return d(e,()=>!1,e=>"node_modules"===s.default.basename(e)||u(e,i))}async function p(e,t){return d(e.endsWith(s.default.sep)?e:e+s.default.sep,e=>(0,o.skip)(e,t),()=>!1)}},2030:e=>{e.exports=require("./instrument")},2546:e=>{e.exports=require("./lib")},2698:e=>{e.exports=require("p-limit")},3106:e=>{e.exports=require("zlib")},3903:e=>{e.exports=require("uuid")},4672:e=>{e.exports=require("./client")},5258:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initCliLoggerContext=function(e,t,i){o=e,s=t,n=i},t.flushAllLogs=a,t.wrapMainWithAutoFlush=function(e){return async()=>{try{await e(),await a()}catch(e){throw await a(),e}}};const r=i(523);let o,n,s;async function a(){try{if(!o)return;if(!s)return;const e=(0,r.getSavedLogs)();if(0===e.length)return;for(const t of e)try{await s.sessionslessLogs(t,o,n,"cli")}catch(e){r.cli_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch{}}},5809:e=>{e.exports=require("./config")},6858:e=>{e.exports=require("commander")},6928:e=>{e.exports=require("path")},8184:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=i(5809),n=i(1638),s=i(8528),a=i(2030),l=i(2546),c=i(523),u=r(i(8938)),d=i(6858),f=i(4672),p=i(9896),g=i(1943),h=r(i(2698)),m=r(i(6928)),y=i(9561),w=i(3903),x=r(i(3106)),_=i(5258),F=i(1952);function v(e){const t=(0,c.formatLogMessage)(e.message,e.errCode,e.moreInfo);console.log(t)}async function C(e,t,i){try{return await(0,g.writeFile)(e,t,i),!0}catch{return!1}}async function P(e,t){try{return await(0,g.rename)(e,t),!0}catch{return!1}}async function M(e){try{await(0,g.unlink)(e)}catch{}}async function E(e){const t=(0,h.default)(20);await Promise.all(e.map(e=>t(async()=>{await Promise.all([M(e.filePath+".hud"),M(e.filePath+".hud.map")])})))}async function I(e,t,i,r){const a=(await t.getUploadUrls(i,r,1))[0];c.cli_logger.info("Got upload URL");const d={...f.HudClient.defaultRequest,send_time:(new Date).toISOString(),build_id:i,token:r,sdk_version:o.SDK_VERSION};let p=[];const g=e.map(e=>e.metadatas[0]);try{p=await(0,l.getFilesForDeclarations)(g,t.sendFileDeclarationsCi.bind(t,d))}catch{p=g}c.cli_logger.info("Got files for declarations",{filesCount:p.length});const m=await async function(e){const t=(0,h.default)(process.env.HUD_PARSE_DECLARATIONS_LIMIT?parseInt(process.env.HUD_PARSE_DECLARATIONS_LIMIT):20),i=x.default.createGzip();let r=0;return await Promise.all(e.map(e=>t(async()=>{try{const t=await(0,l.readFile)(e.filename,e.indexOffset,e.indexOffsetEnd);if(!t)return r++,{declarations:[],blacklist:void 0};const o=await(0,n.parseDeclarations)(e,t);i.write(JSON.stringify(function(e){const t=(new Date).toISOString();return{...f.HudClient.defaultRequest,type:"FunctionDeclaration",arr:e,send_time:t,event_version:s.FUNCTION_DECLARATION_VERSION}}(o.declarations))),i.write("\n")}catch{return r++,{declarations:[],blacklist:void 0}}}))),i.end(),r>0&&c.cli_logger.error("Failed to parse declarations for files",{failedFiles:r}),i}(p);try{await async function(e,t,i,r,o){const n=await(0,y.buffer)(e);let s=t;for(let e=1;e<=3;e++)try{return await u.default.put(s,n,{headers:{"Content-Encoding":"gzip","Content-Type":"application/x-ndjson"}}),void c.cli_logger.info("Uploaded requests")}catch(t){if(!(u.default.isAxiosError(t)&&405===t.response?.status&&e<3))throw t;c.cli_logger.warning("Upload failed with 405 status, retrying",{attempt:e+1,totalAttempts:3,currentUploadUrl:s}),s=(await i.getUploadUrls(r,o,1))[0]}}(m,a,t,i,r),c.cli_logger.info("Upload completed")}catch(e){c.cli_logger.warning("Failed to upload requests, still instrumenting files",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),v(l.UserErrorLogs.HudCliUploadFailed())}}function D(e){const t=m.default.resolve(e);if(!(0,p.existsSync)(t))throw new Error(`Directory does not exist: ${e}`);return t}(0,_.wrapMainWithAutoFlush)(async function(){const e=new d.Command;e.requiredOption("--api-key <string>","Your Hud API key").requiredOption("--dirs <list>","Comma-separated directories to scan").option("--include-modules <list>","Comma-separated module names to trace").option("--node-modules-path <string>","Path to node_modules").option("--max-mapped-functions <number>","Max number of mapped functions").option("--exclude-dirs-patterns <list>","Comma-separated wildcard patterns to exclude directories. Note: relative paths are not supported. Example: 'dist/frontend,*test*'").parse(process.argv);const t=e.opts(),i={apiKey:t.apiKey,modulesToTrace:t.includeModules?t.includeModules.split(",").map(e=>e.trim()):[],dirs:t.dirs.split(",").map(e=>e.trim()),nodeModulesPath:t.nodeModulesPath,maxMappedFunctions:t.maxMappedFunctions,excludeDirsPatterns:t.excludeDirsPatterns?t.excludeDirsPatterns.split(",").map(e=>e.trim()):void 0},r=(0,w.v4)(),n=new f.HudClient;if((0,_.initCliLoggerContext)(t.apiKey,n,r),c.cli_logger.info("CLI build started",{buildId:r,args:i}),!await n.validateToken(t.apiKey))return v(l.UserErrorLogs.HudCliInvalidKey()),void c.cli_logger.critical("Invalid API key");let u,g;i.maxMappedFunctions&&(o.hudConfig.userConfig.maxMappedFunctions={value:i.maxMappedFunctions,source:"SETUP"});try{({dirs:u,nodeModulesPath:g}=function(e){const t=[];let i;for(const i of e.dirs)try{t.push(D(i))}catch(e){throw v(l.UserErrorLogs.HudCliInvalidDirectory(i)),e}if(e.nodeModulesPath)try{i=D(e.nodeModulesPath)}catch(t){throw v(l.UserErrorLogs.HudCliInvalidDirectory(e.nodeModulesPath)),t}return{dirs:t,nodeModulesPath:i}}(i))}catch{return void c.cli_logger.critical("Failed to validate directories")}const y=(0,a.createCheckers)(i.modulesToTrace),x=await(0,F.getFiles)(u,y,g,i.excludeDirsPatterns);if(0===x.length)return c.cli_logger.critical("No .js files to instrument"),void v(l.UserErrorLogs.HudCliNoJsFiles());c.cli_logger.info("Found files to instrument",{filesCount:x.length});const L=await async function(e,t){const i=(0,h.default)(20);return await Promise.all(e.map(e=>i(async()=>async function(e,t){try{if(globalThis.hudRunningMode===s.HudRunningMode.detached)return{status:"skipped"};const i=m.default.join(e.parentPath??e.path,e.name),r=(0,p.readFileSync)(i,"utf-8");if((0,a.parseCliInstrumentationPattern)(r))return{status:"skipped"};const{transformedCode:o,metadatas:n}=(0,a.editWithCliBuildId)(r,i,s.Format.cjs,t);return n[0].detectedForAwaitLoops>0&&c.instrument_logger.warning(`Detected for-await loops in file ${i}`,{detectedForAwaitLoops:n[0].detectedForAwaitLoops}),await async function(e,t,i){const r=(0,l.combineSourceMaps)(t,i);return!(!r||!await C(i+".hud",e)||!await C(i+".hud.map",r,"utf-8")&&(await M(i+".hud"),1))}(o,n,i)?{status:"success",metadatas:n.map(e=>(0,l.sourceFileMetadataToTransferSourceFileMetadata)(e)),filePath:i}:{status:"failed"}}catch{return{status:"failed"}}}(e,t))))}(x,r);if(globalThis.hudRunningMode===s.HudRunningMode.detached)return c.cli_logger.critical("Max mapped functions exceeded",{maxMappedFunctions:o.hudConfig.userConfig.maxMappedFunctions?.value??0}),v(l.UserErrorLogs.HudCliInstrumentedFunctionCountExceeded(o.hudConfig.userConfig.maxMappedFunctions?.value??0)),void await E(L.filter(e=>"success"===e.status).map(e=>({filePath:e.filePath})));const U=await async function(e){const t=e.filter(e=>void 0===e||"failed"===e.status);t.length>0&&c.cli_logger.warning("Failed to edit files",{failedFiles:t.length,totalFiles:e.length});const i=e.filter(e=>"skipped"===e.status);if(i.length>0){if(i.length===e.length)return v(l.UserErrorLogs.HudCliAllFilesInstrumented()),void c.cli_logger.info("No files instrumented");v(l.UserErrorLogs.HudCliSomeFilesInstrumented()),c.cli_logger.info("Skipped files",{skippedFiles:i.length,totalFiles:e.length})}const r=e.filter(e=>"success"===e.status);return r.length>0&&c.cli_logger.info("Edited files",{successFiles:r.length}),r}(L);if(U&&0!==U.length)try{c.cli_logger.info("Parsing declarations for files",{filesCount:U.length}),await I(U,n,r,i.apiKey),await async function(e){const t=(0,h.default)(20);await Promise.all(e.map(e=>t(async()=>{await P(e.filePath+".hud",e.filePath)?await P(e.filePath+".hud.map",e.filePath+".map"):(await M(e.filePath+".hud"),await M(e.filePath+".hud.map"))})))}(U),c.cli_logger.info("Files written to disk"),c.cli_logger.info("Done"),v(l.UserLogs.HudCliCompletedSuccessfully(U.length))}catch(e){throw c.cli_logger.critical("Failed to instrument files, deleting files",{msg:e instanceof Error?e.message:void 0}),await E(U),e}finally{try{await n.completed(r,i.apiKey),c.cli_logger.info("Build completed notification sent")}catch(e){c.cli_logger.error("Failed to send completed request",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}})().catch(async()=>{try{v(l.UserErrorLogs.HudCliUnkownError())}catch{}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9561:e=>{e.exports=require("stream/consumers")},9896:e=>{e.exports=require("fs")}},t={};return function i(r){var o=t[r];if(void 0!==o)return o.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,i),n.exports}(8184)})());
2
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1638:e=>{e.exports=require("./declarations")},1943:e=>{e.exports=require("fs/promises")},1952:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createDirectoryExcludeCheckers=c,t.shouldExcludeDirectory=u,t.getAllFilesInDirectory=f,t.getNodeModulesFiles=p,t.getFiles=async function(e,t,i,r){const o=[],n=c(r||[]);for(const t of e){const e=await f(t,n);o.push(...e)}if(i){const e=await p(i,t);o.push(...e)}return o};const o=i(2030),n=i(1943),s=r(i(6928));function a(e){return e.endsWith(".js")}function l(e){return e.split(s.default.sep).join("/")}function c(e){const t=[];for(const i of e){let e,r=l(i);if(r.endsWith("/")||(r+="/"),r.startsWith("/")||s.default.isAbsolute(i)||(r="/"+r),r.includes("*")){const t=r.split(".").join("\\.").split("*").join(".*?"),i=new RegExp(t);e=e=>{const t=l(e),r=t.endsWith("/")?t:t+"/";return i.test(r)}}else e=e=>{const t=l(e);return(t.endsWith("/")?t:t+"/").includes(r)};t.push(e)}return t}function u(e,t){for(const i of t)if(i(e))return!0;return!1}async function d(e,t,i){const r=[];let o;try{o=await(0,n.readdir)(e,{withFileTypes:!0})}catch{return r}for(const n of o){const o=s.default.join(e,n.name);if(n.isFile())a(o)&&!t(o)&&r.push(n);else if(n.isDirectory()&&!i(o)){const e=await d(o,t,i);r.push(...e)}}return r}async function f(e,t){const i=t||[];return d(e,()=>!1,e=>"node_modules"===s.default.basename(e)||u(e,i))}async function p(e,t){return d(e.endsWith(s.default.sep)?e:e+s.default.sep,e=>(0,o.skip)(e,t),()=>!1)}},2030:e=>{e.exports=require("./instrument")},2546:e=>{e.exports=require("./lib")},2698:e=>{e.exports=require("p-limit")},3106:e=>{e.exports=require("zlib")},3903:e=>{e.exports=require("uuid")},4672:e=>{e.exports=require("./client")},5258:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.initCliLoggerContext=function(e,t,i){o=e,s=t,n=i},t.flushAllLogs=a,t.wrapMainWithAutoFlush=function(e){return async()=>{try{await e(),await a()}catch(e){throw await a(),e}}};const r=i(523);let o,n,s;async function a(){try{if(!o)return;if(!s)return;const e=(0,r.getSavedLogs)();if(0===e.length)return;for(const t of e)try{await s.sessionslessLogs(t,o,n,"cli")}catch(e){r.cli_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch{}}},5809:e=>{e.exports=require("./config")},6858:e=>{e.exports=require("commander")},6928:e=>{e.exports=require("path")},8184:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=i(5809),n=i(1638),s=i(8528),a=i(2030),l=i(2546),c=i(523),u=r(i(8938)),d=i(6858),f=i(4672),p=i(9896),g=i(1943),h=r(i(2698)),m=r(i(6928)),y=i(9561),w=i(3903),_=r(i(3106)),x=i(5258),F=i(1952);function v(e){const t=(0,c.formatLogMessage)(e.message,e.errCode,e.moreInfo);console.log(t)}async function C(e,t,i){try{return await(0,g.writeFile)(e,t,i),!0}catch{return!1}}async function P(e,t){try{return await(0,g.rename)(e,t),!0}catch{return!1}}async function M(e){try{await(0,g.unlink)(e)}catch{}}async function E(e){const t=(0,h.default)(20);await Promise.all(e.map(e=>t(async()=>{await Promise.all([M(e.filePath+".hud"),M(e.filePath+".hud.map")])})))}async function I(e,t,i,r){const a=(await t.getUploadUrls(i,r,1))[0];c.cli_logger.info("Got upload URL");const d={...f.HudClient.defaultRequest,send_time:(new Date).toISOString(),build_id:i,token:r,sdk_version:o.SDK_VERSION};let p=[];const g=e.map(e=>e.metadatas[0]);try{p=await(0,l.getFilesForDeclarations)(g,t.sendFileDeclarationsCi.bind(t,d))}catch{p=g}c.cli_logger.info("Got files for declarations",{filesCount:p.length});const m=await async function(e){const t=(0,h.default)(process.env.HUD_PARSE_DECLARATIONS_LIMIT?parseInt(process.env.HUD_PARSE_DECLARATIONS_LIMIT):20),i=_.default.createGzip();let r=0;return await Promise.all(e.map(e=>t(async()=>{try{const t=await(0,l.readFile)(e.filename,e.indexOffset,e.indexOffsetEnd);if(!t)return r++,{declarations:[],blacklist:void 0};const o=await(0,n.parseDeclarations)(e,t);i.write(JSON.stringify(function(e){const t=(new Date).toISOString();return{...f.HudClient.defaultRequest,type:"FunctionDeclaration",arr:e,send_time:t,event_version:s.FUNCTION_DECLARATION_VERSION}}(o.declarations))),i.write("\n")}catch{return r++,{declarations:[],blacklist:void 0}}}))),i.end(),r>0&&c.cli_logger.error("Failed to parse declarations for files",{failedFiles:r}),i}(p);try{await async function(e,t,i,r,o){const n=await(0,y.buffer)(e);let s=t;for(let e=1;e<=3;e++)try{return await u.default.put(s,n,{headers:{"Content-Encoding":"gzip","Content-Type":"application/x-ndjson"}}),void c.cli_logger.info("Uploaded requests")}catch(t){if(!(u.default.isAxiosError(t)&&405===t.response?.status&&e<3))throw t;c.cli_logger.warning("Upload failed with 405 status, retrying",{attempt:e+1,totalAttempts:3,currentUploadUrl:s}),s=(await i.getUploadUrls(r,o,1))[0]}}(m,a,t,i,r),c.cli_logger.info("Upload completed")}catch(e){c.cli_logger.warning("Failed to upload requests, still instrumenting files",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),v(l.UserErrorLogs.HudCliUploadFailed())}}function D(e){const t=m.default.resolve(e);if(!(0,p.existsSync)(t))throw new Error(`Directory does not exist: ${e}`);return t}(0,x.wrapMainWithAutoFlush)(async function(){const e=new d.Command;e.requiredOption("--api-key <string>","Your Hud API key").requiredOption("--dirs <list>","Comma-separated directories to scan").option("--include-modules <list>","Comma-separated module names to trace").option("--node-modules-path <string>","Path to node_modules").option("--max-mapped-functions <number>","Max number of mapped functions").option("--exclude-dirs-patterns <list>","Comma-separated wildcard patterns to exclude directories. Note: relative paths are not supported. Example: 'dist/frontend,*test*'").parse(process.argv);const t=e.opts(),i={apiKey:t.apiKey,modulesToTrace:t.includeModules?t.includeModules.split(",").map(e=>e.trim()):[],dirs:t.dirs.split(",").map(e=>e.trim()),nodeModulesPath:t.nodeModulesPath,maxMappedFunctions:t.maxMappedFunctions,excludeDirsPatterns:t.excludeDirsPatterns?t.excludeDirsPatterns.split(",").map(e=>e.trim()):void 0},r=(0,w.v4)(),n=new f.HudClient;if((0,x.initCliLoggerContext)(t.apiKey,n,r),c.cli_logger.info("CLI build started",{buildId:r,args:i}),!await n.validateToken(t.apiKey)&&"true"!==process.env.HUD_SKIP_TOKEN_VALIDATION)return v(l.UserErrorLogs.HudCliInvalidKey()),void c.cli_logger.critical("Invalid API key");let u,g;i.maxMappedFunctions&&(o.hudConfig.userConfig.maxMappedFunctions={value:i.maxMappedFunctions,source:"SETUP"});try{({dirs:u,nodeModulesPath:g}=function(e){const t=[];let i;for(const i of e.dirs)try{t.push(D(i))}catch(e){throw v(l.UserErrorLogs.HudCliInvalidDirectory(i)),e}if(e.nodeModulesPath)try{i=D(e.nodeModulesPath)}catch(t){throw v(l.UserErrorLogs.HudCliInvalidDirectory(e.nodeModulesPath)),t}return{dirs:t,nodeModulesPath:i}}(i))}catch{return void c.cli_logger.critical("Failed to validate directories")}const y=(0,a.createCheckers)(i.modulesToTrace),_=await(0,F.getFiles)(u,y,g,i.excludeDirsPatterns);if(0===_.length)return c.cli_logger.critical("No .js files to instrument"),void v(l.UserErrorLogs.HudCliNoJsFiles());c.cli_logger.info("Found files to instrument",{filesCount:_.length});const L=await async function(e,t){const i=(0,h.default)(20);return await Promise.all(e.map(e=>i(async()=>async function(e,t){try{if(globalThis.hudRunningMode===s.HudRunningMode.detached)return{status:"skipped"};const i=m.default.join(e.parentPath??e.path,e.name),r=(0,p.readFileSync)(i,"utf-8");if((0,a.parseCliInstrumentationPattern)(r))return{status:"skipped"};const{transformedCode:o,metadatas:n}=(0,a.editWithCliBuildId)(r,i,s.Format.cjs,t);return n[0].detectedForAwaitLoops>0&&c.instrument_logger.warning(`Detected for-await loops in file ${i}`,{detectedForAwaitLoops:n[0].detectedForAwaitLoops}),await async function(e,t,i){const r=(0,l.combineSourceMaps)(t,i);return!(!r||!await C(i+".hud",e)||!await C(i+".hud.map",r,"utf-8")&&(await M(i+".hud"),1))}(o,n,i)?{status:"success",metadatas:n.map(e=>(0,l.sourceFileMetadataToTransferSourceFileMetadata)(e)),filePath:i}:{status:"failed"}}catch{return{status:"failed"}}}(e,t))))}(_,r);if(globalThis.hudRunningMode===s.HudRunningMode.detached)return c.cli_logger.critical("Max mapped functions exceeded",{maxMappedFunctions:o.hudConfig.userConfig.maxMappedFunctions?.value??0}),v(l.UserErrorLogs.HudCliInstrumentedFunctionCountExceeded(o.hudConfig.userConfig.maxMappedFunctions?.value??0)),void await E(L.filter(e=>"success"===e.status).map(e=>({filePath:e.filePath})));const U=await async function(e){const t=e.filter(e=>void 0===e||"failed"===e.status);t.length>0&&c.cli_logger.warning("Failed to edit files",{failedFiles:t.length,totalFiles:e.length});const i=e.filter(e=>"skipped"===e.status);if(i.length>0){if(i.length===e.length)return v(l.UserErrorLogs.HudCliAllFilesInstrumented()),void c.cli_logger.info("No files instrumented");v(l.UserErrorLogs.HudCliSomeFilesInstrumented()),c.cli_logger.info("Skipped files",{skippedFiles:i.length,totalFiles:e.length})}const r=e.filter(e=>"success"===e.status);return r.length>0&&c.cli_logger.info("Edited files",{successFiles:r.length}),r}(L);if(U&&0!==U.length)try{c.cli_logger.info("Parsing declarations for files",{filesCount:U.length}),await I(U,n,r,i.apiKey),await async function(e){const t=(0,h.default)(20);await Promise.all(e.map(e=>t(async()=>{await P(e.filePath+".hud",e.filePath)?await P(e.filePath+".hud.map",e.filePath+".map"):(await M(e.filePath+".hud"),await M(e.filePath+".hud.map"))})))}(U),c.cli_logger.info("Files written to disk"),c.cli_logger.info("Done"),v(l.UserLogs.HudCliCompletedSuccessfully(U.length))}catch(e){throw c.cli_logger.critical("Failed to instrument files, deleting files",{msg:e instanceof Error?e.message:void 0}),await E(U),e}finally{try{await n.completed(r,i.apiKey),c.cli_logger.info("Build completed notification sent")}catch(e){c.cli_logger.error("Failed to send completed request",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}})().catch(async()=>{try{v(l.UserErrorLogs.HudCliUnkownError())}catch{}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9561:e=>{e.exports=require("stream/consumers")},9896:e=>{e.exports=require("fs")}},t={};return function i(r){var o=t[r];if(void 0!==o)return o.exports;var n=t[r]={exports:{}};return e[r].call(n.exports,n,n.exports,i),n.exports}(8184)})());
3
3
  //# sourceMappingURL=cli.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={1569:e=>{e.exports=require("zod")},2210:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_MODULE_NAME=void 0,t.SDK_MODULE_NAME="hud-sdk"},2509:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),a=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=t.SDK_MODULE_NAME=void 0,a(n(2887),t),a(n(2570),t);var r=n(2210);Object.defineProperty(t,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return r.SDK_MODULE_NAME}}),a(n(7089),t);var o=n(5453);Object.defineProperty(t,"SDK_VERSION",{enumerable:!0,get:function(){return o.SDK_VERSION}})},2570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateDynamicConfig=function(e,t,n){const r=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!r.success)return n.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:r,remoteConfig:e}),t.dynamicConfig;const o=a(t.dynamicConfig,r.data);return void 0!==o.enableInvestigation&&o.enableInvestigation!==t.dynamicConfig.enableInvestigation&&(n.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o.enableInvestigation}),t.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o.enableInvestigation)),void 0!==o.enableInvestigationArgsSending&&o.enableInvestigationArgsSending!==t.dynamicConfig.enableInvestigationArgsSending&&(n.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:o.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=o.enableInvestigationArgsSending),void 0!==o?.investigationRateLimits?.executionFlowMaxLength&&o?.investigationRateLimits?.executionFlowMaxLength!==t.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=o.investigationRateLimits.executionFlowMaxLength),void 0!==o?.investigationRateLimits?.exceptionMaxLength&&o?.investigationRateLimits?.exceptionMaxLength!==t.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=o.investigationRateLimits.exceptionMaxLength),o};const i=n(2887);function a(e,t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(e)&&Array.isArray(t))return t;const n={...e};for(const i in t){const r=e[i],o=t[i];n[i]=a(r,o)}return n}},2887:function(e,t,n){var i,a=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}: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]&&a(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudFailedReadConfigError=t.hudConfig=t.HudDynamicConfigSchema=void 0,t.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},t.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let t;if(e)try{t=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{t=new Map}return t},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)},t.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let t=__dirname,n=0;for(;"/"!==t&&n<10;){const e=`${t}/hud.config`;if(l.existsSync(e))return e;t=u.dirname(t),n++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(t){throw new f(e,t.code)}};const s=n(8528),l=o(n(9896)),u=o(n(6928)),d=n(3903),c=n(1569),m="globalThis._hudMark";t.HudDynamicConfigSchema=c.z.object({aggregationInterval:c.z.number(),aggregationFirstSendTimeout:c.z.number(),investigationInterval:c.z.number(),investigationFirstSendTimeout:c.z.number(),enableInvestigation:c.z.boolean(),enableInvestigationArgsSending:c.z.boolean(),investigationRateLimits:c.z.object({maxSameInvestigations:c.z.number().int().positive(),sameInvestigationTimeWindowMs:c.z.number().int().positive(),maxTotalInvestigations:c.z.number().int().positive(),maxTotalInvestigationsErrorBased:c.z.number().int().positive(),maxTotalInvestigationsDurationBased:c.z.number().int().positive(),totalInvestigationTimeWindowMs:c.z.number().int().positive(),maxUniqLogs:c.z.number().int().positive(),maxStringLength:c.z.number().int().positive(),maxArrayLength:c.z.number().int().positive(),maxObjectDepth:c.z.number().int().positive(),maxKeyLength:c.z.number().int().positive(),executionFlowMaxLength:c.z.number().int().positive(),exceptionMaxLength:c.z.number().int().positive()}),machineMetricsInterval:c.z.number().int().positive(),blacklistParams:c.z.array(c.z.string()),forensicsBlacklistFields:c.z.array(c.z.string()),forensicsWhitelistFields:c.z.array(c.z.string()),censorshipRegexes:c.z.array(c.z.object({regex:c.z.string(),replacement:c.z.string()})),reingestInterval:c.z.number().int().positive(),extraHeaders:c.z.array(c.z.string()),performanceMetricsInterval:c.z.number().int().positive(),enableOutboundData:c.z.boolean(),maxTotalOutbounds:c.z.number().int().positive(),maxOutboundCountWithData:c.z.number().int().positive(),maxHTTPRequestBodySize:c.z.number().int().positive(),maxHTTPResponseBodySize:c.z.number().int().positive()});const g=process.env.HUD_ENABLE_INVESTIGATION,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"},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:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,workerGrace:6e4,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:p,wrapVarPrefix:v,functionIdVarName:`${v}_fid`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[u.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(u.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[u.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.25.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs"}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js"}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request"}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===g,enableInvestigationArgsSending:!0,investigationRateLimits:{maxSameInvestigations:2,sameInvestigationTimeWindowMs:36e5,maxTotalInvestigations:25,maxTotalInvestigationsErrorBased:25,maxTotalInvestigationsDurationBased:20,totalInvestigationTimeWindowMs:216e5,maxUniqLogs:2,executionFlowMaxLength:20,exceptionMaxLength:20,maxStringLength:1024,maxArrayLength:10,maxObjectDepth:3,maxKeyLength:30},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==g,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:(0,d.v5)("axios",p),nodeFetchFunctionId:(0,d.v5)("node-fetch",p),nodeFetchBodiesFunctionIds:{json:(0,d.v5)("node-fetch-body-json",p),text:(0,d.v5)("node-fetch-body-text",p),arrayBuffer:(0,d.v5)("node-fetch-body-arrayBuffer",p),blob:(0,d.v5)("node-fetch-body-blob",p)},requestFunctionId:(0,d.v5)("request-request",p),requestMethodFunctionIds:{get:(0,d.v5)("request-get",p),head:(0,d.v5)("request-head",p),options:(0,d.v5)("request-options",p),post:(0,d.v5)("request-post",p),put:(0,d.v5)("request-put",p),patch:(0,d.v5)("request-patch",p),del:(0,d.v5)("request-del",p),delete:(0,d.v5)("request-delete",p)},pgConnectFunctionId:(0,d.v5)("pg-connect",p),pgQueryFunctionId:(0,d.v5)("pg-query",p),pgEndFunctionId:(0,d.v5)("pg-end",p),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[u.join(u.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"/*modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:m,nextJsMarkStatement:`${m} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};t.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}),t.default=t.hudConfig;class f extends Error{path;code;constructor(e,t){super(),this.path=e,this.code=t}}t.HudFailedReadConfigError=f},3903:e=>{e.exports=require("uuid")},5453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=void 0,t.SDK_VERSION="1.6.40"},6928:e=>{e.exports=require("path")},7089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectStoreConfigSchema=void 0;const i=n(1569),a=i.z.object({type:i.z.literal("s3")}),r=i.z.object({type:i.z.literal("disk"),path:i.z.string()});t.ObjectStoreConfigSchema=i.z.union([a,r])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},t={};return function n(i){var a=t[i];if(void 0!==a)return a.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(2509)})());
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={1569:e=>{e.exports=require("zod")},2210:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_MODULE_NAME=void 0,t.SDK_MODULE_NAME="hud-sdk"},2509:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),a=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=t.SDK_MODULE_NAME=void 0,a(n(2887),t),a(n(2570),t);var r=n(2210);Object.defineProperty(t,"SDK_MODULE_NAME",{enumerable:!0,get:function(){return r.SDK_MODULE_NAME}}),a(n(7089),t);var o=n(5453);Object.defineProperty(t,"SDK_VERSION",{enumerable:!0,get:function(){return o.SDK_VERSION}})},2570:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateDynamicConfig=function(e,t,n){const r=i.HudDynamicConfigSchema.deepPartial().safeParse(e);if(!r.success)return n.error("Dynamic configuration not updated - Invalid configuration override",{remoteConfigParseResult:r,remoteConfig:e}),t.dynamicConfig;const o=a(t.dynamicConfig,r.data);return void 0!==o.enableInvestigation&&o.enableInvestigation!==t.dynamicConfig.enableInvestigation&&(n.info("Dynamic configuration updated - enableInvestigation",{hudEnableInvestigation:o.enableInvestigation}),t.isInvestigationEnabledByEnv||(globalThis.hudEnableInvestigation=o.enableInvestigation)),void 0!==o.enableInvestigationArgsSending&&o.enableInvestigationArgsSending!==t.dynamicConfig.enableInvestigationArgsSending&&(n.info("Dynamic configuration updated - enableInvestigationArgsSending",{hudEnableInvestigationArgsSending:o.enableInvestigationArgsSending}),globalThis.hudEnableInvestigationArgsSending=o.enableInvestigationArgsSending),void 0!==o?.investigationRateLimits?.executionFlowMaxLength&&o?.investigationRateLimits?.executionFlowMaxLength!==t.dynamicConfig.investigationRateLimits.executionFlowMaxLength&&(globalThis.hudExecutionFlowMaxLength=o.investigationRateLimits.executionFlowMaxLength),void 0!==o?.investigationRateLimits?.exceptionMaxLength&&o?.investigationRateLimits?.exceptionMaxLength!==t.dynamicConfig.investigationRateLimits.exceptionMaxLength&&(globalThis.hudExceptionMaxLength=o.investigationRateLimits.exceptionMaxLength),o};const i=n(2887);function a(e,t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(e)&&Array.isArray(t))return t;const n={...e};for(const i in t){const r=e[i],o=t[i];n[i]=a(r,o)}return n}},2887:function(e,t,n){var i,a=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,a)}: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]&&a(t,e,n[o]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudFailedReadConfigError=t.hudConfig=t.HudDynamicConfigSchema=void 0,t.getModulesToTraceFromEnv=function(){const e=process.env.HUD_MONITOR_MODULES||process.env.HUD_INCLUDE_MODULES;if(e)return e.split(",")},t.getFrameworksToEnableFromEnv=function(){const e=process.env.HUD_ENABLE_FRAMEWORKS;let t;if(e)try{t=s.availableFrameworksSchema.parse(JSON.parse(e))}catch{t=new Map}return t},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t.updateInvestigationRateLimitGlobals=function(){globalThis.hudMaxSameInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxSameInvestigations,globalThis.hudMaxTotalInvestigations=t.hudConfig.dynamicConfig.investigationRateLimits.maxTotalInvestigations,globalThis.hudSameInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs)*BigInt(1e6),globalThis.hudTotalInvestigationTimeWindowNs=BigInt(t.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs)*BigInt(1e6)},t.getConfigContent=function(){if(process.env.HUD_CONFIG)return{content:process.env.HUD_CONFIG,source:"HUD_CONFIG"};const e=function(){try{const e=process.env.HUD_CONFIG_PATH;if(e)return l.existsSync(e)?e:void 0;let t=__dirname,n=0;for(;"/"!==t&&n<10;){const e=`${t}/hud.config`;if(l.existsSync(e))return e;t=u.dirname(t),n++}}catch{return}}();if(e)try{return{content:l.readFileSync(e,"utf8"),source:e}}catch(t){throw new h(e,t.code)}};const s=n(8528),l=o(n(9896)),u=o(n(6928)),d=n(3903),c=n(1569);function m(e){return Buffer.from((0,d.parse)(e)).toString("base64").slice(0,22)}const g="globalThis._hudMark";t.HudDynamicConfigSchema=c.z.object({aggregationInterval:c.z.number(),aggregationFirstSendTimeout:c.z.number(),investigationInterval:c.z.number(),investigationFirstSendTimeout:c.z.number(),enableInvestigation:c.z.boolean(),enableInvestigationArgsSending:c.z.boolean(),investigationRateLimits:c.z.object({maxSameInvestigations:c.z.number().int().positive(),sameInvestigationTimeWindowMs:c.z.number().int().positive(),maxTotalInvestigations:c.z.number().int().positive(),maxTotalInvestigationsErrorBased:c.z.number().int().positive(),maxTotalInvestigationsDurationBased:c.z.number().int().positive(),totalInvestigationTimeWindowMs:c.z.number().int().positive(),maxUniqLogs:c.z.number().int().positive(),maxStringLength:c.z.number().int().positive(),maxArrayLength:c.z.number().int().positive(),maxObjectDepth:c.z.number().int().positive(),maxKeyLength:c.z.number().int().positive(),executionFlowMaxLength:c.z.number().int().positive(),exceptionMaxLength:c.z.number().int().positive()}),machineMetricsInterval:c.z.number().int().positive(),blacklistParams:c.z.array(c.z.string()),forensicsBlacklistFields:c.z.array(c.z.string()),forensicsWhitelistFields:c.z.array(c.z.string()),censorshipRegexes:c.z.array(c.z.object({regex:c.z.string(),replacement:c.z.string()})),reingestInterval:c.z.number().int().positive(),extraHeaders:c.z.array(c.z.string()),performanceMetricsInterval:c.z.number().int().positive(),enableOutboundData:c.z.boolean(),maxTotalOutbounds:c.z.number().int().positive(),maxOutboundCountWithData:c.z.number().int().positive(),maxHTTPRequestBodySize:c.z.number().int().positive(),maxHTTPResponseBodySize:c.z.number().int().positive()});const p=process.env.HUD_ENABLE_INVESTIGATION,v="_HUD",b="94a210f3-861c-4e18-ab27-6b6c19437c9d",f={sink:{url:process.env.HUD_HOST||"https://api-prod.hud.io",timeout:5e3,session_attr:"X-Session-ID"},endpoints:{init:"sink/init",send:"sink/send",batch:"sink/batch",logs:"sink/logs",sessionslessLogs:"sink/sessionless-logs",fatalError:"sink/redline",getMode:"sink/getMode",getRemoteConfig:"sink/remote-config/get",fileDeclarations:"sink/file-declarations",sourceMap:"sink/sourcemap",storeObject:"sink/objects/store",getUploadUrls:"sink/registry/get-upload-urls",triggerReingest:"sink/registry/reingest",validateToken:"sink/registry/validate",fileDeclarationsCi:"sink/registry/file-declarations",completed:"sink/registry/completed",endpointsDurationsInvestigationThresholds:"sink/endpoint-configuration"},logger:{default:{levels:{app:"warning",worker:"warning",instrument:"warning"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},investigation:{objectVersion:"1.0.2",store:{type:"s3"}},userConfig:{minPodMemoryMB:{value:250,source:"DEFAULT"},maxMappedFunctions:{value:5e4,source:"DEFAULT"},maxFileSizeBytes:{value:2831155,source:"DEFAULT"},maxTimeUntilInitSessionMs:{value:3e4,source:"DEFAULT"},includeModules:{value:[],source:"DEFAULT"},disableRuntimeInstrumentation:{value:!1,source:"DEFAULT"},disableParametersExtraction:{value:!1,source:"DEFAULT"}},loggerWorkerPortSizeLimit:1e4,customerLoggerLevel:"info",logDirectory:process.env.HUD_LOG_DIR,invocationSampling:new Map([[[300n,null],100],[[200n,300n],50],[[100n,200n],25],[[0n,100n],10]]),callerResetInterval:36e5,modeInterval:3e5,logsSendInterval:6e4,endpointsInterval:3e4,endpointsFirstSendWaitTime:12e4,lazyEndpointsInterval:18e5,staticNextJsEndpointsInterval:1e4,staticNextJsEndpointsMaxAttempts:12,huddBinWidth:1.2,endpointsDurationsInvestigationThresholdsInterval:6e5,workerGrace:6e4,workerTimeout:2e4,timeoutOnRegister:6e4,timeoutOnMetrics:6e4,workerMessageTimeout:1e4,communicationBatchSize:100,writePatched:!1,defaultOff:!0,disableOnBadApiKey:!0,disableOnBadServiceName:!0,cpuTimeCollection:!1,workloadMetadata:{sendInterval:3e5,aws:{imds:{baseURL:"http://169.254.169.254/latest",tokenURI:"/api/token",identityURI:"/dynamic/instance-identity/document",lifeCycleURI:"/meta-data/instance-life-cycle",requestTimeout:5e3},metadataFile:"/run/cloud-init/instance-data.json"},kubernetes:{namespaceFile:"/var/run/secrets/kubernetes.io/serviceaccount/namespace",uuidFile:"/sys/class/dmi/id/product_uuid",podMemoryLimitFile:"/sys/fs/cgroup/memory/memory.stat",podCPULimitFile:"/sys/fs/cgroup/cpuacct/cpu.shares"}},deleteLogsAfterSending:!0,supportSourceMap:!0,editInline:!0,bundlerBuildIdVarName:"hudFileBuildID",bundlerBuildUuidNamespace:"00c1e90b-af75-4d8e-9935-68485877f759",functionUuidNamespace:b,wrapVarPrefix:v,functionInitFunctionName:`${v}i`,functionCatchFunctionName:`${v}c`,functionFinallyFunctionName:`${v}n`,callContextVarName:`${v}x`,fixStackFunctionName:`${v}s`,asyncIteratorWrapperFunctionName:`${v}w`,wrapperUserCatchFunctionName:`${v}u`,beforeYieldFunctionName:`${v}b`,afterYieldFunctionName:`${v}a`,internalBeforeYieldFunctionName:`${v}j`,internalAfterYieldFunctionName:`${v}k`,frameworksToPatch:new Map([["express",{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"express",enableEsbuild:!0}],[u.join("express","lib","application.js"),{framework:s.availableFrameworks.express,enable:!0,version:"<=5",patcher:"expressApplication",enableEsbuild:!0}],["router",{framework:s.availableFrameworks.express,enable:!0,version:"^2.0.0",patcher:"router",enableEsbuild:!0}],["koa",{framework:s.availableFrameworks.koa,enable:!0,version:"^2.0.0",patcher:"koa"}],["graphql/execution/execute",{framework:s.availableFrameworks.graphql,enable:!1,version:"14 - 16",patcher:"graphql"}],["http",{framework:s.availableFrameworks.http,enable:!0,version:"*",patcher:"http"}],["https",{framework:s.availableFrameworks.https,enable:!0,version:"*",patcher:"http"}],["next/dist/server/base-server",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextjs"}],["next/dist/server/lib/module-loader/route-module-loader",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsModuleLoader"}],["next/dist/compiled/next-server/pages-api.runtime.prod",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsRouteModule"}],["next/dist/server/config",{framework:s.availableFrameworks.nextjs,enable:!1,version:">=13.4.0",patcher:"nextJsConfig"}],["@nestjs/core/router/router-execution-context",{framework:s.availableFrameworks.nestjs,enable:!0,version:"*",patcher:"nestjsRouterExecutionContext"}],["kafkajs",{framework:s.availableFrameworks.kafkajs,enable:"win32"!==process.platform,version:">=1.4.0",patcher:"kafkajs"}],["@confluentinc/kafka-javascript",{framework:s.availableFrameworks.confluentKafkaJs,enable:!1,version:">=1.4.0",patcher:"confluentKafkaJs"}],["@nestjs/microservices/context/rpc-context-creator",{framework:s.availableFrameworks.nestjs,enable:"win32"!==process.platform,version:">=7.0.0",patcher:"nestjsRpcContextCreator"}],[["@codegenie/serverless-express","src","frameworks","express.js"].join(u.sep),{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,version:"^4.1.0",patcher:"codeGenieServerlessExpress",enableEsbuild:!0}],["@codegenie/serverless-express",{framework:s.availableFrameworks.codegenieServerlessExpress,enable:!0,enableEsbuild:!0}],["sqs-consumer",{framework:s.availableFrameworks.sqs,enable:!0,version:"*",patcher:"sqsConsumer",extraInfo:{mondayVersion:">=6.1.0",bbcVersion:">=7.5.0"}}],["serverless-http",{framework:s.availableFrameworks.serverlessHttp,enable:!0,enableEsbuild:!0}],[u.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.25.0 <1.0.0 || ^1.0.0",patcher:"outbound/axios",mainFilePath:"axios/dist/node/axios.cjs"}],["node-fetch",{framework:s.availableFrameworks.nodeFetch,enable:!0,version:"^2.0.0",patcher:"outbound/nodeFetch",mainFilePath:"node-fetch/lib/index.js"}],["request",{framework:s.availableFrameworks.request,enable:!0,version:"2.88.2",patcher:"outbound/request"}],["pg",{framework:s.availableFrameworks.pg,enable:!0,version:"^8.8.0",patcher:"outbound/pg"}]]),communicationKeepalive:!1,communicationKeepaliveGrace:5e3,express:{routeNamesSymbol:Symbol.for("hudRoutes"),layerStateSymbol:Symbol.for("hudState"),markedSymbol:Symbol.for("hudMarked"),wrapAllCallbacks:!0},supportedNodeVersions:["18","20","21","22","24"],hudPatchedName:"hudPatched",metricSymbol:Symbol.for("hudMetric"),dynamicConfig:{aggregationInterval:3e5,aggregationFirstSendTimeout:3e4,investigationInterval:5e3,investigationFirstSendTimeout:3e4,enableInvestigation:"true"===p,enableInvestigationArgsSending:!0,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},machineMetricsInterval:1e4,performanceMetricsInterval:6e4,reingestInterval:3e4,extraHeaders:[],enableOutboundData:"true"===process.env.HUD_ENABLE_OUTBOUND_DATA,maxHTTPRequestBodySize:1024,maxHTTPResponseBodySize:5120,blacklistParams:[],censorshipRegexes:[],forensicsBlacklistFields:[],forensicsWhitelistFields:[],maxOutboundCountWithData:process.env.HUD_MAX_OUTBOUND_WITH_DATA?parseInt(process.env.HUD_MAX_OUTBOUND_WITH_DATA):10,maxTotalOutbounds:20},machineMetricsSavedLength:2,isInvestigationEnabledByEnv:void 0!==p,suppressTraces:!0,lambdaMinimunMemory:1024,lambdaBaseGivenTime:400,lambdaExtraGivenTimePerRequest:50,lambdaMaxGivenTime:700,throttleStatusCode:202,axiosFunctionId:m((0,d.v5)("axios",b)),nodeFetchFunctionId:m((0,d.v5)("node-fetch",b)),nodeFetchBodiesFunctionIds:{json:m((0,d.v5)("node-fetch-body-json",b)),text:m((0,d.v5)("node-fetch-body-text",b)),arrayBuffer:m((0,d.v5)("node-fetch-body-arrayBuffer",b)),blob:m((0,d.v5)("node-fetch-body-blob",b))},requestFunctionId:m((0,d.v5)("request-request",b)),requestMethodFunctionIds:{get:m((0,d.v5)("request-get",b)),head:m((0,d.v5)("request-head",b)),options:m((0,d.v5)("request-options",b)),post:m((0,d.v5)("request-post",b)),put:m((0,d.v5)("request-put",b)),patch:m((0,d.v5)("request-patch",b)),del:m((0,d.v5)("request-del",b)),delete:m((0,d.v5)("request-delete",b))},pgConnectFunctionId:m((0,d.v5)("pg-connect",b)),pgQueryFunctionId:m((0,d.v5)("pg-query",b)),pgEndFunctionId:m((0,d.v5)("pg-end",b)),functionsToInstrument:[{moduleName:"typeorm",fileToFunctionsMapping:{[u.join(u.sep,"typeorm","repository","Repository.js")]:["hasId","getId","create","merge","preload","save","remove","softRemove","recover","insert","update","upsert","delete","softDelete","restore","exist","exists","existsBy","count","countBy","sum","average","minimum","maximum","find","findBy","findAndCount","findAndCountBy","findByIds","findOne","findOneBy","findOneById","findOneOrFail","findOneByOrFail","query","clear","increment","decrement","extend"]}}],esbuildGlobalVar:"hudSGV",esbuildPluginMessagePrefix:"ESBuild plugin ",esbuildMark:"/*modifiedByHudESBuildPlugin-",esbuildMarkLength:67,esbuildUploadSourceMapTimeout:15e3,esbuildPluginLogsChunkSize:100,esbuildPluginLogsBatchSize:10,pluginsLogEndpoint:"https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/",uninstrumentedFilesLogThreshold:2,tsNodeConfigTimeout:1e4,allowedEditExtensions:[".ts",".cts",".mts",".js",".cjs",".mjs"],nextJsMarkVarName:g,nextJsMarkStatement:`${g} = "a"`,timeoutOnNextJsPlugin:3e4,logIntervals:{instrumentedFilesCount:5e3,sentEventsCount:12e4},cliBuildIdVarName:"hudCliBuildId",cliSdkVersionVarName:"hudCliSdkVersion"};t.hudConfig=function(e={}){return{...f,...e}}({logger:{default:{levels:{app:"info",worker:"info",instrument:"info"}},debug:{levels:{app:"debug",worker:"debug",instrument:"debug"}}},deleteLogsAfterSending:!1,communicationKeepalive:!0}),t.default=t.hudConfig;class h extends Error{path;code;constructor(e,t){super(),this.path=e,this.code=t}}t.HudFailedReadConfigError=h},3903:e=>{e.exports=require("uuid")},5453:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SDK_VERSION=void 0,t.SDK_VERSION="1.7.0"},6928:e=>{e.exports=require("path")},7089:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectStoreConfigSchema=void 0;const i=n(1569),a=i.z.object({type:i.z.literal("s3")}),r=i.z.object({type:i.z.literal("disk"),path:i.z.string()});t.ObjectStoreConfigSchema=i.z.union([a,r])},8528:e=>{e.exports=require("./dto")},9896:e=>{e.exports=require("fs")}},t={};return function n(i){var a=t[i];if(void 0!==a)return a.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(2509)})());
2
2
  //# sourceMappingURL=config.js.map
package/dist/cjs/core.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(i(523)),d=i(8528),c=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==d.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){c.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(i(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const n=i(8167),o=i(2546),s=i(5809),a=i(8269),d=i(523),c=i(6281),g=r(i(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(o.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,i,r){this.apiKey=e,this.service=t,this.startTime=i,this.tags=r,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof o.HudSessionThrottle?(d.customer_logger.log(o.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof o.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,o.getNetworkError)(e.originalAxiosErrorCode)),d.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,c._detachAndTerminate)(!1,!1,!0)):(d.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,o.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,o.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(o.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(n.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();d.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,o.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new o.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof o.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=o.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),i={...process.env};delete i.NODE_OPTIONS;const r=new n.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:i});let a;try{a=new g.default(r),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof o.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,i){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void n.app_logger.warning("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!n.app_logger.isValid()||!n.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,r.updateUserConfigFromInit)(e,t,i);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void n.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(n.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new o.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(n.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;n.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;n.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{n.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const r=i(2546),n=i(523),o=i(5994),s=i(5809),a=i(8528),d=i(8269),c=i(2546),g=i(7274);let l,u=!1;function h(e=!0,t=!1,i=!1){(0,d.detachHud)(e,t),i&&(0,c.safeCall)(n.app_logger,f()),l&&(0,c.safeCall)(n.app_logger,l.terminateMessenger());const o=(0,d.getLambdaExtensionId)();o&&!u&&(u=!0,(0,c.safeCall)(n.app_logger,(0,r.nextLoopDummy)(o))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const r=(0,d.getSessionInfo)(),o=(0,d.getStoredApiKey)(),s=(0,d.getStoredService)();try{const a=e||o;if(!a||"string"!=typeof a)return;const d=t||s||"unknown",c=(0,n.getSavedLogs)();for(const e of c){const{HudClient:t}=i(4672),o=new t;r?(n.app_logger.info("Flushing logs with session",{size:e.length,sessionId:r.sessionId,service:d}),o.setSession(r),await o.logs(e)):(n.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await o.sessionslessLogs(e,a)),n.app_logger.info("Successfully flushed logs")}}catch(e){try{n.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==r})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const i=(new Date).toISOString(),o=[];return Object.entries(hudCalls).map(([r,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const n={function_id:r,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:i,timeslice:e,exceptions:s(c.exceptions),count:c.count,sampled_count:c.sampledCount,sum_duration:c.sum,sum_squared_duration:c.squareSum,sketch:c.sketch?t.encode(c.sketch):void 0,is_linked_function:c.isLinkedFunction};o.push(n),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){n.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),o.length>0&&(0,r.clearMetricsIndicator)(),o},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const i in globalThis.hudCalls[e][t])o(globalThis.hudCalls[e][t][i])};const r=i(8269),n=i(523);function o(e){e.samplingCounter=0}function s(e){const t={};for(const i in e)t[i]=[{count:e[i]}];return t}},7320:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(i(523)),d=s(i(6460)),c=i(5809),g=i(2546),l=i(8528),u=i(2546),h=i(7131),f=i(8269),m=i(2546),p=i(7274),v=i(2702),w=i(8269),k=i(2546),y=i(6281),b=i(8269),C=i(2546),_=i(6261),E=a.app_logger,T=m.safeCall.bind(m.safeCall,E);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new _.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,_.setMaxListeners)(20,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,E.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,c.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&E.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),E.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,y._detachAndTerminate)(!0,!1,!0)}catch(e){E.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),E.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const i={msg:e,content:t};this.worker.postMessage(i)}async checkWorker(e){const t=["started"];let i;try{i=await this.getMessageFromWorker(t,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;i=await this.getMessageFromWorker(t,e/2,!1)}if(!i)throw new m.HudInitError("Worker not started");return i}async checkWorkerInitialized(e){let t;const i=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(i,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;t=await this.getMessageFromWorker(i,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw E.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:E.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:E.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:E.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:E.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,i=!1,r){let n;e=Array.isArray(e)?e:[e];const o=this.consumeMessageFromQueue(e);if(o)return E.info("Found message in queue",{msg:o.msg}),o;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:s.signal,ref:i}),g=t=>{try{e.includes(t.msg)&&(n=t,s.abort(),this.consumeMessageFromQueue([t.msg]),E.info("Received message from worker (canceling timeout)",t))}catch(e){E.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),r&&this.worker.postMessage(r);try{throw await c,E.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return n}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){E.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){E.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,c.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){E.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){E.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);(0,f.setInvestigationDurationThresholds)(i?.content),E.debug("Endpoints durations investigation thresholds updated",{thresholds:i?.content})}catch(e){E.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let i=!0;await this.setupPeriodicTask(e,t,()=>{if(i){i=!1;try{this._updateTsNodeConfig()&&E.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,w.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,i=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,i,t=>{try{this.refreshInvestigations()}catch(e){E.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const i=(0,p.prepCalls)(t,e);i.length>0&&this._sendArray("Invocations",i)}catch(e){E.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){E.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async highFrequencySendInvestigations(){if(!c.hudConfig.dynamicConfig.enableInvestigation)return;const e=c.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=c.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,b.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw E.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;E.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}E.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:i.c[i.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):E.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,E,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void E.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){E.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){E.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,i,r){function n(e){let t=!0;try{t=i(e)}catch(e){E.error("Failed in periodic task",{taskName:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),n(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!n(t))return void E.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:r})}else E.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:r})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){E.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){E.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,C.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,E.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let i=0;for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(i++,E.debug("Attempting to send static next.js endpoints",{attemptCount:i}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){E.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(i>t){E.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:i});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,i),o.exports}return i.c=t,i(i.s=5119)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},2546:e=>{e.exports=require("./lib")},2702:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.WorkerKeepaliveGuard=void 0;const a=s(i(523)),d=i(8528),c=a.app_logger;t.WorkerKeepaliveGuard=class{worker;keepaliveGrace;timeoutId=void 0;eventHandler=this.keepalive.bind(this);constructor(e,t){this.worker=e,this.keepaliveGrace=t}keepalive(e){try{if(e.msg!==d.KeepAliveMessage.msg)return;this._restartTimeout()}catch(e){c.error("Error in keepalive",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_restartTimeout(){const e=setTimeout(()=>{},this.keepaliveGrace);clearTimeout(this.timeoutId),this.timeoutId=e}start(){this.stop(),this.worker.on("message",this.eventHandler).unref()}stop(){void 0!==this.timeoutId&&clearTimeout(this.timeoutId),this.worker.off("message",this.eventHandler),this.timeoutId=void 0}}},4672:e=>{e.exports=require("./client")},5119:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.tryFlushPendingLogs=t.init=void 0;const a=s(i(6281));t.init=a.default,Object.defineProperty(t,"tryFlushPendingLogs",{enumerable:!0,get:function(){return a.tryFlushPendingLogs}})},5809:e=>{e.exports=require("./config")},5994:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MainThread=void 0;const n=i(8167),o=i(2546),s=i(5809),a=i(8269),d=i(523),c=i(6281),g=r(i(7320));function l(){globalThis.hudInstrumentationOccured&&d.customer_logger.log(o.UserErrorLogs.YesInstrumentationNoMetrics())}t.MainThread=class{apiKey;service;startTime;tags;messenger;constructor(e,t,i,r){this.apiKey=e,this.service=t,this.startTime=i,this.tags=r,(0,a.storeCredentials)(e,t)}startFailed(e){e instanceof o.HudSessionThrottle?(d.customer_logger.log(o.UserLogs.InitIdleMode()),(0,c._detachAndTerminate)(!1,!1,!0)):e instanceof o.HudInitNetworkError&&e.originalAxiosErrorCode?(d.customer_logger.log((0,o.getNetworkError)(e.originalAxiosErrorCode)),d.app_logger.critical("Failed to start worker because of network error",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,c._detachAndTerminate)(!1,!1,!0)):(d.app_logger.critical("Failed to start worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,o.setFirstError)(e.code),(0,c._detachAndTerminate)(!0,!1,!0))}async _registerLambdaExtension(){const e=await(0,o.register)();return(0,a.setLambdaExtensionId)(e),e}async startMessenger(e){try{this.messenger=await this._createMessenger(e),await this._start(),d.customer_logger.log(o.UserLogs.HudInitSuccess())}catch(e){throw this.startFailed(e),e}}async start(){if(n.isMainThread)if(globalThis.hudRuningInsideLambda)try{const e=await this._registerLambdaExtension();d.app_logger.info("Lambda extension registered, not waiting for worker to start",{lambdaExtensionId:e}),(0,o.next)(e).then(async()=>{d.app_logger.info("Lambda got first event, creating messenger");try{await this.startMessenger(e)}catch{}}).catch(e=>{d.app_logger.error("Failed to send first event to lambda",{msg:e instanceof Error?e.message:void 0}),this.startFailed(e)})}catch(e){throw this.startFailed(e),e}else await this.startMessenger(void 0)}async _start(){if(!this.messenger)throw new o.HudInitError("Messenger not initialized");try{const e=await this.messenger.checkWorkerInitialized(s.hudConfig.workerTimeout),t=e?.content?.sessionInfo;t&&(0,a.storeSessionInfo)(t),await this._initDynamicConfig(),globalThis.hudMetricsIndicator=setTimeout(l,s.hudConfig.timeoutOnMetrics),globalThis.hudMetricsIndicator.unref()}catch(e){const t=e instanceof Error?e.message:void 0;if(e instanceof o.HudSessionThrottle)throw e;throw d.app_logger.critical("Failed to start worker",{msg:t}),e}await this.messenger.start()}async _createMessenger(e){const t=o.myRequire.resolve(`${s.SDK_MODULE_NAME}/worker`),i={...process.env};delete i.NODE_OPTIONS;const r=new n.Worker(t,{workerData:{apiKey:this.apiKey,service:this.service,startTime:this.startTime,tags:this.tags,lambdaExtensionId:e,shouldCreateDeclaraionWorker:!!e,userConfig:s.hudConfig.userConfig},execArgv:[],env:i});let a;try{a=new g.default(r),await a.checkWorker(s.hudConfig.workerTimeout)}catch(e){if(e instanceof o.HudSessionThrottle)throw d.app_logger.info("Worker started in idle mode - session throttled"),e;throw d.app_logger.critical("Worker failed to start",{msg:e instanceof Error?e.message:void 0}),e}finally{r.unref()}return a}async _initDynamicConfig(){const e=await(this.messenger?.getRemoteConfig());e?(d.app_logger.info("Remote configuration exists"),s.hudConfig.dynamicConfig=(0,s.updateDynamicConfig)(e,s.hudConfig,d.app_logger),(0,s.updateInvestigationRateLimitGlobals)(),d.app_logger.info("Current dynamic configuration:",{currentDynamicConfig:s.hudConfig.dynamicConfig})):d.app_logger.info("No remote configuration - falling back to default dynamic configuration",{defaultDynamicConfig:s.hudConfig.dynamicConfig})}async terminateMessenger(){await(this.messenger?.terminateWorker()),this.messenger?.stop(),this.messenger=void 0}}},6261:e=>{e.exports=require("events")},6281:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,i){try{if(!globalThis.hudRanOnRequire)return;if(globalThis.hudRunMutex)return void n.app_logger.warning("Already ran init!");if(globalThis.hudRunMutex=!0,(0,d.clearInitGuard)(),!n.app_logger.isValid()||!n.customer_logger.isValid())return(0,c.setFirstError)((new c.HudBadLoggerError).code),void h(!0,!0);(0,r.updateUserConfigFromInit)(e,t,i);const g=(0,d.validateAndGetUserInput)();if(!g)return;if(globalThis.hudRunningMode!==a.HudRunningMode.enabled)return void n.app_logger.critical("SDK running mode is not enabled - initialization aborted");if(n.app_logger.info("Initializing hud",{userConfig:Object.entries(s.hudConfig.userConfig).filter(([e,t])=>"DEFAULT"!==t.source)}),l=new o.MainThread(g.apiKey,g.service,globalThis.hudStartTime,s.hudConfig.userConfig.tags?.value),await l.start(),l.messenger&&(0,c.safeCall)(n.app_logger,l.messenger.handleLogsTask()),globalThis.hudImportStartTime){const e=process.uptime()-globalThis.hudImportStartTime;n.app_logger.info("Hud initialized",{importTime:e,startTime:globalThis.hudImportStartTime})}}catch(e){try{if(e instanceof c.HudSessionThrottle)return;n.app_logger.critical("Something went wrong in init",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}catch{n.app_logger.critical("Something went wrong in init & e.stack raised an exception")}h(!0,!1,!0)}},t.isValidParam=function(e){return null!=e&&""!==e&&"string"==typeof e},t._detachAndTerminate=h,t.flushLogs=f,t.tryFlushPendingLogs=async function(e,t){(0,d.getShouldFlushOnInit)()&&((0,d.markShouldFlushOnInit)(!1),await f(e,t))};const r=i(2546),n=i(523),o=i(5994),s=i(5809),a=i(8528),d=i(8269),c=i(2546),g=i(7274);let l,u=!1;function h(e=!0,t=!1,i=!1){(0,d.detachHud)(e,t),i&&(0,c.safeCall)(n.app_logger,f()),l&&(0,c.safeCall)(n.app_logger,l.terminateMessenger());const o=(0,d.getLambdaExtensionId)();o&&!u&&(u=!0,(0,c.safeCall)(n.app_logger,(0,r.nextLoopDummy)(o))),(0,d.clearUserIndicatorsTimeouts)(),(0,g.resetCallers)()}async function f(e,t){const r=(0,d.getSessionInfo)(),o=(0,d.getStoredApiKey)(),s=(0,d.getStoredService)();try{const a=e||o;if(!a||"string"!=typeof a)return;const d=t||s||"unknown",c=(0,n.getSavedLogs)();for(const e of c){const{HudClient:t}=i(4672),o=new t;r?(n.app_logger.info("Flushing logs with session",{size:e.length,sessionId:r.sessionId,service:d}),o.setSession(r),await o.logs(e)):(n.app_logger.info("Flushing logs (sessionless)",{size:e.length,service:d}),await o.sessionslessLogs(e,a)),n.app_logger.info("Successfully flushed logs")}}catch(e){try{n.app_logger.error("Failed to flush logs",{msg:e instanceof Error?e.message:void 0,hasSession:null!==r})}catch{}}}},6460:e=>{e.exports=require("timers/promises")},7131:e=>{e.exports=require("./wrap")},7274:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._liftExceptions=s,t.prepCalls=function(e,t){const i=(new Date).toISOString(),o=[];return Object.entries(hudCalls).map(([r,a])=>{Object.entries(a).forEach(([a,d])=>{Object.entries(d).forEach(([d,c])=>{try{if(0===c.sampledCount)return;const n={function_id:r,wrapped_flow_id:d||void 0,wrapped_caller_id:a||void 0,timestamp:i,timeslice:e,exceptions:s(c.exceptions),count:c.count,sampled_count:c.sampledCount,sum_duration:c.sum,sum_squared_duration:c.squareSum,sketch:c.sketch?t.encode(c.sketch):void 0,is_linked_function:c.isLinkedFunction};o.push(n),function(e){e.count=0,e.sampledCount=0,e.sum=0,e.squareSum=0,e.sketch=null,e.exceptions={}}(c)}catch(e){n.app_logger.error("Failed preparing invocation, skipping",{func:r,wrappedCaller:a,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}})})}),o.length>0&&(0,r.clearMetricsIndicator)(),o},t.resetCallers=function(){for(const e in globalThis.hudCalls)for(const t in globalThis.hudCalls[e])for(const i in globalThis.hudCalls[e][t])o(globalThis.hudCalls[e][t][i])};const r=i(8269),n=i(523);function o(e){e.samplingCounter=0}function s(e){const t={};for(const i in e)t[i]=[{count:e[i]}];return t}},7320:function(e,t,i){var r,n=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),s=0;s<i.length;s++)"default"!==i[s]&&n(t,e,i[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=s(i(523)),d=s(i(6460)),c=i(5809),g=i(2546),l=i(8528),u=i(2546),h=i(7131),f=i(8269),m=i(2546),p=i(7274),v=i(2702),w=i(8269),k=i(2546),y=i(6281),b=i(8269),C=i(2546),_=i(6261),E=a.app_logger,T=m.safeCall.bind(m.safeCall,E);t.default=class{worker;tsNodeUpdated=!1;staticNextJsEndpointsSent=!1;abortController;workerKeepaliveGuard;messageQueue=[];MAX_QUEUE_SIZE=100;messageEmitter=new _.EventEmitter;constructor(e){this.worker=e,this.abortController=new AbortController,(0,_.setMaxListeners)(20,this.abortController.signal);let t=!1;this.worker.on("message",e=>{e.msg!==l.KeepAliveMessage.msg&&(this.messageQueue.length>=this.MAX_QUEUE_SIZE&&(t||(t=!0,E.error("Message queue is at max size, dropping oldest message",{msg:e.msg})),this.messageQueue.shift()),this.messageQueue.push(e),this.messageEmitter.emit("message",e))}).unref(),this.worker.on("error",this.handleWorkerError).unref(),this.workerKeepaliveGuard=new v.WorkerKeepaliveGuard(e,c.hudConfig.communicationKeepaliveGrace),this._updateTsNodeConfig()&&E.info("ts-node config updated from Messenger constructor")}handleWorkerError=e=>{try{e?.code===(new m.HudClientUnauthorizedError).code&&a.customer_logger.log(m.UserErrorLogs.ApiKeyDenied(c.hudConfig.userConfig.key?.source)),E.critical("Error from worker, stopping hud",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),(0,m.setFirstError)(e?.code),this.stop(),(0,y._detachAndTerminate)(!0,!1,!0)}catch(e){E.critical("Error stopping hud after worker crash",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};stop(){this.abortWorker(),c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.stop(),this.abortController.abort(),this.abortController=new AbortController,this.messageQueue=[],this.messageEmitter.removeAllListeners(),(0,f.resetGlobals)()}abortWorker(){this._sendObject("Abort",{})}async restart(e){this.stop(),globalThis.hudRunningMode=e,await this.start()}_sendArray(e,t){t.length>0&&(this._sendObject(e,t),E.debug("sent data to worker",{msg:e,size:t.length}))}_sendObject(e,t){const i={msg:e,content:t};this.worker.postMessage(i)}async checkWorker(e){const t=["started"];let i;try{i=await this.getMessageFromWorker(t,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;i=await this.getMessageFromWorker(t,e/2,!1)}if(!i)throw new m.HudInitError("Worker not started");return i}async checkWorkerInitialized(e){let t;const i=["initialized","throttled","networkError"];try{t=await this.getMessageFromWorker(i,e,!0)}catch(r){if(!(r instanceof m.HudTimeoutError))throw r;t=await this.getMessageFromWorker(i,e/10,!1)}if("throttled"===t?.msg)throw new m.HudSessionThrottle;if("networkError"===t?.msg)throw E.error("networkError",{error:t.content.error}),new m.HudInitNetworkError(t.content.message,t.content.originalMessage);if(!t||"initialized"!==t?.msg||void 0===t?.content)throw new m.HudInitError("Worker not initialized successfully");if(t?.content.status!==l.HudSessionInitStatus.success)throw new m.HudInitError("Worker not initialized successfully");return t}async start(){switch(c.hudConfig.communicationKeepalive&&this.workerKeepaliveGuard.start(),globalThis.hudRunningMode){case l.HudRunningMode.enabled:E.info("Enabled mode"),T(this.getMode()),T(this.periodicGetEndpointsDurationsInvestigationThresholds()),T(this.startPeriodicTasks()),T(this.periodicSendMetrics()),T(this.highFrequencySendInvestigations()),T(this.periodicSendProcessedFiles()),T(this.periodicSendEndpoints()),T(this.periodicSendOutbounds()),T(this.periodicSendLazyEndpoints()),T(this.periodicSendKafkaJS()),T(this.periodicSendSqs()),T(this.periodicSendGraphQL()),T(this.sendStaticNextJsEndpointsOnce()),T(this.periodicSaveMachineMetrics()),T(this.periodicSendReingest()),T(this.resetCallerCounters()),T(this.periodicResetGlobalInvestigationCounter()),T(this.periodicResetInvestigationDedupingCache()),T(this.sendLogsPeriodically(c.hudConfig.logsSendInterval)),T(this.sendRuntime()),T(this.sendPatchedModules()),T(this.sendPreloadedModules()),T(this.dumpModulesAfterWhile(6e4)),T(this.periodicSendThreadPerformanceMetrics());break;case l.HudRunningMode.disabled:E.info("Disabled mode"),T(this.getMode());break;case l.HudRunningMode.detached:E.info("Detached"),(0,y._detachAndTerminate)(!1,!1),this.stop();break;default:E.error("Running mode not handled")}}consumeMessageFromQueue(e){const t=this.messageQueue.findIndex(t=>e.includes(t.msg));if(-1!==t)return this.messageQueue.splice(t,1)[0]}async getMessageFromWorker(e,t,i=!1,r){let n;e=Array.isArray(e)?e:[e];const o=this.consumeMessageFromQueue(e);if(o)return E.info("Found message in queue",{msg:o.msg}),o;const s=new AbortController,a=()=>{s.abort()};this.abortController.signal.addEventListener("abort",a);const c=d.setTimeout(t,void 0,{signal:s.signal,ref:i}),g=t=>{try{e.includes(t.msg)&&(n=t,s.abort(),this.consumeMessageFromQueue([t.msg]),E.info("Received message from worker (canceling timeout)",t))}catch(e){E.error("Failed handling message from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}};this.messageEmitter.on("message",g),r&&this.worker.postMessage(r);try{throw await c,E.warning("Timeout waiting for message from worker"),new m.HudTimeoutError}catch(e){if(!(0,m.isAbortError)(e))throw(0,m.setFirstError)(e.code),e}finally{this.abortController.signal.removeEventListener("abort",a),this.messageEmitter.off("message",g)}return n}async getMode(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.modeInterval,void 0,{signal:this.abortController.signal}))try{const e={msg:"GetMode",content:{startTime:globalThis.hudStartTime,runningMode:globalThis.hudRunningMode}},t=await this.getMessageFromWorker(e.msg,c.hudConfig.workerMessageTimeout,!1,e);if(t?.msg!==e.msg||void 0===t?.content.mode){E.error("Unexpected message from worker",t);continue}t.content.mode!==globalThis.hudRunningMode&&await this.restart(t?.content.mode)}catch(e){E.error("Failed getting mode from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async getRemoteConfig(){const e="initDynamicConfig";try{const t=await this.getMessageFromWorker(e,c.hudConfig.workerMessageTimeout,!0);if(t?.msg!==e||void 0===t?.content)throw new Error(`Unexpected message from worker: ${t}`);return t?.content}catch(e){E.error("Failed getting remote configuration from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicSaveMachineMetrics(){(0,f.saveMachineMetric)();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.machineMetricsInterval,void 0,{signal:this.abortController.signal}))(0,f.saveMachineMetric)()}async resetCallerCounters(){const e=c.hudConfig.callerResetInterval;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting caller",{interval:e}),(0,p.resetCallers)()}catch(e){E.error("Failed reseting caller counters",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async updateEndpointDurationsInvestigationThresholds(){const e={msg:"EndpointsDurationsInvestigationThresholds"},t="EndpointsDurationsInvestigationThresholds";try{const i=await this.getMessageFromWorker(t,c.hudConfig.workerMessageTimeout,!1,e);if(i?.msg!==t||void 0===i?.content)throw new Error(`Unexpected message from worker: ${i}`);(0,f.setInvestigationDurationThresholds)(i?.content),E.debug("Endpoints durations investigation thresholds updated",{thresholds:i?.content})}catch(e){E.error("Failed getting endpoints durations investigation thresholds from worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicGetEndpointsDurationsInvestigationThresholds(){await this.updateEndpointDurationsInvestigationThresholds();for await(const e of(0,u.unrefSetInterval)(c.hudConfig.endpointsDurationsInvestigationThresholdsInterval,void 0,{signal:this.abortController.signal}))await this.updateEndpointDurationsInvestigationThresholds()}async periodicSendProcessedFiles(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;let i=!0;await this.setupPeriodicTask(e,t,()=>{if(i){i=!1;try{this._updateTsNodeConfig()&&E.info("ts-node config updated from periodicSendProcessedFiles")}catch{return!1}}const e=function(){const e=globalThis.hudProcessedFiles;return globalThis.hudProcessedFiles=[],e}();return this._sendArray("ProcessedFiles",e),!0},"periodicSendProcessedFiles")}async periodicSendKafkaJS(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getKafkaJSTopics)();return this._sendArray("KafkaJSTopics",e),!0},"periodicSendKafkaJS")}async periodicSendSqs(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=(0,w.getSqsQueues)();return e.length>0&&this._sendArray("SqsQueue",e),!0},"periodicSendSqs")}async periodicSendGraphQL(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>{const e=Object.values((0,w.getGraphQLOperations)());return e.length>0&&this._sendArray("GraphQLDeclaration",e),!0},"periodicSendGraphQL")}async periodicSendMetrics(){const e=new h.SketchManager(c.hudConfig.huddBinWidth),t=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,i=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(t,i,t=>{try{this.refreshInvestigations()}catch(e){E.error("Failed sending investigations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const i=(0,p.prepCalls)(t,e);i.length>0&&this._sendArray("Invocations",i)}catch(e){E.error("Failed sending invocations",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}try{const e=(0,f.getFlowMetrics)(t);Object.keys(e).length>0&&this._sendObject("FlowMetrics",{aggregatedMetrics:e})}catch(e){E.error("Failed sending flow metrics",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return!0},"periodicSendMetrics")}async highFrequencySendInvestigations(){if(!c.hudConfig.dynamicConfig.enableInvestigation)return;const e=c.hudConfig.dynamicConfig.investigationFirstSendTimeout,t=c.hudConfig.dynamicConfig.investigationInterval;await this.setupPeriodicTask(e,t,()=>(this.refreshInvestigations(),!0),"highFrequencySendInvestigations")}refreshInvestigations(){const e=(0,w.getClosedInvestigations)();e.length>0&&this._sendArray("Investigations",e)}async periodicSendEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.endpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendEndpoints(),!0),"periodicSendEndpoints")}async periodicSendOutbounds(){const e=c.hudConfig.dynamicConfig.aggregationFirstSendTimeout,t=c.hudConfig.dynamicConfig.aggregationInterval;await this.setupPeriodicTask(e,t,()=>(this.sendOutbounds(),!0),"periodicSendOutbounds")}async periodicSendLazyEndpoints(){const e=c.hudConfig.endpointsFirstSendWaitTime,t=c.hudConfig.lazyEndpointsInterval;await this.setupPeriodicTask(e,t,()=>(this.sendLazyEndpoints(),!0),"periodicSendLazyEndpoints")}sendLazyEndpoints(){const e=(0,w.getExpressEndpointDeclarations)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendEndpoints(){const e=(0,f.getEndpointDeclarationsFromStorage)().map(e=>({path:e.path,methods:e.methods,flow_id:e.flow_id,framework:e.framework,partial_path:e.partial_path}));this._sendArray("EndpointDeclaration",e)}sendOutbounds(){const e=(0,b.getLoadedOutboundsFromStorage)();e.length>0&&this._sendArray("LoadedOutbounds",e)}async terminateWorker(){try{const e=a.getSavedLogs();await this.getMessageFromWorker("terminated",c.hudConfig.workerGrace,!1,{msg:"Terminate",content:{grace:c.hudConfig.workerGrace,logBuffers:e}})}catch(e){if(!(e instanceof m.HudTimeoutError))throw E.critical("Unexpected error during worker termination",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),await this.worker.terminate(),e;E.critical("Grace period timeout - terminating worker",{error:e.message}),await this.worker.terminate()}E.info("Worker terminated successfully.")}async sendRuntime(){const e={nodeVersion:process.version,nodeDependencyVersions:process.versions,platform:process.platform,architecture:process.arch,pid:process.pid,cwd:process.cwd(),execPath:process.execPath,execArgv:process.execArgv,argv:process.argv,uptime:process.uptime(),mainModulePath:i.c[i.s]?.filename};this._sendObject("Runtime",e)}async startPeriodicTasks(){this._sendObject("StartPeriodicTasks",{})}async sendPreloadedModules(){globalThis.hudLoadedModules?this._sendObject("PreInitLoadedModules",{modules:globalThis.hudLoadedModules}):E.warning("Didn't get module, weird....")}async periodicSendThreadPerformanceMetrics(){const e=c.hudConfig.dynamicConfig.performanceMetricsInterval,t=(0,g.createThreadStatsBaseline)();for await(const i of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){const e=(0,m.collectThreadPerformance)(t,E,"MainThread");e&&this._sendObject("PerformanceMetrics",e)}}async dumpModulesAfterWhile(e){await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal});const t=Object.keys(k.myRequire.cache);this._sendObject("PostInitLoadedModules",{modules:t})}async sendPatchedModules(){if(!globalThis.hudPatched)return void E.error("Cant find patched modules");const e=Array.from(globalThis.hudPatched);this._sendObject("PatchedModules",{modules:e})}async handleLogsTask(){try{const e=a.getSavedLogs();for(const t of e)try{this._sendObject("Logs",{logs:t})}catch(e){E.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}catch(e){E.error("Failed send logs to worker",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async sendLogsPeriodically(e){for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))await this.handleLogsTask()}async setupPeriodicTask(e,t,i,r){function n(e){let t=!0;try{t=i(e)}catch(e){E.error("Failed in periodic task",{taskName:r,msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}return t}if(await(0,u.unrefSetTimeout)(e,void 0,{signal:this.abortController.signal}),n(e)){for await(const e of(0,u.unrefSetInterval)(t,void 0,{signal:this.abortController.signal}))if(!n(t))return void E.warning("Periodic task failed, stopping task",{firstRun:!1,taskName:r})}else E.warning("Periodic task failed, stopping task",{firstRun:!0,taskName:r})}async periodicResetGlobalInvestigationCounter(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.totalInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting global investigation counter",{interval:e}),(0,w.setGlobalInvestigationTracking)(0),(0,f.resetTotalInvestigationsDurationBased)(),(0,f.resetTotalInvestigationsErrorBased)()}catch(e){E.error("Failed resetting global investigation counter",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}async periodicResetInvestigationDedupingCache(){const e=c.hudConfig.dynamicConfig.investigationRateLimits.sameInvestigationTimeWindowMs;for await(const t of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal}))try{E.info("Resetting investigation deduping cache",{interval:e}),(0,w.resetInvestigationDedupingCache)(),(0,f.resetInvestigationDurationCounts)()}catch(e){E.error("Failed resetting investigation deduping cache",{msg:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}_updateTsNodeConfig(){if(this.tsNodeUpdated)return!1;try{const e=(0,C.getUserTsNodeConfig)();return!!e&&(this.tsNodeUpdated=!0,E.info("tsconfig found, sending config to worker"),this._sendObject("TsNodeConfig",{tsConfig:e}),!0)}catch(e){throw this.tsNodeUpdated=!0,this.stop(),e instanceof m.HudError&&(0,m.setFirstError)(e.code),(0,y._detachAndTerminate)(!1),e}}async sendStaticNextJsEndpointsOnce(){if(!(0,g.isNextJsApp)())return;const e=c.hudConfig.staticNextJsEndpointsInterval,t=c.hudConfig.staticNextJsEndpointsMaxAttempts;let i=0;for await(const r of(0,u.unrefSetInterval)(e,void 0,{signal:this.abortController.signal})){if(i++,E.debug("Attempting to send static next.js endpoints",{attemptCount:i}),(0,w.isNextConfigExtracted)()&&!this.staticNextJsEndpointsSent){E.info("Sending static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)()}),this.staticNextJsEndpointsSent=!0;const e=(0,w.getNextConfig)();this._sendObject("StaticNextJsEndpoints",{NextConfig:JSON.stringify(e)});break}if(i>t){E.warning("Exceeded max attempts to send static next.js endpoints",{isNextConfigExtracted:(0,w.isNextConfigExtracted)(),attemptCount:i});break}}}async periodicSendReingest(){for await(const e of(0,u.unrefSetInterval)(c.hudConfig.dynamicConfig.reingestInterval,void 0,{signal:this.abortController.signal})){const e=(0,f.getAndClearReingestValues)();e.size>0&&this._sendArray("Reingest",Array.from(e))}}}},8167:e=>{e.exports=require("worker_threads")},8269:e=>{e.exports=require("./globalstate")},8528:e=>{e.exports=require("./dto")}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,i),o.exports}return i.c=t,i(i.s=5119)})());
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1145:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createOutboundDeclarations=void 0,t.createAxiosDeclaration=r,t.createNodeFetchDeclaration=s,t.createRequestDeclaration=a,t.createPgDeclaration=c;const i=n(5809),o=n(8528);function r(){return[l("axios","Axios","request",i.hudConfig.axiosFunctionId)]}function s(){return[l("node-fetch","node-fetch","fetch",i.hudConfig.nodeFetchFunctionId),...Object.entries(i.hudConfig.nodeFetchBodiesFunctionIds).map(([e,t])=>l("node-fetch","node-fetch",e,t))]}function a(){return[l("request","request","request",i.hudConfig.requestFunctionId),...Object.entries(i.hudConfig.requestMethodFunctionIds).map(([e,t])=>l("request","request",e,t))]}function c(){return[l("pg","Client","connect",i.hudConfig.pgConnectFunctionId),l("pg","Client","query",i.hudConfig.pgQueryFunctionId),l("pg","Client","end",i.hudConfig.pgEndFunctionId)]}function l(e,t,n,i){return{module:e,third_party_module:e,file:`${e}.js`,format:"commonjs",async:!0,runtime_function_id:i,type:o.EntityType.ClassMethod,methodKind:"method",symbol:{sourcemap_location_hints:[{name:n,line:0,column:0,source:`${e}.js`}],name:n,format:"%s"},scope_chain:[{type:o.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0},{type:o.EntityType.ClassDeclaration,symbol:{sourcemap_location_hints:[{name:t,line:0,column:0,source:`${e}.js`}],name:t,format:"%s"},context:{},childrenCount:{},siblingIndex:0}],original_location:{file:`${e}.js`,start_line:0,end_line:0,start_column:0,end_column:0},parameters:[],start_line:0,end_line:0,start_column:0,source_code_hash:"1",bundler_build_id:"1",was_bundler_build_id_generated:!0,has_input_map:!0,sourcemap_crc:1,file_path_checksum:1,file_checksum:1,declarations_count:1,childrenCount:{},siblingIndex:0,context:{}}}t.createOutboundDeclarations={axios:r,"node-fetch":s,request:a,pg:c}},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const r=(0,i.getEntityType)(e);if(r){const s=(0,i.getEntityIdentity)(e.node),a=(0,o.getContextualData)(e,n),c=s?s.loc?[n(s.loc.start,s.name,s.loc.filename??t)]:[]:e.node.loc?[n(e.node.loc.start,void 0,e.node.loc.filename??t)]:[],l=c[0]?.name??s?.name;return{type:r,context:a,symbol:{name:l,sourcemap_location_hints:c,format:l?"%s":void 0},methodKind:(0,o.getMethodKind)(e.node)}}};const i=n(5203),o=n(9127)},2535:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const i=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==i.length?o.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:i}):t=r.default.format(e.format,...i):t=i.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const i=e.loc?.start,r=e.loc?.end;if(!i||!r)return o.worker_logger.info("Node without location",{filename:n,type:e.type}),{start:{source:null,line:-1,column:-1},end:{source:null,line:-1,column:-1}};const s=t({line:i.line,column:i.column}),a=t({line:r.line,column:r.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(o.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:i,locEnd:r}),s.line=-1,s.column=-1,a.line=-1,a.column=-1),{start:{source:s.source,line:s.line,column:s.column},end:{source:a.source,line:a.line,column:a.column}}};const o=n(523),r=i(n(9023))},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3176:e=>{e.exports=require("buffer-crc32")},3903:e=>{e.exports=require("uuid")},4634:e=>{e.exports=require("source-map")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return i.types.isFunctionDeclaration(t)?o.EntityType.FunctionDeclaration:i.types.isFunctionExpression(t)?o.EntityType.FunctionExpression:i.types.isArrowFunctionExpression(t)?o.EntityType.FunctionArrow:i.types.isObjectMethod(t)?o.EntityType.ObjectMethod:i.types.isStaticBlock(t)||i.types.isClassMethod(t)?o.EntityType.ClassMethod:i.types.isClassPrivateMethod(t)?o.EntityType.ClassPrivateMethod:i.types.isClassDeclaration(t)?o.EntityType.ClassDeclaration:i.types.isClassExpression(t)?o.EntityType.ClassExpression:i.types.isForInStatement(t)||i.types.isForOfStatement(t)||i.types.isForStatement(t)?o.EntityType.ForLoop:i.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(i.types.isFunctionDeclaration(t)||i.types.isFunctionExpression(t)||i.types.isArrowFunctionExpression(t)||i.types.isClassMethod(t)||i.types.isObjectMethod(t)||i.types.isClassPrivateMethod(t)))if(i.types.isIfStatement(t)){if("consequent"===e.parentKey)return o.EntityType.IfConsequent;if("alternate"===e.parentKey)return o.EntityType.IfAlternate;if("test"===e.parentKey)return o.EntityType.IfTest}else{if(i.types.isBlockStatement(t)||i.types.isProgram(t))return o.EntityType.Block;if(i.types.isTryStatement(t)){if("block"===e.parentKey)return o.EntityType.Try;if("finalizer"===e.parentKey)return o.EntityType.Finally}else{if(i.types.isCatchClause(t))return;if(i.types.isWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(i.types.isDoWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(!(i.types.isForStatement(t)||i.types.isForInStatement(t)||i.types.isForOfStatement(t)))return;if("test"===e.parentKey)return o.EntityType.ForTest;if("body"===e.parentKey)return o.EntityType.ForBlock}}}(e):i.types.isProgram(t)?o.EntityType.Program:i.types.isDoWhileStatement(t)?o.EntityType.DoWhile:i.types.isWhileStatement(t)?o.EntityType.While:i.types.isCatchClause(t)?o.EntityType.Catch:i.types.isObjectExpression(t)?o.EntityType.ObjectExpression:i.types.isWithStatement(t)?o.EntityType.With:i.types.isSwitchStatement(t)?o.EntityType.Switch:i.types.isSwitchCase(t)?o.EntityType.SwitchCase:i.types.isTryStatement(t)?o.EntityType.TryCatch:i.types.isIfStatement(t)?o.EntityType.If:o.EntityType.Other},t.getEntityIdentity=function(e){return i.types.isFunctionDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Function declaration without an identifier"):i.types.isClassDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Class declaration without an identifier"):i.types.isFunctionExpression(e)||i.types.isClassExpression(e)?i.types.isIdentifier(e.id)?e.id:void 0:i.types.isClassMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Class method without an identifier"):i.types.isObjectMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Object method without an identifier"):i.types.isClassPrivateMethod(e)?i.types.isIdentifier(e.key.id)?e.key.id:void r.worker_logger.info("Class private method without an identifier"):void 0};const i=n(6346),o=n(8528),r=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(9850),t),o(n(1145),t),o(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getParameterInfo=function(e,t){return e.node.params.map(e=>{try{return p(e,t)}catch{return}}).filter(e=>void 0!==e)};const a=s(n(6346)),c=n(8528),l=n(523);function u(e,t){if(a.types.isIdentifier(e.argument)){const n=e.argument.loc?t(e.argument.loc.start):void 0;return{name:n?.name??e.argument.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}{l.worker_logger.warning("Unsupported rest element",{type:e.argument.type});const n=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}}function p(e,t){if(e)switch(e?.type){case"Identifier":return function(e,t){const n=e.loc?t(e.loc.start,e.name):void 0;return{name:n?.name??e.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}(e,t);case"AssignmentPattern":return function(e,t,n,i){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,left:t,right:i}}(e,p(e.left,t),t,function(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"BigIntLiteral":case"DecimalLiteral":return{type:e.type,value:e.value};case"RegExpLiteral":return{type:e.type,value:e.pattern}}return{type:e.type}}(e.right));case"ArrayPattern":return function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,elements:t}}(e,e.elements.map(e=>p(e,t)).filter(e=>void 0!==e),t);case"RestElement":return u(e,t);case"ObjectPattern":{const n=[];return e.properties.forEach(e=>{if(a.types.isObjectProperty(e)){const i=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:p(e.key,t);n.push(function(e,t,n,i){const o=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,key:n,value:i}}(e,t,i,p(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,properties:t}}(e,n,t)}default:l.worker_logger.warning("Unsupported parameter type",{type:e.type})}}},8528:e=>{e.exports=require("./dto")},9011:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NamespaceScopeAlias=t.ScopableAlias=void 0,t.isHudScopeable=function(e){return i.types.isArrowFunctionExpression(e)||i.types.isBlockStatement(e)||i.types.isCatchClause(e)||i.types.isClassMethod(e)||i.types.isClassPrivateMethod(e)||i.types.isDeclareModule(e)||i.types.isDoExpression(e)||i.types.isDoWhileStatement(e)||i.types.isForInStatement(e)||i.types.isForOfStatement(e)||i.types.isForStatement(e)||i.types.isFunctionDeclaration(e)||i.types.isFunctionExpression(e)||i.types.isIfStatement(e)||i.types.isLabeledStatement(e)||i.types.isObjectMethod(e)||i.types.isProgram(e)||i.types.isStaticBlock(e)||i.types.isSwitchCase(e)||i.types.isTSModuleBlock(e)||i.types.isTryStatement(e)||i.types.isWhileStatement(e)||i.types.isWithStatement(e)||i.types.isClassDeclaration(e)||i.types.isClassExpression(e)||i.types.isObjectExpression(e)||i.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return i.types.isFunction(e)||i.types.isClass(e)||i.types.isObjectExpression(e)};const i=n(6346);t.ScopableAlias="ArrowFunctionExpression|BlockStatement|CatchClause|ClassMethod|ClassPrivateMethod|DeclareModule|DoExpression|DoWhileStatement|ForInStatement|ForOfStatement|ForStatement|FunctionDeclaration|FunctionExpression|IfStatement|LabeledStatement|ObjectMethod|StaticBlock|SwitchCase|TSModuleBlock|TryStatement|WhileStatement|WithStatement|ClassDeclaration|ClassExpression|ObjectExpression|SwitchStatement",t.NamespaceScopeAlias="FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod|ClassPrivateMethod|ClassDeclaration|ClassExpression|ObjectExpression"},9023:e=>{e.exports=require("util")},9127:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionIdentifier=function(e){const{node:t}=e;if(c.types.isFunctionDeclaration(t)||c.types.isFunctionExpression(t)){if(c.types.isIdentifier(t.id))return t.id}else if(c.types.isClassMethod(t)){if(c.types.isIdentifier(t.key))return t.key}else if(c.types.isClassPrivateMethod(t)){if(c.types.isIdentifier(t.key.id))return t.key.id}else if(c.types.isObjectMethod(t)&&c.types.isIdentifier(t.key))return t.key},t.getContextSymbol=g,t.getContextualData=function(e,t){let n,i;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[i,o]of n.node.arguments.entries())if(o===e.node){const o=n.node.callee;let r;try{r=y(o,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${o.type}-${e.node.type}`;v.has(n)||(p.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:o.type,nodeType:e.node.type}),v.add(n))}}const s=_(n.node,t);return{callee:{symbol:r,argsCount:n.node.arguments.length,args:s},index:i}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(i=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const o=g(e,t);return o&&(o.name=(0,f.getSymbolName)(o)),{symbol:o,callback:n,immediatelyInvoked:i}},t.getMethodKind=function(e){if(a.types.isClassMethod(e)||a.types.isObjectMethod(e)||a.types.isClassPrivateMethod(e))return e.kind};const a=s(n(6346)),c=n(6346),l=n(8528),u=n(2546),p=n(523),d=n(9772),f=n(2535);function m(e,t,n){const i=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:i?.name??t,sourcemap_location_hints:i?[i]:[],format:"%s"}}function y(e,t){if(c.types.isIdentifier(e)){const n=e.loc?[t(e.loc.start,e.name,e.loc.filename)]:[];return{name:n[0]?.name??e.name,sourcemap_location_hints:n,format:"%s"}}if(c.types.isMemberExpression(e)||c.types.isOptionalMemberExpression(e)){let n;n=c.types.isThisExpression(e.object)?{name:"this",sourcemap_location_hints:e.object.loc?[t(e.object.loc.start,"this",e.object.loc.filename)]:[]}:y(e.object,t);const i=y(e.property,t),o=e.computed?n.name+"["+i.name+"]":n.name+"."+i.name,r=n.format??"%s",s=i.format??"%s",a=e.computed?`${r}[${s}]`:`${r}.${s}`;return{name:o,sourcemap_location_hints:[...n.sourcemap_location_hints,...i.sourcemap_location_hints],format:a}}if(c.types.isOptionalCallExpression(e)||c.types.isCallExpression(e))return y(e.callee,t);if(c.types.isSequenceExpression(e))return(0,d.isHudAwaitSequence)(e)?y((0,d.getHudAwaitSequenceElement)(e),t):y(e.expressions[e.expressions.length-1],t);if(c.types.isArrayExpression(e))return{name:"[]",sourcemap_location_hints:e.loc?[t(e.loc.start,"[]",e.loc.filename)]:[],format:"%s"};if(c.types.isObjectExpression(e))return{name:"{}",sourcemap_location_hints:e.loc?[t(e.loc.start,"{}",e.loc.filename)]:[],format:"%s"};if(c.types.isStringLiteral(e)){const n=e.loc?[t(e.loc.start,e.value,e.loc.filename)]:[];return{name:`"${n[0]?.name??e.value}"`,sourcemap_location_hints:n,format:'"%s"'}}throw new u.HudUnsupportedError("Unsupported left side of assignment - "+e.type+"loc - "+JSON.stringify(e.loc))}const h=new Set;function g(e,t){const{node:n}=e;if(e.isExpression())try{return function(e,t){const{parent:n}=e;if(c.types.isVariableDeclarator(n)&&c.types.isIdentifier(n.id))return m(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isAssignmentExpression(n))return y(n.left,t);if(c.types.isAssignmentPattern(n))return y(n.left,t);throw new u.HudUnsupportedError(`Unsupported parent type - ${n.type} for me ${e.node.type}`)}(e,t)}catch(t){if(t instanceof u.HudUnsupportedError){const n=`${e.parentPath?.node.type}`;return void(h.has(n)||(p.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),h.add(n)))}throw t}p.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function _(e,t){const n=[];return e.arguments.forEach((e,i)=>{let o,r;if(c.types.isStringLiteral(e)?(o=l.ArgumentTypes.StringLiteral,r=e.value):c.types.isTemplateLiteral(e)?(o=l.ArgumentTypes.TemplateString,r=function(e){let t="";const n=e.quasis,i=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<i.length&&(t+=`\${${b(i[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(o=l.ArgumentTypes.Identifier,r=e.name),o&&r){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:i,type:o,value:a?.name??r,sourcemap_location_hint:a})}}),n}function b(e){if(c.types.isIdentifier(e))return e.name;if(c.types.isStringLiteral(e))return e.value;if(c.types.isCallExpression(e)||c.types.isOptionalCallExpression(e)){const t=e;if(c.types.isIdentifier(t.callee))return t.callee.name;if(c.types.isMemberExpression(t.callee)||c.types.isOptionalMemberExpression(t.callee)){let e="";const n=t.callee;if(c.types.isThisExpression(n.object)?e+="this.":c.types.isIdentifier(n.object)&&(e+=`${n.object.name}.`),""!==e&&c.types.isIdentifier(n.property))return e+=`${n.property.name}`,e}}return""}const v=new Set},9772:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHudAwaitSequence=function(e){if(e.expressions.length<2)return!1;const t=e.expressions[e.expressions.length-1];return!!i.types.isIdentifier(t)&&!!t.name.startsWith(o.hudConfig.wrapVarPrefix)},t.getHudAwaitSequenceElement=function(e){const t=e.expressions[0];if(!i.types.isAssignmentExpression(t))throw new r.HudUnsupportedError("Expected assignment expression");const{left:n,right:s}=t;if(!i.types.isIdentifier(n)||!n.name.startsWith(o.hudConfig.wrapVarPrefix))throw new r.HudUnsupportedError("Expected identifier starting with "+o.hudConfig.wrapVarPrefix);return s};const i=n(6346),o=n(5809),r=n(2546)},9850:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fixSourceMap=O,t.getRealPositionNothingFunc=P,t.getRealPositionOffsetsFunc=M,t.getRealPositionSourceMapFunc=F,t.parseDeclarations=async function(e,t,n=null,i){const{filename:o,bundlerBuildId:r,bundlerBuildIdGenerated:s,lineOffset:a,columnOffset:P,file_path_checksum:T,file_checksum:D,functionIds:A,sourceCodeHash:q,moduleBase:B,isNextJsApp:N,marksCount:$}=e;if(h.worker_logger.debug("Parsing code",{filename:o}),i)try{if(!j){const e=(0,y.myRequire)("ts-node");j=e.create({...i,transpileOnly:!0,typeCheck:!1})}const e=function(e,t,n){try{return n.compile(e,t)}catch(e){return void h.worker_logger.warning("ts file pass, but failed to compile with ts-node",{filename:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(t,o,j);if(!e)return{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};t=e}catch(e){return h.worker_logger.error("Failed to require and compile ts file",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}}}else if(o.endsWith(".ts")||o.endsWith(".mts"))return h.worker_logger.error("ts file pass, but not found ts-options"),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};const W=(0,g.default)(t).readUInt32BE();if(W!==D)return h.worker_logger.warning("File checksum mismatch",{filename:o,file_path_checksum:T,diskFileChecksum:W,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};let L,U,K=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(a&&P)K=M(a,P);else{const e=(0,_.getSourceMap)(o,t);try{null!==e&&(U=(0,g.default)(e).readUInt32BE(),d.hudConfig.userConfig.disableSourceMapsResolution?.value||(L=JSON.parse(e),L&&(K=F(await new u.SourceMapConsumer(O(L))))))}catch(e){h.worker_logger.error("Failed to parse source map",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}h.worker_logger.debug("Parsing code",{filename:o});const H=[],R=new S(t,B),J=R.getRemainingMarksCount(),V=await c.parseAsync(t,C);if(null===V)return h.worker_logger.warning("Failed parsing code to tree",{filename:o,file_path_checksum:T,diskFileChecksum:W,file_checksum:D,functionIds:A}),{declarations:[],blacklist:{file_path_checksum:T,file_checksum:D,uuids:A}};h.worker_logger.debug("Parsed code to tree",{filename:o});const z=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],G=new Set,Q=new Map;h.worker_logger.debug("Traversing declarations",{filename:o}),n?.postMessage("eventlooptime"),c.traverse(V,{[w.NamespaceScopeAlias]:{enter(e){const{node:n}=e;if(!(0,w.isNamespaceScopeable)(n))return;const i=z[z.length-1],r=(0,x.getScope)(e,o,K);if(!r)return;const s=i.childrenCount[r.type]||0,a={...r,childrenCount:{},siblingIndex:s};if(i.childrenCount[r.type]=s+1,z.push(a),G.add(n),e.isFunction()){const i=function(e,t,n,i,o,r,s){try{const c=(0,y.getInstrumentedThirdPartyModuleInfo)(n);let l;if(c){if(!function(e,t){const n=(0,p.getFunctionIdentifier)(e);if(!n)return!1;const i=n.name;return t.functions.includes(i)}(e,c))return;l=c.moduleName}const u=I(e);if(!u)throw new Error("Function node has no block start location");const _=e;if(void 0===e.node.start||null===e.node.start||void 0===e.node.end||null===e.node.end)throw new Error("Function node has no start or end location");const x=function(e,t,n,i){const o=i.slice(0,n),r=`${e}_${t}_${Buffer.byteLength(o,"utf8")}`;return(0,b.v5)(r,d.hudConfig.functionUuidNamespace).toString()}(t,n,u.start-(o-1),r),w=(a=r.slice(e.node.start,e.node.end),(0,g.default)(a).readUInt32BE().toString());if(!w)return void h.worker_logger.warning("Function hash not found",{functionID:x,filename:n});const C=_.node.async||!1,S=_.node.loc?s(_.node.loc.start,void 0,n):void 0,O=_.node.loc?s(_.node.loc.end,void 0,n):void 0,P=S?.source??n,M=(0,v.getEntityType)(_),F=(0,p.getMethodKind)(_.node),j=(0,p.getContextualData)(_,s),T=(0,k.getParameterInfo)(_,s),{siblingIndex:D,childrenCount:A}=i[i.length-1],q=i.slice(0,-1),B=(0,p.getFunctionIdentifier)(_),N=B?B.loc?[s(B.loc.start,B.name,P)]:[]:_.node.loc?[s(_.node.loc.start,void 0,P)]:[],$=N[0]?.name??B?.name,W={name:$,sourcemap_location_hints:N,format:$?"%s":void 0};return W.name&&(W.name=(0,E.getSymbolName)(W)),{module:f.default.parse(P).name,symbol:W,context:j,file:P,type:M,format:m.Format.cjs,parameters:T,async:C,start_line:S?.line??-1,end_line:O?.line??-1,start_column:S?.column??-1,source_code_hash:w,runtime_function_id:x,scope_chain:q,methodKind:F,siblingIndex:D,childrenCount:A,third_party_module:l,original_location:{file:n,start_line:e.node.loc?.start?.line,end_line:e.node.loc?.end?.line,start_column:e.node.loc?.start?.column,end_column:e.node.loc?.end?.column}}}catch(e){h.worker_logger.error("Failed to handle function",{filename:n,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}var a}(e,q,o,z,B,t,K);i&&(N?Q.set(n,i):H.push(i))}},exit(e){const{node:t}=e;if(N&&e.isFunction()&&Q.has(t)){const n=Q.get(t),i=I(e);i&&R.functionContainsMark(i.start,i.end)&&H.push(n),Q.delete(t)}G.has(t)&&(z.pop(),G.delete(t))}}}),h.worker_logger.debug("Traversed declarations",{filename:o}),N&&$!==H.length&&h.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:o,marksCount:$,declarationsCount:H.length,remainingMarks:R.getRemainingMarksCount(),initialMarkCount:J});const{declarations:X,blacklist:Y}=function(e,t,n,i,o,r,s,a,c){const l=new Set(t),u=new Set(e.map(e=>e.runtime_function_id));let p=[];const d=[];e.forEach(e=>{l.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:i,has_input_map:void 0!==o,sourcemap_crc:r,file_path_checksum:s,file_checksum:a}):d.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),d.length>0&&h.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t});const f=new Set;l.forEach(e=>{u.has(e)||f.add(e)});const m=f.size>0;return m&&h.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...f]}),{declarations:p,blacklist:m?{file_path_checksum:s,file_checksum:a,uuids:[...f]}:void 0}}(H,A,r,s,L,U,T,D,o);return{declarations:X,blacklist:Y}};const c=s(n(6346)),l=n(8528),u=n(4634),p=n(9127),d=n(5809),f=a(n(6760)),m=n(8528),y=n(2546),h=n(523),g=a(n(3176)),_=n(2784),b=n(3903),v=n(5203),k=n(6864),x=n(1602),E=n(2535),w=n(9011),C={babelrc:!1,configFile:!1};class S{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=d.hudConfig.nextJsMarkVarName;let n=0,i=e.indexOf(t,n);for(;-1!==i;)this.markPositions.push(i),n=i+t.length,i=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,i=t-this.moduleBase;let o=!1,r=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=i){o=!0,r=e;break}}return o&&this.markPositions.splice(r,1),o}getRemainingMarksCount(){return this.markPositions.length}}function O(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function P(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function M(e,t){return(n,i,o)=>({name:i??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:o??void 0})}function F(e){return(t,n,i)=>{const o=e.originalPositionFor({line:t.line,column:t.column});return o?{name:o.name??n,line:o.line??-1,column:o.column??-1,source:o.source??i,resolved:!0,server:{name:n,line:t.line,column:t.column,source:i}}:{name:n??void 0,line:t.line,column:t.column,source:i??void 0,resolved:!1}}}function I(e){let t=e.node.body.loc?.start?.index;if(void 0===t)return null;"ArrowFunctionExpression"===e.node.type&&e.node.body.extra?.parenthesized&&e.node.body.extra?.parenStart&&Number.isInteger(e.node.body.extra.parenStart)&&(t=e.node.body.extra.parenStart);const n=e.node.end;return null==n?null:{start:t,end:n}}let j}},t={};return function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(6066)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1145:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createOutboundDeclarations=void 0,t.createAxiosDeclaration=s,t.createNodeFetchDeclaration=a,t.createRequestDeclaration=c,t.createPgDeclaration=l;const i=n(5809),o=n(8528),r=n(9850);function s(){return[u("axios","Axios","request",i.hudConfig.axiosFunctionId)]}function a(){return[u("node-fetch","node-fetch","fetch",i.hudConfig.nodeFetchFunctionId),...Object.entries(i.hudConfig.nodeFetchBodiesFunctionIds).map(([e,t])=>u("node-fetch","node-fetch",e,t))]}function c(){return[u("request","request","request",i.hudConfig.requestFunctionId),...Object.entries(i.hudConfig.requestMethodFunctionIds).map(([e,t])=>u("request","request",e,t))]}function l(){return[u("pg","Client","connect",i.hudConfig.pgConnectFunctionId),u("pg","Client","query",i.hudConfig.pgQueryFunctionId),u("pg","Client","end",i.hudConfig.pgEndFunctionId)]}function u(e,t,n,i){return{module:e,third_party_module:e,file:`${e}.js`,format:"commonjs",async:!0,runtime_function_id:(0,r.rawFunctionIdToUuidFunctionId)(i),type:o.EntityType.ClassMethod,methodKind:"method",symbol:{sourcemap_location_hints:[{name:n,line:0,column:0,source:`${e}.js`}],name:n,format:"%s"},scope_chain:[{type:o.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0},{type:o.EntityType.ClassDeclaration,symbol:{sourcemap_location_hints:[{name:t,line:0,column:0,source:`${e}.js`}],name:t,format:"%s"},context:{},childrenCount:{},siblingIndex:0}],original_location:{file:`${e}.js`,start_line:0,end_line:0,start_column:0,end_column:0},parameters:[],start_line:0,end_line:0,start_column:0,source_code_hash:"1",bundler_build_id:"1",was_bundler_build_id_generated:!0,has_input_map:!0,sourcemap_crc:1,file_path_checksum:1,file_checksum:1,declarations_count:1,childrenCount:{},siblingIndex:0,context:{}}}t.createOutboundDeclarations={axios:s,"node-fetch":a,request:c,pg:l}},1602:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getScope=function(e,t,n){const r=(0,i.getEntityType)(e);if(r){const s=(0,i.getEntityIdentity)(e.node),a=(0,o.getContextualData)(e,n),c=s?s.loc?[n(s.loc.start,s.name,s.loc.filename??t)]:[]:e.node.loc?[n(e.node.loc.start,void 0,e.node.loc.filename??t)]:[],l=c[0]?.name??s?.name;return{type:r,context:a,symbol:{name:l,sourcemap_location_hints:c,format:l?"%s":void 0},methodKind:(0,o.getMethodKind)(e.node)}}};const i=n(5203),o=n(9127)},2535:function(e,t,n){var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getSymbolName=function(e){let t=e.name;const n=e.sourcemap_location_hints;if(n.length>0&&n.every(e=>e.name)){const i=n.map(e=>e.name?.startsWith("#")?e.name?.slice(1):e.name);e.format?Array.from(e.format.matchAll(/%s/g)).length!==i.length?o.worker_logger.warning("Format string does not match number of location hints",{format:e.format,locationHints:i}):t=r.default.format(e.format,...i):t=i.join(".")}return t??""},t.getNodeLocation=function(e,t,n=void 0){const i=e.loc?.start,r=e.loc?.end;if(!i||!r)return o.worker_logger.info("Node without location",{filename:n,type:e.type}),{start:{source:null,line:-1,column:-1},end:{source:null,line:-1,column:-1}};const s=t({line:i.line,column:i.column}),a=t({line:r.line,column:r.column});return null!==s.line&&null!==s.column&&null!==a.line&&null!==a.column||(o.worker_logger.debug("Could not find location for function",{filename:n,type:e.type,locStart:i,locEnd:r}),s.line=-1,s.column=-1,a.line=-1,a.column=-1),{start:{source:s.source,line:s.line,column:s.column},end:{source:a.source,line:a.line,column:a.column}}};const o=n(523),r=i(n(9023))},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3176:e=>{e.exports=require("buffer-crc32")},3903:e=>{e.exports=require("uuid")},4634:e=>{e.exports=require("source-map")},5203:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getEntityType=function(e){const{node:t}=e;return i.types.isFunctionDeclaration(t)?o.EntityType.FunctionDeclaration:i.types.isFunctionExpression(t)?o.EntityType.FunctionExpression:i.types.isArrowFunctionExpression(t)?o.EntityType.FunctionArrow:i.types.isObjectMethod(t)?o.EntityType.ObjectMethod:i.types.isStaticBlock(t)||i.types.isClassMethod(t)?o.EntityType.ClassMethod:i.types.isClassPrivateMethod(t)?o.EntityType.ClassPrivateMethod:i.types.isClassDeclaration(t)?o.EntityType.ClassDeclaration:i.types.isClassExpression(t)?o.EntityType.ClassExpression:i.types.isForInStatement(t)||i.types.isForOfStatement(t)||i.types.isForStatement(t)?o.EntityType.ForLoop:i.types.isBlockStatement(t)?function(e){const t=e.parentPath.node;if(!(i.types.isFunctionDeclaration(t)||i.types.isFunctionExpression(t)||i.types.isArrowFunctionExpression(t)||i.types.isClassMethod(t)||i.types.isObjectMethod(t)||i.types.isClassPrivateMethod(t)))if(i.types.isIfStatement(t)){if("consequent"===e.parentKey)return o.EntityType.IfConsequent;if("alternate"===e.parentKey)return o.EntityType.IfAlternate;if("test"===e.parentKey)return o.EntityType.IfTest}else{if(i.types.isBlockStatement(t)||i.types.isProgram(t))return o.EntityType.Block;if(i.types.isTryStatement(t)){if("block"===e.parentKey)return o.EntityType.Try;if("finalizer"===e.parentKey)return o.EntityType.Finally}else{if(i.types.isCatchClause(t))return;if(i.types.isWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(i.types.isDoWhileStatement(t))return"test"===e.parentKey?o.EntityType.WhileTest:o.EntityType.Do;if(!(i.types.isForStatement(t)||i.types.isForInStatement(t)||i.types.isForOfStatement(t)))return;if("test"===e.parentKey)return o.EntityType.ForTest;if("body"===e.parentKey)return o.EntityType.ForBlock}}}(e):i.types.isProgram(t)?o.EntityType.Program:i.types.isDoWhileStatement(t)?o.EntityType.DoWhile:i.types.isWhileStatement(t)?o.EntityType.While:i.types.isCatchClause(t)?o.EntityType.Catch:i.types.isObjectExpression(t)?o.EntityType.ObjectExpression:i.types.isWithStatement(t)?o.EntityType.With:i.types.isSwitchStatement(t)?o.EntityType.Switch:i.types.isSwitchCase(t)?o.EntityType.SwitchCase:i.types.isTryStatement(t)?o.EntityType.TryCatch:i.types.isIfStatement(t)?o.EntityType.If:o.EntityType.Other},t.getEntityIdentity=function(e){return i.types.isFunctionDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Function declaration without an identifier"):i.types.isClassDeclaration(e)?i.types.isIdentifier(e.id)?e.id:void r.worker_logger.info("Class declaration without an identifier"):i.types.isFunctionExpression(e)||i.types.isClassExpression(e)?i.types.isIdentifier(e.id)?e.id:void 0:i.types.isClassMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Class method without an identifier"):i.types.isObjectMethod(e)?i.types.isIdentifier(e.key)?e.key:void r.worker_logger.info("Object method without an identifier"):i.types.isClassPrivateMethod(e)?i.types.isIdentifier(e.key.id)?e.key.id:void r.worker_logger.info("Class private method without an identifier"):void 0};const i=n(6346),o=n(8528),r=n(523)},5809:e=>{e.exports=require("./config")},6066:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),o(n(9850),t),o(n(1145),t),o(n(9127),t)},6346:e=>{e.exports=require("@babel/core")},6760:e=>{e.exports=require("node:path")},6864:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getParameterInfo=function(e,t){return e.node.params.map(e=>{try{return p(e,t)}catch{return}}).filter(e=>void 0!==e)};const a=s(n(6346)),c=n(8528),l=n(523);function u(e,t){if(a.types.isIdentifier(e.argument)){const n=e.argument.loc?t(e.argument.loc.start):void 0;return{name:n?.name??e.argument.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}{l.worker_logger.warning("Unsupported rest element",{type:e.argument.type});const n=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}}function p(e,t){if(e)switch(e?.type){case"Identifier":return function(e,t){const n=e.loc?t(e.loc.start,e.name):void 0;return{name:n?.name??e.name,type:c.ParameterTypes[e.type],sourcemap_location_hint:n}}(e,t);case"AssignmentPattern":return function(e,t,n,i){const o=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,left:t,right:i}}(e,p(e.left,t),t,function(e){switch(e.type){case"StringLiteral":case"NumericLiteral":case"BooleanLiteral":case"BigIntLiteral":case"DecimalLiteral":return{type:e.type,value:e.value};case"RegExpLiteral":return{type:e.type,value:e.pattern}}return{type:e.type}}(e.right));case"ArrayPattern":return function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,elements:t}}(e,e.elements.map(e=>p(e,t)).filter(e=>void 0!==e),t);case"RestElement":return u(e,t);case"ObjectPattern":{const n=[];return e.properties.forEach(e=>{if(a.types.isObjectProperty(e)){const i=a.types.isIdentifier(e.key)&&a.types.isIdentifier(e.value)||a.types.isAssignmentPattern(e.value)?void 0:p(e.key,t);n.push(function(e,t,n,i){const o=e.loc?t(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:o,key:n,value:i}}(e,t,i,p(e.value,t)))}else a.types.isRestElement(e)&&n.push(u(e,t))}),function(e,t,n){const i=e.loc?n(e.loc.start):void 0;return{type:c.ParameterTypes[e.type],sourcemap_location_hint:i,properties:t}}(e,n,t)}default:l.worker_logger.warning("Unsupported parameter type",{type:e.type})}}},8528:e=>{e.exports=require("./dto")},9011:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NamespaceScopeAlias=t.ScopableAlias=void 0,t.isHudScopeable=function(e){return i.types.isArrowFunctionExpression(e)||i.types.isBlockStatement(e)||i.types.isCatchClause(e)||i.types.isClassMethod(e)||i.types.isClassPrivateMethod(e)||i.types.isDeclareModule(e)||i.types.isDoExpression(e)||i.types.isDoWhileStatement(e)||i.types.isForInStatement(e)||i.types.isForOfStatement(e)||i.types.isForStatement(e)||i.types.isFunctionDeclaration(e)||i.types.isFunctionExpression(e)||i.types.isIfStatement(e)||i.types.isLabeledStatement(e)||i.types.isObjectMethod(e)||i.types.isProgram(e)||i.types.isStaticBlock(e)||i.types.isSwitchCase(e)||i.types.isTSModuleBlock(e)||i.types.isTryStatement(e)||i.types.isWhileStatement(e)||i.types.isWithStatement(e)||i.types.isClassDeclaration(e)||i.types.isClassExpression(e)||i.types.isObjectExpression(e)||i.types.isSwitchStatement(e)},t.isNamespaceScopeable=function(e){return i.types.isFunction(e)||i.types.isClass(e)||i.types.isObjectExpression(e)};const i=n(6346);t.ScopableAlias="ArrowFunctionExpression|BlockStatement|CatchClause|ClassMethod|ClassPrivateMethod|DeclareModule|DoExpression|DoWhileStatement|ForInStatement|ForOfStatement|ForStatement|FunctionDeclaration|FunctionExpression|IfStatement|LabeledStatement|ObjectMethod|StaticBlock|SwitchCase|TSModuleBlock|TryStatement|WhileStatement|WithStatement|ClassDeclaration|ClassExpression|ObjectExpression|SwitchStatement",t.NamespaceScopeAlias="FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod|ClassMethod|ClassPrivateMethod|ClassDeclaration|ClassExpression|ObjectExpression"},9023:e=>{e.exports=require("util")},9127:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.getFunctionIdentifier=function(e){const{node:t}=e;if(c.types.isFunctionDeclaration(t)||c.types.isFunctionExpression(t)){if(c.types.isIdentifier(t.id))return t.id}else if(c.types.isClassMethod(t)){if(c.types.isIdentifier(t.key))return t.key}else if(c.types.isClassPrivateMethod(t)){if(c.types.isIdentifier(t.key.id))return t.key.id}else if(c.types.isObjectMethod(t)&&c.types.isIdentifier(t.key))return t.key},t.getContextSymbol=g,t.getContextualData=function(e,t){let n,i;(e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression())&&(n=function(e,t){const n=e.parentPath;if(n.isCallExpression())for(const[i,o]of n.node.arguments.entries())if(o===e.node){const o=n.node.callee;let r;try{r=y(o,t)}catch(t){if(!(t instanceof u.HudUnsupportedError))throw t;{const n=`${o.type}-${e.node.type}`;v.has(n)||(p.worker_logger.warning("could not get callee symbol recursively",{error:t,errorMessage:t.message,calleType:o.type,nodeType:e.node.type}),v.add(n))}}const s=_(n.node,t);return{callee:{symbol:r,argsCount:n.node.arguments.length,args:s},index:i}}}(e,t)),(e.isFunctionExpression()||e.isArrowFunctionExpression())&&(i=function(e){const t=e.parentPath;return!!t.isCallExpression()&&t.node.callee===e.node}(e));const o=g(e,t);return o&&(o.name=(0,f.getSymbolName)(o)),{symbol:o,callback:n,immediatelyInvoked:i}},t.getMethodKind=function(e){if(a.types.isClassMethod(e)||a.types.isObjectMethod(e)||a.types.isClassPrivateMethod(e))return e.kind};const a=s(n(6346)),c=n(6346),l=n(8528),u=n(2546),p=n(523),d=n(9772),f=n(2535);function m(e,t,n){const i=e.loc?n(e.loc.start,t,e.loc.filename):void 0;return{name:i?.name??t,sourcemap_location_hints:i?[i]:[],format:"%s"}}function y(e,t){if(c.types.isIdentifier(e)){const n=e.loc?[t(e.loc.start,e.name,e.loc.filename)]:[];return{name:n[0]?.name??e.name,sourcemap_location_hints:n,format:"%s"}}if(c.types.isMemberExpression(e)||c.types.isOptionalMemberExpression(e)){let n;n=c.types.isThisExpression(e.object)?{name:"this",sourcemap_location_hints:e.object.loc?[t(e.object.loc.start,"this",e.object.loc.filename)]:[]}:y(e.object,t);const i=y(e.property,t),o=e.computed?n.name+"["+i.name+"]":n.name+"."+i.name,r=n.format??"%s",s=i.format??"%s",a=e.computed?`${r}[${s}]`:`${r}.${s}`;return{name:o,sourcemap_location_hints:[...n.sourcemap_location_hints,...i.sourcemap_location_hints],format:a}}if(c.types.isOptionalCallExpression(e)||c.types.isCallExpression(e))return y(e.callee,t);if(c.types.isSequenceExpression(e))return(0,d.isHudAwaitSequence)(e)?y((0,d.getHudAwaitSequenceElement)(e),t):y(e.expressions[e.expressions.length-1],t);if(c.types.isArrayExpression(e))return{name:"[]",sourcemap_location_hints:e.loc?[t(e.loc.start,"[]",e.loc.filename)]:[],format:"%s"};if(c.types.isObjectExpression(e))return{name:"{}",sourcemap_location_hints:e.loc?[t(e.loc.start,"{}",e.loc.filename)]:[],format:"%s"};if(c.types.isStringLiteral(e)){const n=e.loc?[t(e.loc.start,e.value,e.loc.filename)]:[];return{name:`"${n[0]?.name??e.value}"`,sourcemap_location_hints:n,format:'"%s"'}}throw new u.HudUnsupportedError("Unsupported left side of assignment - "+e.type+"loc - "+JSON.stringify(e.loc))}const h=new Set;function g(e,t){const{node:n}=e;if(e.isExpression())try{return function(e,t){const{parent:n}=e;if(c.types.isVariableDeclarator(n)&&c.types.isIdentifier(n.id))return m(n,n.id.name,t);if(c.types.isObjectProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isClassProperty(n)&&c.types.isIdentifier(n.key))return m(n,n.key.name,t);if(c.types.isAssignmentExpression(n))return y(n.left,t);if(c.types.isAssignmentPattern(n))return y(n.left,t);throw new u.HudUnsupportedError(`Unsupported parent type - ${n.type} for me ${e.node.type}`)}(e,t)}catch(t){if(t instanceof u.HudUnsupportedError){const n=`${e.parentPath?.node.type}`;return void(h.has(n)||(p.worker_logger.warning("getContextSymbol: Unsupported parent node type",{parentType:e.parentPath?.node.type,error:t,errorMessage:t.message}),h.add(n)))}throw t}p.worker_logger.debug("getContextSymbol; Unsupported node type",{type:n.type})}function _(e,t){const n=[];return e.arguments.forEach((e,i)=>{let o,r;if(c.types.isStringLiteral(e)?(o=l.ArgumentTypes.StringLiteral,r=e.value):c.types.isTemplateLiteral(e)?(o=l.ArgumentTypes.TemplateString,r=function(e){let t="";const n=e.quasis,i=e.expressions;for(let e=0;e<n.length;e++)t+=n[e].value.cooked,e<i.length&&(t+=`\${${b(i[e])}}`);return t=`\`${t}\``,t}(e)):c.types.isIdentifier(e)&&(o=l.ArgumentTypes.Identifier,r=e.name),o&&r){const s=c.types.isIdentifier(e)?e.name:void 0,a=e.loc?t(e.loc.start,s):void 0;n.push({index:i,type:o,value:a?.name??r,sourcemap_location_hint:a})}}),n}function b(e){if(c.types.isIdentifier(e))return e.name;if(c.types.isStringLiteral(e))return e.value;if(c.types.isCallExpression(e)||c.types.isOptionalCallExpression(e)){const t=e;if(c.types.isIdentifier(t.callee))return t.callee.name;if(c.types.isMemberExpression(t.callee)||c.types.isOptionalMemberExpression(t.callee)){let e="";const n=t.callee;if(c.types.isThisExpression(n.object)?e+="this.":c.types.isIdentifier(n.object)&&(e+=`${n.object.name}.`),""!==e&&c.types.isIdentifier(n.property))return e+=`${n.property.name}`,e}}return""}const v=new Set},9772:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isHudAwaitSequence=function(e){if(e.expressions.length<2)return!1;const t=e.expressions[e.expressions.length-1];return!!i.types.isIdentifier(t)&&!!t.name.startsWith(o.hudConfig.wrapVarPrefix)},t.getHudAwaitSequenceElement=function(e){const t=e.expressions[0];if(!i.types.isAssignmentExpression(t))throw new r.HudUnsupportedError("Expected assignment expression");const{left:n,right:s}=t;if(!i.types.isIdentifier(n)||!n.name.startsWith(o.hudConfig.wrapVarPrefix))throw new r.HudUnsupportedError("Expected identifier starting with "+o.hudConfig.wrapVarPrefix);return s};const i=n(6346),o=n(5809),r=n(2546)},9850:function(e,t,n){var i,o=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(i=function(e){return i=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},i(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=i(e),s=0;s<n.length;s++)"default"!==n[s]&&o(t,e,n[s]);return r(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.fixSourceMap=O,t.getRealPositionNothingFunc=F,t.getRealPositionOffsetsFunc=P,t.getRealPositionSourceMapFunc=I,t.parseDeclarations=async function(e,t,n=null,i){const{filename:o,bundlerBuildId:r,bundlerBuildIdGenerated:s,lineOffset:a,columnOffset:F,file_path_checksum:D,file_checksum:A,functionIds:q,sourceCodeHash:B,moduleBase:N,isNextJsApp:$,marksCount:W}=e;if(g.worker_logger.debug("Parsing code",{filename:o}),i)try{if(!j){const e=(0,h.myRequire)("ts-node");j=e.create({...i,transpileOnly:!0,typeCheck:!1})}const e=function(e,t,n){try{return n.compile(e,t)}catch(e){return void g.worker_logger.warning("ts file pass, but failed to compile with ts-node",{filename:t,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}(t,o,j);if(!e)return{declarations:[],blacklist:{file_path_checksum:D,file_checksum:A,uuids:q}};t=e}catch(e){return g.worker_logger.error("Failed to require and compile ts file",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0}),{declarations:[],blacklist:{file_path_checksum:D,file_checksum:A,uuids:q}}}else if(o.endsWith(".ts")||o.endsWith(".mts"))return g.worker_logger.error("ts file pass, but not found ts-options"),{declarations:[],blacklist:{file_path_checksum:D,file_checksum:A,uuids:q}};const U=(0,_.default)(t).readUInt32BE();if(U!==A)return g.worker_logger.warning("File checksum mismatch",{filename:o,file_path_checksum:D,diskFileChecksum:U,file_checksum:A,functionIds:q}),{declarations:[],blacklist:{file_path_checksum:D,file_checksum:A,uuids:q}};let L,K,H=(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0});if(a&&F)H=P(a,F);else{const e=(0,b.getSourceMap)(o,t);try{null!==e&&(K=(0,_.default)(e).readUInt32BE(),f.hudConfig.userConfig.disableSourceMapsResolution?.value||(L=JSON.parse(e),L&&(H=I(await new u.SourceMapConsumer(O(L))))))}catch(e){g.worker_logger.error("Failed to parse source map",{filename:o,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}}g.worker_logger.debug("Parsing code",{filename:o});const R=[],J=new S(t,N),V=J.getRemainingMarksCount(),z=await c.parseAsync(t,C);if(null===z)return g.worker_logger.warning("Failed parsing code to tree",{filename:o,file_path_checksum:D,diskFileChecksum:U,file_checksum:A,functionIds:q}),{declarations:[],blacklist:{file_path_checksum:D,file_checksum:A,uuids:q}};g.worker_logger.debug("Parsed code to tree",{filename:o});const G=[{type:l.EntityType.Program,symbol:{sourcemap_location_hints:[]},context:{},childrenCount:{},siblingIndex:0}],Q=new Set;g.worker_logger.debug("Traversing declarations",{filename:o}),n?.postMessage("eventlooptime"),c.traverse(z,{[w.NamespaceScopeAlias]:{enter(e){const{node:t}=e;if(!(0,w.isNamespaceScopeable)(t))return;const n=G[G.length-1],i=(0,E.getScope)(e,o,H);if(!i)return;const r=n.childrenCount[i.type]||0,s={...i,childrenCount:{},siblingIndex:r};n.childrenCount[i.type]=r+1,G.push(s),Q.add(t)},exit(e){const{node:n}=e;if(e.isFunction()){const n=function(e,t,n,i,o,r,s){try{const c=(0,h.getInstrumentedThirdPartyModuleInfo)(n);let l;if(c){if(!function(e,t){const n=(0,d.getFunctionIdentifier)(e);if(!n)return!1;const i=n.name;return t.functions.includes(i)}(e,c))return;l=c.moduleName}const u=M(e);if(!u)throw new Error("Function node has no block start location");const b=e;if(void 0===e.node.start||null===e.node.start||void 0===e.node.end||null===e.node.end)throw new Error("Function node has no start or end location");const E=function(e,t,n,i){const o=i.slice(0,n),r=`${e}_${t}_${Buffer.byteLength(o,"utf8")}`;return p.v5(r,f.hudConfig.functionUuidNamespace).toString()}(t,n,u.start-(o-1),r),w=(a=r.slice(e.node.start,e.node.end),(0,_.default)(a).readUInt32BE().toString());if(!w)return void g.worker_logger.warning("Function hash not found",{functionID:E,filename:n});const C=b.node.async||!1,S=b.node.loc?s(b.node.loc.start,void 0,n):void 0,O=b.node.loc?s(b.node.loc.end,void 0,n):void 0,F=S?.source??n,P=(0,v.getEntityType)(b),I=(0,d.getMethodKind)(b.node),j=(0,d.getContextualData)(b,s),T=(0,k.getParameterInfo)(b,s),{siblingIndex:D,childrenCount:A}=i[i.length-1],q=i.slice(0,-1),B=(0,d.getFunctionIdentifier)(b),N=B?B.loc?[s(B.loc.start,B.name,F)]:[]:b.node.loc?[s(b.node.loc.start,void 0,F)]:[],$=N[0]?.name??B?.name,W={name:$,sourcemap_location_hints:N,format:$?"%s":void 0};return W.name&&(W.name=(0,x.getSymbolName)(W)),{module:m.default.parse(F).name,symbol:W,context:j,file:F,type:P,format:y.Format.cjs,parameters:T,async:C,start_line:S?.line??-1,end_line:O?.line??-1,start_column:S?.column??-1,source_code_hash:w,runtime_function_id:E,scope_chain:q,methodKind:I,siblingIndex:D,childrenCount:A,third_party_module:l,original_location:{file:n,start_line:e.node.loc?.start?.line,end_line:e.node.loc?.end?.line,start_column:e.node.loc?.start?.column,end_column:e.node.loc?.end?.column}}}catch(e){g.worker_logger.error("Failed to handle function",{filename:n,error:e instanceof Error?e.message:void 0,stack:e instanceof Error?e.stack:void 0})}var a}(e,B,o,G,N,t,H);if(n)if($){const t=M(e);t&&J.functionContainsMark(t.start,t.end)&&R.push(n)}else R.push(n)}Q.has(n)&&(G.pop(),Q.delete(n))}}}),g.worker_logger.debug("Traversed declarations",{filename:o}),$&&W!==R.length&&g.worker_logger.warning("Marks count mismatch while parsing declarations",{filename:o,marksCount:W,declarationsCount:R.length,remainingMarks:J.getRemainingMarksCount(),initialMarkCount:V});const{declarations:X,blacklist:Y}=function(e,t,n,i,o,r,s,a,c){t=t.map(T);const l=new Set(t),u=new Set(e.map(e=>e.runtime_function_id));let p=[];const d=[];e.forEach(e=>{l.has(e.runtime_function_id)?p.push({...e,declarations_count:0,bundler_build_id:n,was_bundler_build_id_generated:i,has_input_map:void 0!==o,sourcemap_crc:r,file_path_checksum:s,file_checksum:a}):d.push(e)}),p=p.map(e=>({...e,declarations_count:p.length})),d.length>0&&g.worker_logger.warning("Function IDs mismatch, missing instrumentation",{filename:c,runtimeFunctionIds:t});const f=new Set;l.forEach(e=>{u.has(e)||f.add(e)});const m=f.size>0;return m&&g.worker_logger.error("Function IDs mismatch, missing declarations",{filename:c,missingRuntimeFunctionIds:[...f]}),{declarations:p,blacklist:m?{file_path_checksum:s,file_checksum:a,uuids:[...f]}:void 0}}(R,q,r,s,L,K,D,A,o);return{declarations:X,blacklist:Y}},t.rawFunctionIdToUuidFunctionId=T;const c=s(n(6346)),l=n(8528),u=n(4634),p=s(n(3903)),d=n(9127),f=n(5809),m=a(n(6760)),y=n(8528),h=n(2546),g=n(523),_=a(n(3176)),b=n(2784),v=n(5203),k=n(6864),E=n(1602),x=n(2535),w=n(9011),C={babelrc:!1,configFile:!1};class S{markPositions=[];moduleBase;constructor(e,t){this.moduleBase=t,this.findMarkPositions(e)}findMarkPositions(e){const t=f.hudConfig.nextJsMarkVarName;let n=0,i=e.indexOf(t,n);for(;-1!==i;)this.markPositions.push(i),n=i+t.length,i=e.indexOf(t,n)}functionContainsMark(e,t){const n=e-this.moduleBase,i=t-this.moduleBase;let o=!1,r=0;for(let e=0;e<this.markPositions.length;e++){const t=this.markPositions[e];if(t>=n&&t<=i){o=!0,r=e;break}}return o&&this.markPositions.splice(r,1),o}getRemainingMarksCount(){return this.markPositions.length}}function O(e){let t;return t="string"==typeof e?JSON.parse(e):e,t.sources=t.sources.map(e=>e.replace(/^webpack:\/\/(?:@[^/]+?[/])?[^/]+\//,"")),t}function F(){return(e,t,n)=>({name:t??void 0,line:e.line,column:e.column,source:n??void 0})}function P(e,t){return(n,i,o)=>({name:i??void 0,line:n.line+(e||0),column:n.column+(1===n.line&&t||0),source:o??void 0})}function I(e){return(t,n,i)=>{const o=e.originalPositionFor({line:t.line,column:t.column});return o?{name:o.name??n,line:o.line??-1,column:o.column??-1,source:o.source??i,resolved:!0,server:{name:n,line:t.line,column:t.column,source:i}}:{name:n??void 0,line:t.line,column:t.column,source:i??void 0,resolved:!1}}}function M(e){let t=e.node.body.loc?.start?.index;if(void 0===t)return null;"ArrowFunctionExpression"===e.node.type&&e.node.body.extra?.parenthesized&&e.node.body.extra?.parenStart&&Number.isInteger(e.node.body.extra.parenStart)&&(t=e.node.body.extra.parenStart);const n=e.node.end;return null==n?null:{start:t,end:n}}let j;function T(e){try{return p.stringify(Buffer.from(e+"==","base64"))}catch(t){throw g.worker_logger.error("Failed to convert raw function id to uuid function id",{rawFunctionId:e,error:t instanceof Error?t.message:void 0,stack:t instanceof Error?t.stack:void 0}),t}}}},t={};return function n(i){var o=t[i];if(void 0!==o)return o.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(6066)})());
2
2
  //# sourceMappingURL=declarations.js.map
@@ -1,2 +1,2 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=async function(e,t,r,o=!1){const n=[],i=[];return await Promise.all(Array.from({length:t},async function(){for(;e.length>0;){const t=e.shift();try{const e=await r(t);n.push(e)}catch(e){if(i.push(e),o)throw e}}})),{results:n,errors:i}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=async function(e,t,r,o=3){for(let n=0;n<o;n++)try{return await u.default.post(e,t,r)}catch(t){if(t instanceof u.AxiosError&&401===t.response?.status)throw new s.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,l.logToHud)(`Failed request to ${e}, attempt ${n+1} of ${o}. Error: ${t}`),await new Promise(e=>setTimeout(e,1))}throw new s.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)};const s=r(2546),u=a(r(8938)),l=r(5231)},3903:e=>{e.exports=require("uuid")},4414:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadSourceMap=h,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,f.logToHud)("Skipping source map upload due to env var");else{(0,f.logToHud)(`Uploading source maps for ${e.length} files`);try{const r=[];for(const{buildId:o,filepath:n}of e){const e=`${n}.map`;try{await c.promises.access(e,c.constants.F_OK),r.push({buildId:o,filePath:e,hudKey:t})}catch{(0,f.logToHud)(`No source map found for file: ${n}`)}}await(0,p.limitedParallel)(r,10,h,!0),(0,f.logToHud)("Finished uploading source maps")}catch{return(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,f.setDontSendLogs)()}}};const u=r(5809),l=r(2546),d=s(r(2305)),c=a(r(9896)),f=r(5231),p=r(870),g=r(3066);async function h(e){const{buildId:t,filePath:r,hudKey:o}=e,n=new d.default;n.append("build_id",t),n.append("token",o);try{const e=await c.promises.readFile(r,"utf8"),t=JSON.parse(e);delete t.sourcesContent,n.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,f.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,g.requestRelentless)(`${u.hudConfig.sink.url}/${u.hudConfig.endpoints.sourceMap}`,n,{headers:{"Content-Type":"multipart/form-data"},timeout:u.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,f.logToHud)(`failed uploading source map. File: ${r}, Error: ${e}`),(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemap(r))}}},5231:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logToUser=function(e){let t="";t="string"==typeof e?(0,n.formatLogMessage)(`${u}${e}`):(0,n.formatLogMessage)(`${u}${e.message}`,e.errCode,e.moreInfo),console.log(t),f(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&f(e,t)},t.logToHud=f,t.exportBuildLogs=async function(e){const t=[];for(let r=0;r<d.length;r+=o.hudConfig.esbuildPluginLogsBatchSize){const n=d.slice(r,r+o.hudConfig.esbuildPluginLogsBatchSize).map(t=>({...t,accessToken:e}));t.push(n)}await(0,a.limitedParallel)(t,10,p)},t.setDontSendLogs=function(){c=!1},t.getShouldSendLogs=function(){return c};const o=r(5809),n=r(523),i=r(6982),a=r(870),s=r(3066),u=o.hudConfig.esbuildPluginMessagePrefix,l=(0,i.randomUUID)(),d=[];let c=!0;function f(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,n.formatLogMessage)(`${u}${e}`)),console.log(e)),d.push({message:e,SessionID:l,timestamp:Date.now()})}async function p(e){await(0,s.requestRelentless)(o.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},6932:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudBuildError=void 0,t.verifyAndMarkFinalFiles=async function(e,t,r){const o=[];for(const n of e){if(!n.path.endsWith(".js")){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}if(!n.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}const e=(0,c.v5)(n.contents,s.hudConfig.bundlerBuildUuidNamespace);o.push({filepath:n.path,buildId:e});const i=m(n.text,e);process.env.HUD_SKIP_FILE_VALIDATION||y(i,n.path,r),n.contents=new Uint8Array(Buffer.from(i,"utf8")),t&&await(0,p.writeFileAndFolder)(n.path,n.contents)}return o},t.markFileAsHudModified=m,t.markFile=function(e,t){const r=d.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[b(e,!0)],suffixStatements:[b(e,!1)]});if(!r||!r.code||!r.map)throw new Error("Failed generating ast");return(0,l.appendInlineSourceMap)(r.code,r.map)},t.createMark=b,t.verifyFileContent=y;const s=r(5809),u=r(2030),l=r(2546),d=a(r(2784)),c=r(3903),f=a(r(9154)),p=r(7085),g=r(5231);class h extends Error{}function m(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function b(e,t){const r=t?"Start":"End";return`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${r}:${e}");`}function y(e,t,r){try{(0,g.logToHud)(`Verifying file content: ${t}, with marks`),new f.Script(e),(0,g.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:o,editedChunksSizes:n}=(0,u.editInSplits)(e,t,r,!0,!0,e=>!e.includes("node_modules"));if(!o)throw new h(`Failed verify file content, ${t}`);for(let e=0;e<n.length;e+=p.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(n.slice(e,e+p.LOG_CHUNKS_SIZE_BATCH));(0,g.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,g.logToHud)(`Verifying new file content: ${t}`),new f.Script(o),(0,g.logToHud)(`Verified new file content: ${t}`),(0,g.logToHud)(`${t}: Original code size: ${e.length}, new code size: ${o.length}`)}catch(e){throw(0,g.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new h(`Failed verify file content, ${t}`)}}t.HudBuildError=h},6982:e=>{e.exports=require("crypto")},7085:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.LOG_CHUNKS_SIZE_BATCH=void 0,t.writeFileAndFolder=async function(e,t){const r=f.dirname(e);try{await d.promises.stat(r)}catch{await d.promises.mkdir(r,{recursive:!0})}await d.promises.writeFile(e,t)},t.getModuleRoot=_;const s=r(8528),u=r(2030),l=r(6982),d=a(r(9896)),c=a(r(857)),f=a(r(6928)),p=r(5809),g=r(2546),h=r(9929),m=r(5231),b=r(6932),y=r(4414),w=30;async function v(e,t,r,o,n){if(!(r&&o&&n&&o.test(e)))return;const i=f.join(n,e),a=f.dirname(i);try{await d.promises.access(a)}catch{await d.promises.mkdir(a,{recursive:!0})}await d.promises.writeFile(i,t,"utf8");const s=await r(i);return s?.contents&&(t=s.contents),t}async function _(e){let t=f.dirname(e);for(let e=0;e<w&&"/"!==t;e++){const e=f.join(t,"package.json");try{return await d.promises.access(e),t}catch{t=f.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=p.hudConfig.esbuildPluginLogsChunkSize;const O="hud-esbuild-plugin";t.plugin=e=>({name:O,async setup(t){if("inline"===t.initialOptions.sourcemap||"both"===t.initialOptions.sourcemap)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildSourceMapInline());if("node"!==t.initialOptions.platform)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===c.platform())return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedWindows());const r=e?.hudKey??process.env.HUD_KEY;if(!r)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildMissingKey());const o=e?.includeModules??(0,p.getModulesToTraceFromEnv)()??[],n=(0,u.createCheckers)(o);(0,m.logToUser)("started running");const i=t.initialOptions.write??!0;t.initialOptions.write=!1;const a="esm"===t.initialOptions?.format?s.Format.esm:s.Format.cjs,{callback:w,filter:T,tempDir:S}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const r=t.plugins.findIndex(e=>e.name===O),o=t.plugins[r+1];if(!o||"datadog-esbuild"!==o.name)return;let n;(0,m.logToHud)("datadog-esbuild plugin detected");const i={...e,onLoad:(...e)=>{n=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(o.setup(i),!n)return void(0,m.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=f.join(c.tmpdir(),`hud-${(0,l.randomUUID)()}`);try{return await d.promises.access(a),void(0,m.logToUser)("temp dir already exists, try rerunning the build.")}catch{}return(0,m.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await d.promises.mkdir(a,{recursive:!0}),{filter:n[0].filter,callback:n[1],tempDir:a}}(t)??{},$=new Set(t.initialOptions.external||[]),U=new Map;t.onResolve({filter:/.*/},async e=>{if(e.pluginData?.hud?.calledFromHud)return;if($.has(e.path))return;const r=p.hudConfig.frameworksToPatch.get(e.path);if(!r)return;if(!r.enable||!r.enableEsbuild)return;const o={...e};delete o.path;const n=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await _(n.path);i&&(U.set(i,e.path),(0,m.logToHud)(`mapping framework: ${i} => ${e.path}`))}),t.onLoad({filter:/.*\.(js|ts|cjs)$/},async e=>{try{const t=w?async t=>await w({...e,path:t}):void 0;if((0,u.skip)(e.path,n)){const r=await(0,h.getFrameworkContentSuffix)(e.path,U);if(!r)return;let o=await d.promises.readFile(e.path,"utf8");return o=await v(e.path,o,t,T,S)??o,o+=r,{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}let r=await d.promises.readFile(e.path,"utf8");return r=(0,b.markFile)(e.path,r),r=await v(e.path,r,t,T,S)??r,r+=await(0,h.getFrameworkContentSuffix)(e.path,U)??"",{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}catch(t){return(0,m.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,m.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}}),t.onEnd(async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,b.verifyAndMarkFinalFiles)(e.outputFiles,i,a),(0,m.logToUser)("finished")}catch(e){throw(0,m.logToHud)(`failed validating. Error: ${e}`),(0,m.logToUser)(g.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,y.uploadAllSourceMaps)(t,r)}catch(e){(0,m.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(S)try{await d.promises.access(S),(0,m.logToHud)("cleaning temp dir"),await d.promises.rm(S,{recursive:!0,force:!0})}catch{}}catch(e){(0,m.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,m.getShouldSendLogs)()&&await(0,m.exportBuildLogs)(r)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,m.logToUser)(`Failed exporting build logs. Error: ${e}`)}}})}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=async function(e,t){const r=[...t.entries()].find(([t,r])=>e.startsWith(t));if(!r)return;const[u,l]=r;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=o.hudConfig.frameworksToPatch.get(d);if(!(c?.enable&&c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${n.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)};const o=r(5809),n=r(8528),i=r(2030),a=r(7085),s=r(5231)}},t={};return function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}(7085)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},857:e=>{e.exports=require("os")},870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.limitedParallel=async function(e,t,r,o=!1){const n=[],i=[];return await Promise.all(Array.from({length:t},async function(){for(;e.length>0;){const t=e.shift();try{const e=await r(t);n.push(e)}catch(e){if(i.push(e),o)throw e}}})),{results:n,errors:i}}},2030:e=>{e.exports=require("./instrument")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},2784:e=>{e.exports=require("../native/_index")},3066:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.requestRelentless=async function(e,t,r,o=3){for(let n=0;n<o;n++)try{return await u.default.post(e,t,r)}catch(t){if(t instanceof u.AxiosError&&401===t.response?.status)throw new s.HudClientUnauthorizedError(`Unauthorized request for ${e}`);(0,l.logToHud)(`Failed request to ${e}, attempt ${n+1} of ${o}. Error: ${t}`),await new Promise(e=>setTimeout(e,1))}throw new s.HudClientExceededMaxRetries(`Exceeded max retries for ${e}`)};const s=r(2546),u=a(r(8938)),l=r(5231)},3903:e=>{e.exports=require("uuid")},4414:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t}),s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.uploadSourceMap=h,t.uploadAllSourceMaps=async function(e,t){if(process.env.HUD_SKIP_SOURCEMAP_UPLOAD)(0,f.logToHud)("Skipping source map upload due to env var");else{(0,f.logToHud)(`Uploading source maps for ${e.length} files`);try{const r=[];for(const{buildId:o,filepath:n}of e){const e=`${n}.map`;try{await c.promises.access(e,c.constants.F_OK),r.push({buildId:o,filePath:e,hudKey:t})}catch{(0,f.logToHud)(`No source map found for file: ${n}`)}}await(0,p.limitedParallel)(r,10,h,!0),(0,f.logToHud)("Finished uploading source maps")}catch{return(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemapUnauthorized()),void(0,f.setDontSendLogs)()}}};const u=r(5809),l=r(2546),d=s(r(2305)),c=a(r(9896)),f=r(5231),p=r(870),g=r(3066);async function h(e){const{buildId:t,filePath:r,hudKey:o}=e,n=new d.default;n.append("build_id",t),n.append("token",o);try{const e=await c.promises.readFile(r,"utf8"),t=JSON.parse(e);delete t.sourcesContent,n.append("sourcemap",JSON.stringify(t),{filename:"sourcemap",contentType:"application/json"})}catch(e){return(0,f.logToHud)(`failed parsing source map, skipping upload. Error: ${e}`),void(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedParsingSourcemap())}try{await(0,g.requestRelentless)(`${u.hudConfig.sink.url}/${u.hudConfig.endpoints.sourceMap}`,n,{headers:{"Content-Type":"multipart/form-data"},timeout:u.hudConfig.esbuildUploadSourceMapTimeout})}catch(e){if(e instanceof Error&&e.message.includes("Unauthorized"))throw e;(0,f.logToHud)(`failed uploading source map. File: ${r}, Error: ${e}`),(0,f.logToUser)(l.UserErrorLogs.EsbuildFailedUploadingSourcemap(r))}}},5231:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.logToUser=function(e){let t="";t="string"==typeof e?(0,n.formatLogMessage)(`${u}${e}`):(0,n.formatLogMessage)(`${u}${e.message}`,e.errCode,e.moreInfo),console.log(t),f(t,!1)},t.logToHudDebug=function(e,t=!0){"true"===process.env.HUD_PLUGIN_DEBUG&&f(e,t)},t.logToHud=f,t.exportBuildLogs=async function(e){const t=[];for(let r=0;r<d.length;r+=o.hudConfig.esbuildPluginLogsBatchSize){const n=d.slice(r,r+o.hudConfig.esbuildPluginLogsBatchSize).map(t=>({...t,accessToken:e}));t.push(n)}await(0,a.limitedParallel)(t,10,p)},t.setDontSendLogs=function(){c=!1},t.getShouldSendLogs=function(){return c};const o=r(5809),n=r(523),i=r(6982),a=r(870),s=r(3066),u=o.hudConfig.esbuildPluginMessagePrefix,l=(0,i.randomUUID)(),d=[];let c=!0;function f(e,t=!0){"true"===process.env.HUD_PLUGIN_VERBOSE&&(t&&(e=(0,n.formatLogMessage)(`${u}${e}`)),console.log(e)),d.push({message:e,SessionID:l,timestamp:Date.now()})}async function p(e){await(0,s.requestRelentless)(o.hudConfig.pluginsLogEndpoint,{messages:e},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}},5809:e=>{e.exports=require("./config")},6928:e=>{e.exports=require("path")},6932:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.HudBuildError=void 0,t.verifyAndMarkFinalFiles=async function(e,t,r){const o=[];for(const n of e){if(!n.path.endsWith(".js")){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}if(!n.text.includes(s.hudConfig.esbuildGlobalVar)){t&&await(0,p.writeFileAndFolder)(n.path,n.contents);continue}const e=(0,c.v5)(n.contents,s.hudConfig.bundlerBuildUuidNamespace);o.push({filepath:n.path,buildId:e});const i=m(n.text,e);process.env.HUD_SKIP_FILE_VALIDATION||y(i,n.path,r),n.contents=new Uint8Array(Buffer.from(i,"utf8")),t&&await(0,p.writeFileAndFolder)(n.path,n.contents)}return o},t.markFileAsHudModified=m,t.markFile=function(e,t){const r=d.markFile(t,{data:{filename:e,format:"esm"},initialStatements:[b(e,!0)],suffixStatements:[b(e,!1)]});if(!r||!r.code||!r.map)throw new Error("Failed generating ast");return(0,l.appendInlineSourceMap)(r.code,r.map)},t.createMark=b,t.verifyFileContent=y;const s=r(5809),u=r(2030),l=r(2546),d=a(r(2784)),c=r(3903),f=a(r(9154)),p=r(7085),g=r(5231);class h extends Error{}function m(e,t){return`/*modifiedByHudESBuildPlugin-${t}*/${e}`}function b(e,t){const r=t?"Start":"End";return e=t?e:"",`;globalThis && (globalThis.${s.hudConfig.esbuildGlobalVar}="${r}:${e}");`}function y(e,t,r){try{(0,g.logToHud)(`Verifying file content: ${t}, with marks`),new f.Script(e),(0,g.logToHud)(`Editing in splits file content: ${t}`);const{transformedCode:o,editedChunksSizes:n}=(0,u.editInSplits)(e,t,r,!0,!0,!0,e=>!e.includes("node_modules"));if(!o)throw new h(`Failed verify file content, ${t}`);for(let e=0;e<n.length;e+=p.LOG_CHUNKS_SIZE_BATCH){const t=JSON.stringify(n.slice(e,e+p.LOG_CHUNKS_SIZE_BATCH));(0,g.logToHudDebug)(`Edited chunks sizes: ${t}`)}(0,g.logToHud)(`Verifying new file content: ${t}`),new f.Script(o),(0,g.logToHud)(`Verified new file content: ${t}`),(0,g.logToHud)(`${t}: Original code size: ${e.length}, new code size: ${o.length}`)}catch(e){throw(0,g.logToHud)(`Failed verify file content, ${t}, error: ${e}`),new h(`Failed verify file content, ${t}`)}}t.HudBuildError=h},6982:e=>{e.exports=require("crypto")},7085:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),a=0;a<r.length;a++)"default"!==r[a]&&n(t,e,r[a]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.plugin=t.LOG_CHUNKS_SIZE_BATCH=void 0,t.writeFileAndFolder=async function(e,t){const r=f.dirname(e);try{await d.promises.stat(r)}catch{await d.promises.mkdir(r,{recursive:!0})}await d.promises.writeFile(e,t)},t.getModuleRoot=_;const s=r(8528),u=r(2030),l=r(6982),d=a(r(9896)),c=a(r(857)),f=a(r(6928)),p=r(5809),g=r(2546),h=r(9929),m=r(5231),b=r(6932),y=r(4414),w=30;async function v(e,t,r,o,n){if(!(r&&o&&n&&o.test(e)))return;const i=f.join(n,e),a=f.dirname(i);try{await d.promises.access(a)}catch{await d.promises.mkdir(a,{recursive:!0})}await d.promises.writeFile(i,t,"utf8");const s=await r(i);return s?.contents&&(t=s.contents),t}async function _(e){let t=f.dirname(e);for(let e=0;e<w&&"/"!==t;e++){const e=f.join(t,"package.json");try{return await d.promises.access(e),t}catch{t=f.dirname(t)}}}t.LOG_CHUNKS_SIZE_BATCH=p.hudConfig.esbuildPluginLogsChunkSize;const O="hud-esbuild-plugin";t.plugin=e=>({name:O,async setup(t){if("inline"===t.initialOptions.sourcemap||"both"===t.initialOptions.sourcemap)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildSourceMapInline());if("node"!==t.initialOptions.platform)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedPlatform());if("win32"===c.platform())return void(0,m.logToUser)(g.UserErrorLogs.EsbuildUnsupportedWindows());const r=e?.hudKey??process.env.HUD_KEY;if(!r)return void(0,m.logToUser)(g.UserErrorLogs.EsbuildMissingKey());const o=e?.includeModules??(0,p.getModulesToTraceFromEnv)()??[],n=(0,u.createCheckers)(o);(0,m.logToUser)("started running");const i=t.initialOptions.write??!0;t.initialOptions.write=!1;const a="esm"===t.initialOptions?.format?s.Format.esm:s.Format.cjs,{callback:w,filter:T,tempDir:S}=await async function(e){const t=e.initialOptions;if(!t.plugins)return;const r=t.plugins.findIndex(e=>e.name===O),o=t.plugins[r+1];if(!o||"datadog-esbuild"!==o.name)return;let n;(0,m.logToHud)("datadog-esbuild plugin detected");const i={...e,onLoad:(...e)=>{n=e},onStart:()=>{},onEnd:()=>{},onResolve:()=>{},onDispose:()=>{}};if(o.setup(i),!n)return void(0,m.logToHud)("datadog-esbuild plugin detected but failed receive onLoad callback");const a=f.join(c.tmpdir(),`hud-${(0,l.randomUUID)()}`);try{return await d.promises.access(a),void(0,m.logToUser)("temp dir already exists, try rerunning the build.")}catch{}return(0,m.logToHud)(`creating temp dir to be used by datadog plugin.\n\tPath: ${a}`),await d.promises.mkdir(a,{recursive:!0}),{filter:n[0].filter,callback:n[1],tempDir:a}}(t)??{},$=new Set(t.initialOptions.external||[]),U=new Map;t.onResolve({filter:/.*/},async e=>{if(e.pluginData?.hud?.calledFromHud)return;if($.has(e.path))return;const r=p.hudConfig.frameworksToPatch.get(e.path);if(!r)return;if(!r.enable||!r.enableEsbuild)return;const o={...e};delete o.path;const n=await t.resolve(e.path,{...o,pluginData:{...e.pluginData,hud:{calledFromHud:!0}}}),i=await _(n.path);i&&(U.set(i,e.path),(0,m.logToHud)(`mapping framework: ${i} => ${e.path}`))}),t.onLoad({filter:/.*\.(js|ts|cjs)$/},async e=>{try{const t=w?async t=>await w({...e,path:t}):void 0;if((0,u.skip)(e.path,n)){const r=await(0,h.getFrameworkContentSuffix)(e.path,U);if(!r)return;let o=await d.promises.readFile(e.path,"utf8");return o=await v(e.path,o,t,T,S)??o,o+=r,{contents:o,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}let r=await d.promises.readFile(e.path,"utf8");return r=(0,b.markFile)(e.path,r),r=await v(e.path,r,t,T,S)??r,r+=await(0,h.getFrameworkContentSuffix)(e.path,U)??"",{contents:r,loader:e.path.endsWith("ts")?"ts":"js",resolveDir:f.dirname(e.path)}}catch(t){return(0,m.logToHud)(`failed patching file "${e.path}", fallbacking to original loader. Error: ${t}`),void(0,m.logToUser)(`failed patching file "${e.path}", fallbacking to original loader`)}}),t.onEnd(async e=>{if(!e?.outputFiles)return;let t;try{t=await(0,b.verifyAndMarkFinalFiles)(e.outputFiles,i,a),(0,m.logToUser)("finished")}catch(e){throw(0,m.logToHud)(`failed validating. Error: ${e}`),(0,m.logToUser)(g.UserErrorLogs.EsbuildFailedBundling()),e}finally{if(t)try{await(0,y.uploadAllSourceMaps)(t,r)}catch(e){(0,m.logToHud)(`failed uploading source maps. Shouldnt get here since we catch all errors in verifyAndMarkFinalFiles, error: ${e}`)}try{if(S)try{await d.promises.access(S),(0,m.logToHud)("cleaning temp dir"),await d.promises.rm(S,{recursive:!0,force:!0})}catch{}}catch(e){(0,m.logToHud)(`failed cleaning temp dir. Error: ${e}`)}try{!process.env.HUD_SKIP_BUILD_LOG_EXPORT&&(0,m.getShouldSendLogs)()&&await(0,m.exportBuildLogs)(r)}catch(e){"true"===process.env.HUD_PLUGIN_VERBOSE&&"true"===process.env.HUD_DEBUG&&(0,m.logToUser)(`Failed exporting build logs. Error: ${e}`)}}})}})},8528:e=>{e.exports=require("./dto")},8938:e=>{e.exports=require("axios")},9154:e=>{e.exports=require("vm")},9896:e=>{e.exports=require("fs")},9929:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFrameworkContentSuffix=async function(e,t){const r=[...t.entries()].find(([t,r])=>e.startsWith(t));if(!r)return;const[u,l]=r;let d=l+e.slice(u.length);(d.endsWith("index.js")||d.endsWith("index.ts"))&&(d=d.slice(0,d.length-9));const c=o.hudConfig.frameworksToPatch.get(d);if(!(c?.enable&&c?.enableEsbuild&&c?.patcher&&c?.version))return;(0,s.logToHud)(`Patching framwork: ${d}`);const f=await(0,a.getModuleRoot)(e);if(!f)return void(0,s.logToHud)(`Failed to find package.json for ${d}`);const p=(0,i.extractModuleVersion)(f);if((0,s.logToHud)(`Patching framework ${d}, version: ${p}`),(0,i.getFrameworkPatcher)(c.patcher).isSupported(f,d,c.version,c.extraInfo))return`\n ;\n try {\n const { hudRITM, infoSafeLog: hudSafeLogger } = require("hud-sdk/instrument");\n if (globalThis.hudRunningMode === ${n.HudRunningMode.enabled}) {\n if (typeof hudRITM === "function") {\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger("esbuild patching ${d}");\n }\n module.exports = hudRITM(module.exports, "${d}", "hud-esbuild-folder-should-not-exists");\n }\n }\n } catch (e) {\n try {\n const { errorSafeLog: hudSafeLogger } = require("hud-sdk/internal");\n if (typeof hudSafeLogger === "function") {\n hudSafeLogger(\`esbuild patching ${f} failed: \${e}\`);\n }\n } catch {}\n }\n `;(0,s.logToHud)(`Failed to patch ${d}, unsupported version: ${p}`)};const o=r(5809),n=r(8528),i=r(2030),a=r(7085),s=r(5231)}},t={};return function r(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o].call(i.exports,i,i.exports,r),i.exports}(7085)})());
2
2
  //# sourceMappingURL=esbuildPlugin.js.map