UNPKG

hud-sdk

Version:

Hud's Node SDK

2 lines 12 kB
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var o=t();for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(global,()=>(()=>{"use strict";var e={523:e=>{e.exports=require("./logger")},1244:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.withHud=i;const a=r(o(6760));function i(e,t){const r=e=>{const r=e.webpack;return{...e,webpack:(a,i)=>(r&&(a=r(a,i)),function(e,t,r){const{dev:a,isServer:i,nextRuntime:s}=t;if(a||!i||"edge"===s)return e;const{logger:n}=o(5449),{hudWebpackPlugin:u}=o(9017),l=e.devtool&&("source-map"===e.devtool||"inline-source-map"===e.devtool||"nosources-source-map"===e.devtool);return!l&&r.accessToken&&(n.debug("No source maps detected, temporarily enabling source-map"),e.devtool="source-map"),e.plugins=e.plugins||[],e.plugins.push(...u({...r,projectDir:t.dir,initFilePath:r.initFilePath,cleanupTempSourceMaps:!l})),e.module||(e.module={}),e.module.rules||(e.module.rules=[]),e.module.rules.unshift({test:/\.[jt]sx?$/,enforce:"pre",exclude:/node_modules/,loader:"hud-sdk/nextServerLoader"}),e}(a,i,{...t,distDir:e.distDir}))}};if("function"!=typeof e){const t=e;return process.argv.some(e=>"next"===e||e.endsWith(`${a.default.sep}next`))&&process.argv.includes("build")?r(t):t}const i=e;return(e,t,...o)=>{const a="phase-production-build"===e,s=i(e,t,...o);return Promise.resolve(s).then(e=>a?r(e):e)}}t.default=i},1455:e=>{e.exports=require("node:fs/promises")},2305:e=>{e.exports=require("form-data")},2546:e=>{e.exports=require("./lib")},3024:e=>{e.exports=require("node:fs")},3903:e=>{e.exports=require("uuid")},4409:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.tempSourceMapFiles=void 0,t.createSourceMapUploadPlugin=function({accessToken:e,apiEndpoint:o=l.HUD_API_ENDPOINT,cleanupTempSourceMaps:r=!1}){return o.endsWith("/")&&(o=o.slice(0,-1)),async a=>{c.logger.debug("Recieved artifacts",{artifacts:a});const i=a.filter(e=>e.endsWith(".js")||e.endsWith(".mjs")||e.endsWith(".cjs"));if(0===i.length)return c.logger.warn("No build artifacts to upload"),!1;if(c.logger.debug("Uploading build artifacts",{artifacts:i}),r)for(const e of i){const o=`${e}.map`;try{await(0,n.access)(o),t.tempSourceMapFiles.add(o),c.logger.debug("Tracked source map for cleanup",{sourceMapPath:o})}catch{c.logger.debug("Source map doesn't exist, nothing to track",{sourceMapPath:o})}}const l=(await Promise.all(i.map(async t=>{try{const r=await async function(e){let t;try{t=await(0,n.readFile)(e,"utf-8")}catch{return void c.logger.error("Could not read file. File will not be source mapped: ",{uploadFilePath:e})}const o=await async function(e,t){const o=t.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);if(o){const t=f(e,o[1]);if(t)try{return await(0,n.access)(t,s.default.constants.R_OK),t}catch{}}try{const t=`${e}.map`;return await(0,n.access)(t,s.default.constants.R_OK),t}catch{}c.logger.debug("Could not determine source map path - Did you turn on source map generation in your bundler?",{file:e})}(e,t);if(void 0===o)return void c.logger.debug("Could not find source map for artifact. File will not be source mapped: ",{uploadFilePath:e});const r=d(t);if(void 0!==r)return{buildID:r,sourceMapPath:o};c.logger.error("Could not find build ID in artifact. File will not be source mapped: ",{uploadFilePath:e})}(t);if(void 0===r)return;if(c.logger.debug("Uploading source map",{path:r.sourceMapPath,buildID:r.buildID}),await p(r.buildID,r.sourceMapPath,o,e))return c.logger.debug("Source map uploaded successfully",{path:r.sourceMapPath,buildID:r.buildID}),{sourceMapPath:r.sourceMapPath,buildID:r.buildID,sourceFilePath:t}}catch(e){c.logger.error("Error uploading source map",e)}}))).filter(Boolean);if(c.logger.info("Source Map Upload Report"),0===l.length)c.logger.info(" No source maps uploaded");else for(const e of l)e&&c.logger.info(` ${u.default.basename(e.sourceFilePath)} -> ${u.default.basename(e.sourceMapPath)} (build-id: ${e.buildID})`);return l.length>0}},t.cleanupTemporarySourceMaps=async function(){const e=Array.from(t.tempSourceMapFiles);if(t.tempSourceMapFiles.clear(),0===e.length)return;const o=e.map(async e=>{try{await(0,n.unlink)(e)}catch(t){throw c.logger.error("Failed to clean up temporary source map",{filePath:e,error:t}),t}});await Promise.all(o)},t.getBuildIDForArtifact=d,t.resolveSourceMapUrl=f;const a=r(o(8938)),i=r(o(2305)),s=r(o(3024)),n=o(1455),u=r(o(6760)),l=o(8805),c=o(5449);async function p(e,t,o,r,u=!0){const d=new i.default;let f;d.append("build_id",e),d.append("token",r);try{f=await(0,n.readFile)(t,"utf-8")}catch(o){return c.logger.error("Failed to upload source map due file read failure",{error:o,path:t,buildID:e}),!1}try{const e=JSON.parse(f);delete e.sourcesContent,d.append("sourcemap",JSON.stringify(e),{filename:"sourcemap",contentType:"application/json"})}catch(o){c.logger.warn("Failed to parse the sourcemap as JSON",{error:o,path:t,buildID:e}),d.append("sourcemap",s.default.createReadStream(t))}try{await a.default.post(`${o}${l.HUD_API_URI}`,d,{headers:{"Content-Type":"multipart/form-data"},timeout:1e4})}catch(a){const i=a;return 401===i.response?.status?(c.logger.error("Failed to upload source map: Unauthorized. Please check your access token."),!1):(c.logger.error("Failed to upload source map",{error:i.message,status:i.response?.status,path:t,buildID:e}),u?(c.logger.debug("Retrying source map upload"),await new Promise(e=>setTimeout(e,1e3)),p(e,t,o,r,!1)):(c.logger.error("Failed to upload source map: Retries exhausted"),!1))}return!0}function d(e){const t=e.match(`${l.BUILD_ID_VAR_NAME}="([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})"`);return t?t[1]:void 0}function f(e,t){const o=u.default.normalize(t);try{if("file:"===new URL(o).protocol)return o}catch{return u.default.isAbsolute(o)?o:u.default.join(u.default.dirname(e),o)}}t.tempSourceMapFiles=new Set},5449:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0,t.flushLogs=async function(e){try{let o=[];if(e)for(const r of t.logger.transports)if(r instanceof a.WorkerPortTransport){const t=r.getLogs().map(t=>({...t,accessToken:e}));o=o.concat(t)}if(e&&o.length>0)try{await i.default.post(s.HUD_API_LOG_ENDPOINT,{messages:o},{headers:{"x-hudx-plugin":"true","Content-Type":"application/json"}})}catch{}}catch{}};const a=o(523),i=r(o(8938)),s=o(8805);t.logger=function(){const e=[new a.ConsoleTransport({isCustomerLogger:!0,enabled:!0,minLevel:s.USER_CONSOLE_LOG_LEVEL}),new a.WorkerPortTransport({messagesLimit:1e4})];return new a.Logger("hud-bundler-plugin",s.DEFAULT_LOG_LEVEL,e)}()},6760:e=>{e.exports=require("node:path")},6807:e=>{e.exports=require("webpack")},8805:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HUD_API_LOG_ENDPOINT=t.HUD_API_URI=t.HUD_API_ENDPOINT=t.BUILD_ID_VAR_NAME=t.HUD_UUID_NAMESPACE=t.USER_CONSOLE_LOG_LEVEL=t.DEFAULT_LOG_LEVEL=void 0,t.DEFAULT_LOG_LEVEL="info",t.USER_CONSOLE_LOG_LEVEL="error",t.HUD_UUID_NAMESPACE="00c1e90b-af75-4d8e-9935-68485877f759",t.BUILD_ID_VAR_NAME="hudFileBuildID",t.HUD_API_ENDPOINT="https://api-prod.hud.io",t.HUD_API_URI="/sink/sourcemap",t.HUD_API_LOG_ENDPOINT="https://yqp37dddrsewm6wdwwpwfraxqm0shdmx.lambda-url.eu-central-1.on.aws/"},8938:e=>{e.exports=require("axios")},9017:function(e,t,o){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.hudWebpackPlugin=void 0;const a=o(2546),i=o(523),s=o(1455),n=r(o(6760)),u=r(o(9899)),l=o(3903),c=o(8805),p=o(4409),d=o(5449);class f{apply(e){const t=e?.webpack?.BannerPlugin||o(6807).BannerPlugin;e.options.plugins=e.options.plugins||[],e.options.plugins.push(new t({raw:!0,footer:!0,include:/\.(js|ts|jsx|tsx|mjs|cjs|mts|cts)$/,banner:e=>{return t=e?.chunk?.hash?(0,l.v5)(e.chunk.hash,c.HUD_UUID_NAMESPACE):(0,l.v4)(),`;!function(){try{globalThis? globalThis.${c.BUILD_ID_VAR_NAME}="${t}":null}catch(e){}}();`;var t}}))}}class g{upload;constructor(e){this.upload=e}apply(e){e.hooks.afterEmit.tapPromise("hud-webpack-build-id-source-map-upload-plugin",async e=>{try{const t=e.outputOptions.path??n.default.resolve(),o=Object.keys(e.assets).map(e=>n.default.join(t,e));await this.upload(o)?i.customer_logger.logEntry(a.UserLogs.WebpackUploadedSourcemapSuccess()):i.customer_logger.logEntry(a.UserErrorLogs.WebpackFailedUploadingSourcemap())}catch{d.logger.error("Source map upload failed - terminating plugin"),i.customer_logger.logEntry(a.UserErrorLogs.WebpackFailedUploadingSourcemap())}})}}class h{projectDir;initFilePath;distDir;constructor(e,t="hud.ts",o){this.projectDir=e,this.initFilePath=t,this.distDir=o}apply(e){this.projectDir?e.hooks.afterEmit.tapPromise("hud-init-file-copy-plugin",async()=>{try{const e=n.default.join(this.projectDir,this.initFilePath);try{await(0,s.access)(e)}catch{return void d.logger.warn("Init file not found, skipping copy",{sourcePath:e,initFile:this.initFilePath})}const t=this.distDir?n.default.join(this.projectDir,this.distDir):n.default.join(this.projectDir,".next"),o=this.initFilePath.endsWith(".ts")||this.initFilePath.endsWith(".tsx");let r,a;if(o){d.logger.debug("Compiling TypeScript init file",{sourcePath:e,initFile:this.initFilePath});try{r=await async function(e){const t=await(0,s.readFile)(e,"utf-8"),o={target:u.default.ScriptTarget.ES2018,module:u.default.ModuleKind.CommonJS,esModuleInterop:!0,allowSyntheticDefaultImports:!0,skipLibCheck:!0,strict:!1,declaration:!1,sourceMap:!1};return u.default.transpileModule(t,{compilerOptions:o,fileName:e}).outputText}(e),a=n.default.basename(this.initFilePath).replace(/\.tsx?$/,".js")}catch(t){return void d.logger.error("Failed to compile TypeScript init file",{error:t,sourcePath:e,initFile:this.initFilePath})}}else r=await(0,s.readFile)(e,"utf-8"),a=n.default.basename(this.initFilePath);const i=n.default.join(t,a);await(0,s.writeFile)(i,r,"utf-8"),d.logger.info("Successfully copied init file to output directory",{from:e,to:i,initFile:this.initFilePath,compiled:o})}catch(e){d.logger.error("Failed to copy init file",{error:e,initFile:this.initFilePath})}}):d.logger.info("No project directory provided, skipping init file copy")}}class m{cleanupTempSourceMaps;accessToken;constructor(e,t){this.cleanupTempSourceMaps=e,this.accessToken=t}apply(e){this.cleanupTempSourceMaps&&e.hooks.shutdown.tapPromise({name:"hud-webpack-cleanup-plugin",stage:Number.MAX_SAFE_INTEGER},async()=>{try{const e=p.tempSourceMapFiles.size;await(0,p.cleanupTemporarySourceMaps)(),e>0&&d.logger.info(`Cleaned up ${e} temporary source map files`)}catch{d.logger.error("Source map cleanup failed - terminating plugin"),i.customer_logger.logEntry(a.UserErrorLogs.SourceMapCleanupFailed()),await(0,d.flushLogs)(this.accessToken),process.exit(1)}await(0,d.flushLogs)(this.accessToken)})}}t.hudWebpackPlugin=e=>{const t=[],o=d.logger.transports.find(e=>e instanceof i.ConsoleTransport);return o&&e.silent&&(o.enabled=!1),!e.verbose&&e.accessToken||o&&(o.minLevel="info"),e.accessToken||d.logger.info("No access token provided. Source maps and logs will not be uploaded to Hud."),e.accessToken&&(t.push(new f),t.push(new g((0,p.createSourceMapUploadPlugin)({accessToken:e.accessToken,apiEndpoint:e.apiEndpoint,cleanupTempSourceMaps:e.cleanupTempSourceMaps}))),t.push(new m(e.cleanupTempSourceMaps||!1,e.accessToken))),t.push(new h(e.projectDir,e.initFilePath,e.distDir)),t},t.default=t.hudWebpackPlugin},9899:e=>{e.exports=require("typescript")}},t={};return function o(r){var a=t[r];if(void 0!==a)return a.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,o),i.exports}(1244)})()); //# sourceMappingURL=nextjsPlugin.js.map