dt-app
Version:
The Dynatrace App Toolkit is a tool you can use from your command line to create, develop, and deploy apps on your Dynatrace environment.
238 lines (210 loc) • 158 kB
JavaScript
"use strict";var bp=Object.create;var Sn=Object.defineProperty;var vp=Object.getOwnPropertyDescriptor;var wp=Object.getOwnPropertyNames;var Tp=Object.getPrototypeOf,xp=Object.prototype.hasOwnProperty;var Ep=(e,t)=>{for(var n in t)Sn(e,n,{get:t[n],enumerable:!0})},qo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wp(t))!xp.call(e,o)&&o!==n&&Sn(e,o,{get:()=>t[o],enumerable:!(r=vp(t,o))||r.enumerable});return e};var x=(e,t,n)=>(n=e!=null?bp(Tp(e)):{},qo(t||!e||!e.__esModule?Sn(n,"default",{value:e,enumerable:!0}):n,e)),Sp=e=>qo(Sn({},"__esModule",{value:!0}),e);var Od={};Ep(Od,{APP_REGISTRY_BASE_URL:()=>jn,DEFAULT_SSO_CLIENT_ID:()=>Pa,DEFAULT_SSO_URL:()=>Sa,DevServer:()=>Pr,FileMode:()=>bn,OperatingSystem:()=>Zn,RequestOptions:()=>xn,Response:()=>En,_ExecuteFunction:()=>wd,_ExtractDtAppConfigFromTs:()=>Cd,_Fetch:()=>Ed,_GetBearerToken:()=>Td,_GetDtAppFileConfig:()=>xd,_GetSSOUrl:()=>Pd,_InternalPrepareManifest:()=>mr,_Response:()=>Sd,canBeFormatted:()=>Wo,createDtAppConfigBuffer:()=>Vo,createProject:()=>$r,createProjectCommand:()=>pp,executeFunction:()=>sr,extractDtAppConfigFromTs:()=>wt,fetch:()=>zo,getAvailableEmbeddedTemplates:()=>qc,getBearerToken:()=>U,getCompiledFileName:()=>Kc,getDefaultCliOptions:()=>Je,getDtAppFileConfig:()=>Et,getFilesRecursive:()=>gn,getNormalizedBaseHrefWithSlash:()=>Ct,getPackageManager:()=>Go,getSSOUrl:()=>yt,loadEmbeddedTemplates:()=>Jc,loadTemplates:()=>Qe,mergeOptions:()=>gr,mergeRecursively:()=>be,writeTemplateFiles:()=>_r});module.exports=Sp(Od);var or=require("path"),ir=require("@dynatrace/runtime-simulator");var _=require("path");var Jo={sourcemap:!1,includeVendorSourceMaps:!1},Pp={sourcemap:!0,includeVendorSourceMaps:!0};function ce(e){if(e.sourcemaps===void 0)return e.dev?Pp:Jo;switch(e.sourcemaps){case!0:return{sourcemap:!0,includeVendorSourceMaps:!1};case!1:return{sourcemap:!1,includeVendorSourceMaps:!1};case"all":return{sourcemap:!0,includeVendorSourceMaps:!0};default:return Jo}}var oe=require("path");function tt(e,t){let n=oe.posix.normalize(oe.posix.join(t.split(oe.win32.sep).join(oe.posix.sep),"/")),r=new RegExp(`^.*?${n}`,"g"),o=oe.posix.parse(e.split(oe.win32.sep).join(oe.posix.sep).replace(r,""));return new URL("http://localhost"+oe.posix.normalize(oe.posix.join("/",o.dir,o.name.replace(/\.function$/,"")))).pathname}var Mt=require("path");var rt=require("path");var Ko=require("fs"),Cp="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",pe=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(t.path.endsWith(".js"))return{contents:`${(0,Ko.readFileSync)(t.path,"utf8")}
${Cp}`,loader:"default"}})}});function N(e,t){return require.resolve(e,{paths:[t]})}var It=require("path");var Yo=require("chalk"),Pn=(n=>(n.GENERIC_CLI_ERROR="DEC:D9",n.CONNECTION_ERROR="DEC:DA",n))(Pn||{}),T=(u=>(u[u.POSIX_SIGNAL_BASE=128]="POSIX_SIGNAL_BASE",u[u.UNCAUGHT=256]="UNCAUGHT",u[u.INTERNAL=257]="INTERNAL",u[u.USER=258]="USER",u[u.AUTH=259]="AUTH",u[u.TIMEOUT=260]="TIMEOUT",u[u.COMPILATION=261]="COMPILATION",u[u.NETWORKING=263]="NETWORKING",u[u.VALIDATION=264]="VALIDATION",u[u.BUILD=265]="BUILD",u[u.APP_GATEWAY_COMMUNICATION=266]="APP_GATEWAY_COMMUNICATION",u))(T||{}),Op=`Authentication failed!
Please make sure that:
* The provided client ID and the secret are correct.
* The provided client ID has needed scopes.
Deploy scopes:
* app-engine:apps:run
* app-engine:apps:install
* app-engine:apps:delete
Uninstall scopes:
* app-engine:apps:delete
Telemetry scopes:
* app-engine:apps:run
Development server needs all the scopes specified in the app.config.
For more details on how you can configure authentication, see https://dt-url.net/qw024j8
`;function Hr(e){let t=[e,Op];return new Error(t.filter(Boolean).join(`
`),{cause:259})}function Xo(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes(It.sep)?`${t.split(It.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function Oe(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map((t,n)=>n===0&&t.toLocaleLowerCase()==="error:"?"":t).map(t=>t.includes("http")||t.includes("://")?"":t).map(t=>t.includes(It.sep)?`${t.replace(/["']/g,"").split(It.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function A(e){return e instanceof Error?e:new Error(String(e))}function Zo(e,t){throw new Error(`ERROR [${(0,Yo.green)(t)}]: ${e.message}`)}var nt=require("path"),On=require("fs");var Qo=require("path");var Vr;function Te(e){return Vr||(Vr=require(N("typescript",e))),Vr}function xe(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,Qo.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function ei(e,t){let n=Te(t),r=`TS${e.code}`,o=n.flattenDiagnosticMessageText(e.messageText,`
`),i=e.category===n.DiagnosticCategory.Error?"Error":"Warning";if(e.file){let{line:s,character:a}=n.getLineAndCharacterOfPosition(e.file,e.start);return{code:r,category:i,text:o,filePath:e.file.fileName,column:a+1,line:s+1}}return{code:r,category:i,text:o,filePath:void 0,line:1,column:1}}var Cn=require("path");function B(){if(__filename.endsWith("bin.js"))return(0,Cn.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Cn.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Cn.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var ti=require("fast-glob"),ni=require("path");function v(e,t){let r=(Array.isArray(e)?e:e.split(/[\/\\]/g)).map(o=>o?o.replace(/\\/g,"/"):"").join("/").replace(/\/\.\//g,"/").replace(/(?<!:)\/{2,}/g,"/").replace(/^.\//,"");return t?.keepFullPath?r:r.replace(/^([a-zA-Z]):/,"")}async function ri(e,t){let n=Te(e),r=(0,ti.sync)(v([e,t.input,t.glob]));return n.createProgram(r,{}).getSourceFiles().map(i=>(0,ni.relative)(e,i.fileName)).filter(i=>!i.includes("node_modules"))}function Rn(e){return e.map(Rp).filter(t=>!t.filePath?.includes("node_modules/"))}var oi=e=>xe(e,"Error"),Rp=e=>xe(e,"Warning");async function ii(e,t){let n=e.build.functions,o=(await ri(e.root,n)).length>0,i=(0,On.existsSync)((0,nt.join)(e.root,t));if(o&&!i)throw new Error(`Failed to build functions
${(0,nt.join)(n.input,n.tsconfig)} must exist, if function source files are present in the ${n.input} directory.
Please create a tsconfig.json file in the ${n.input} directory, or delete the directory.
Example ${(0,nt.join)(n.input,"tsconfig.json")}
${(0,On.readFileSync)((0,nt.join)(B(),"function/template/tsconfig.json"),"utf-8")}:
`,{cause:265});if(!o&&i)throw new Error(`Failed to build functions
${(0,nt.join)(n.input,n.tsconfig)} exists, but no functions were found in the ${n.input} directory.
Please create a function in the ${n.input} directory, or delete the directory.
You can create functions with the generate command:
$ yarn generate:function
`,{cause:265})}function le(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}async function si(e,t,n){let r=require(N("esbuild",t.cwd));if(!r.context)throw new Error(`esbuild context function not found. This is likely happening because you may have dependencies in your project that are installing an older version of esbuild. Please fix your dependencies and try again. ${r.version?`Your current esbuild version being used is ${r.version}.`:""}`,{cause:258});let{context:o}=r,i=t.sourcemapOptions?.sourcemap??!1;i&&!t.sourcemapOptions?.includeVendorSourceMaps&&(t.plugins=[...t.plugins??[],pe()]);let s=await o({...le(),entryPoints:t.entryPoints.map(c=>(0,rt.isAbsolute)(c)?c:(0,rt.join)(t.cwd,c)),outbase:t.outbase,target:t.target,minify:t.minify??!1,sourcemap:i,platform:t.platform||"browser",plugins:t.plugins||[],external:t.external||[],sourceRoot:t.sourceRoot,tsconfig:(0,rt.isAbsolute)(t.tsconfig)?t.tsconfig:(0,rt.join)(t.cwd,t.tsconfig),outdir:e,format:t.format,globalName:t.globalName,metafile:t.metafile,write:!1,define:t.define});n?.addEventListener("abort",()=>s.cancel());let a=s.rebuild();try{return await a}finally{s.dispose()}}async function An(e,t){let n=Date.now();try{let r=(0,Mt.join)(e.cwd,"dist"),o=await si(r,e,t),i=Date.now(),s=o.warnings.map(l=>xe(l,"Warning")).filter(l=>!l.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:o.outputFiles.reduce((l,d)=>{let u=`${Mt.sep}${(0,Mt.join)(a,d.path.replace(r,""))}`;return{...l,[u]:{content:Buffer.from(d.contents)}}},{}),diagnostics:s,duration:i-n,metafile:o.metafile}}catch(r){let o=Date.now();if(Ap(r)){let s=[...r.errors.map(a=>xe(a,"Error")),...r.warnings.map(a=>xe(a,"Warning")).filter(a=>!a.filePath?.includes("node_modules/"))];return{fileMap:{},diagnostics:s,duration:o-n}}throw r instanceof Error?r:new Error(String(r),{cause:261})}}function Ap(e){return typeof e=="object"&&typeof e?.errors<"u"}var ns=require("fs"),Ae=x(require("fast-glob")),me=require("path");var In=x(require("fs"));var ot=require("undici");async function E(e,t){return(0,ot.fetch)(e,t)}var Mn=require("path");var ai=x(require("path"));function it(){return ai.default.resolve(B(),"utils","snippets")}var ci=x(require("fastify")),Gr=require("fs"),pi=x(require("ws"));function li(e){let t={};e.https&&(t={https:{cert:(0,Gr.readFileSync)(e.https.cert),key:(0,Gr.readFileSync)(e.https.key)}});let n=(0,ci.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(r,o,i)=>{i(null,o)}),n}function ui({server:e}){return new pi.default.Server({server:e})}function di(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}var Fn=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function mi(e){if(!Fn)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Fn}-${e}.${t}`}var _t=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function fi(e){if(!_t)return;let t=new URL(_t).hostname;return`${e}-${t}`}var zr=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,ie=_t||Fn||zr;function Me(e){if(ie)return zr?zr.replace(/^https?:\/\//,""):_t?fi(e):mi(e)}function kn(e){let t=Me(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}function gi(){let e=(0,Mn.resolve)(it(),"defaultIndex.snippet.html");return In.default.readFileSync(e).toString("utf-8")}function st(e,t){let{transformSync:n}=require(N("esbuild",t)),r=(0,Mn.resolve)(it(),"sdkWebShim.snippet.ts"),o=In.default.readFileSync(r,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(o,i).code}function hi(e){let t=(0,Mn.resolve)(it(),"selfmon_config.snippet.js");return In.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var Dn;async function _n(e){return Dn||(Dn=await(await E(e)).text(),Dn)}function at(e){let t=kn(e.server.port),n=di(e.server);return`window.socketUrl = '${t===""?n:t}';`}var yi=x(require("chalk"));var Dp=/(?<=(?:\||")cuc=).*?(?=\||")/g,qr;function bi(e){let t;qr?t=qr:(t=Dp.exec(e),qr=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${yi.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function vi(e){try{if(!e.includes("http"))return 3;let t=await E(e),n=t.status,o=t.headers.get("content-type")?.includes("javascript"),s=(await t.text()).includes("cuc=");return n===404||!o||!s?2:(await _n(e),0)}catch{return 1}}var W=require("chalk"),pt=require("lodash");var z=require("fs"),Ti=require("fs/promises"),Un=require("path"),Ip=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),wi=e=>(e>9?"":"0")+e,Mp=e=>`${e.getFullYear()}-${wi(e.getMonth()+1)}-${wi(e.getDate())}_log.txt`,_p=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},Jr=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},Kr=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,Un.join)(t,".dt-app/logs"),(0,z.existsSync)(this.logFolder)||(0,z.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,Un.join)(this.logFolder,Mp(new Date)),!(0,z.existsSync)(this.logFile)){let t=(0,z.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>Ip.test(n));if(t.length>=10){let n=t.map(r=>({path:r,date:_p(r)})).filter(r=>r.date).sort((r,o)=>r.date.getTime()-o.date.getTime())[0].path;(0,Ti.unlink)((0,Un.join)(this.logFolder,n))}(0,z.closeSync)((0,z.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,z.createWriteStream)(this.logFile,{encoding:"utf-8",flags:"a"}),this.stream.on("open",()=>t())})}write(t){this.stream&&this.stream.write(t)}getLogFile(){return this.logFile}};async function xi(e){return $n=new Kr,$n.setup(e)}var $n=new Jr;var Pi=require("os");var Zr=x(require("ora"));var Yr=[],ct=!1;function Up(e){return new Promise((t,n)=>{Yr.push(async()=>{try{let r=await e();t(r)}catch(r){n(r)}}),$p()})}async function $p(){if(!ct){for(ct=!0;Yr.length>0;)await Yr.shift()();ct=!1}}async function Nn(e){return Up(e)}var Nt=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",Ut={interval:80},Ee=[],_e="idle",Bt=(0,Zr.default)({spinner:{frames:[""],interval:Ut.interval},isSilent:!Nt}),Np=()=>`
${Ee.map(e=>e.getFrame()).join(`
`)}`;function Bp(){Bt.text=Np()}var $t;function jp(){Nt&&_e!=="running"&&!ct&&($t===void 0&&($t=setInterval(Bp,Ut.interval)),Bt.start(),_e="running")}function Ei(){_e==="running"&&(_e="paused",Bt.stop())}function Si(){_e==="paused"&&!ct&&(_e="running",Bt.start())}function Xr(){_e="idle",Bt.stop(),Ee.forEach(e=>e.abort()),$t!==void 0&&(clearInterval($t),$t=void 0)}var Bn=class{spinner;constructor(t){this.spinner=(0,Zr.default)({...t,isSilent:!Nt})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=Ee.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),Ee.splice(t,1)),Ee.length===0&&Xr()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),Ee.includes(this)||Ee.push(this),jp(),this}_stop(t,n="abort"){switch(this.text=t??this.text,Ei(),n){case"success":this.spinner.succeed(this.text);break;case"info":this.spinner.info(this.text);break;case"fail":this.spinner.fail(this.text);break;case"warn":this.spinner.warn(this.text);break;case"abort":this.spinner.stop();break;default:this.spinner.stopAndPersist(n)}return this.cleanup(),Si(),this}stop(t,n={}){return this._stop(t,n)}abort(){return this._stop(void 0,"abort")}info(t){return this._stop(t,"info")}succeed(t){return this._stop(t,"success")}fail(t){return this._stop(t,"fail")}warn(t){return this._stop(t,"warn")}},ue={create:(e={})=>new Bn({...e,interval:Ut.interval}),start:(e,t={})=>new Bn({...t,interval:Ut.interval}).start(e),pause:Ei,resume:Si,reset:Xr,successAll:e=>Ee.forEach(t=>t.succeed(e)),failAll:e=>Ee.forEach(t=>t.fail(e)),disable:()=>{Nt=!1,Xr()},enable:()=>{Nt=!0},getInterval:()=>Ut.interval,_getMockedSpinner:function(e){let t={abort:(...n)=>t,fail:(...n)=>t,info:(...n)=>t,start:(...n)=>t,stop:(...n)=>t,succeed:(...n)=>t,text:e??"",warn:(...n)=>t};return t}};var Ci=`Using 0.0.0.0 as host will expose the dev server to your internal network!
Use 0.0.0.0 as host only when you want to access the dev server from another machine.
Remove "host: '0.0.0.0'" if this behavior is not explicitly wanted.`;var Qr=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>ue.create(),disable:ue.disable,start:t=>ue.start(t),pause:ue.pause,resume:ue.resume,abort:ue.reset};disable(){this.disabled=!0,ue.disable()}log(t){this._log(`${this._padString(t,1)}`,"INFO")}debug(t,n){global.VERBOSE_MODE&&n.startsWith(global.VERBOSE_MODE.replace("%",""))&&(this.spinner.pause(),console.log(`${(0,W.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ue.getInterval())),this._printToFile(`[${n}] ${t}`,"DEBUG")}info(t,n){this._log(n===void 0||n?this._padString(t,0):t,"INFO")}success(t){this._log((0,W.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,W.red)(this._padString(t,0)),"ERROR")}warn(t){let n=`
${(0,W.yellow)("Warning "+(0,pt.repeat)("─",this.warningBoxSize-8))}
${(0,W.yellow)(this._padString(t))}
${(0,W.yellow)((0,pt.repeat)("─",this.warningBoxSize))}
`;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=`
${(0,W.magenta)((0,pt.repeat)("─",this.boxSize))}
${(0,W.magenta)(this._padString(t))}
${(0,W.magenta)((0,pt.repeat)("─",this.boxSize))}
`;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await xi(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):Nn(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ue.getInterval()),this._printToFile(t,n))}_printToFile(t,n){$n.write(`${Wp().toISOString()} ${n} ${Lp(t)}
`)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(r=>`${(0,pt.repeat)(" ",n)}${r}`).join(Pi.EOL)}};function Lp(e){let t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return e.replace(new RegExp(t,"g"),"")}function Wp(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var p=new Qr;var q=x(require("chalk"));var de={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function eo(e,t){t&&console.log(`${e}
`),console.log(q.default.hex(de.green).bold(`${e}
`))}function jt(e){if(e){console.log(`════════
`);return}console.log(q.default.hex(de.blue).bold("══")+q.default.hex(de.limeGreen).bold("══")+q.default.hex(de.green).bold("══")+q.default.hex(de.purple).bold("══")+`
`)}function S(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(H(e,t))}function Ai(e,t="white",n){if(n){console.log(e);return}console.log(H(e,t))}function H(e,t="white"){return{white:q.default.white,blue:q.default.hex(de.blue),green:q.default.hex(de.green),purple:q.default.hex(de.purple),limeGreen:q.default.hex(de.limeGreen),gray:q.default.dim}[t](e)}function lt(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+`
`);return}console.log(q.default.hex(de.blue)("─".repeat(n))+`
`)}function D(){console.log(`
`)}function Ue(e,t=""){let n=(r,o="")=>{let i="│ ",s="├─ ",a="└─ ",c="";return r.items?.forEach((l,d)=>{let u=d===r.items.length-1,m=u?a:s,f=u?" ":i;c+=`${o}${m}${l.name}
`,l.items?.length&&(c+=n(l,o+f))}),c};console.log(n(e,t))}function Fi(){console.log("")}function Lt(e,t,n,r=!0){let o={};e.forEach(s=>{let c=s.split("/")[0];o[c]||(o[c]=[]),o[c].push(s)});let i={items:[]};return Object.keys(o).forEach(s=>{let a={name:s,items:[]};o[s].forEach(c=>{let l=c.split("/");if(l.shift(),l.length!==0)if(l.length===1){let d=l[0];a.items.push(d.endsWith("widget.tsx")?Oi(d,t,n,r):Ri(d,t,n))}else{let d=a;for(let m=0;m<l.length-1;m++){let f=l[m],g=d.items.find(y=>y.name===f&&Array.isArray(y.items));g||(g={name:f,items:[]},d.items.push(g)),d=g}let u=l[l.length-1];d.items.push(u.endsWith("widget.tsx")?Oi(u,t,n,r):Ri(u,t,n))}}),i.items.push(a)}),i}function Oi(e,t,n,r){let o=[{name:`Local: ${t[e+"_local"]}`}];return r&&o.push({name:`Environment: ${t[e+"_environment"]}`}),{name:n[e],items:o}}function Ri(e,t,n){return{name:`${n[e]}: ${t[e]}`}}var io=x(require("chalk")),se=require("path"),zt=require("fs/promises");function Se(e){return e.startsWith("../")?e:e.startsWith("./")?e.slice(1):e.startsWith("/")?e:"/"+e}var Le=require("@dynatrace/openkit-js"),zi=require("lodash"),dt=require("fs"),Vn=require("fs/promises"),qi=x(require("http")),Ji=x(require("https")),Re=require("os"),ro=require("path"),Ht=require("url");var ki=require("child_process"),Hp=require("commander");function V(e,t){let r={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((o,i)=>{(0,ki.exec)(e,r,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):o(a)})})}var jn="/platform/app-engine/registry/v1";function Vp(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(`
`),{cause:266})}async function Ln(e,t){try{let n=new URL(e),r={headers:{authorization:`Bearer ${t}`,"content-type":"application/octet-stream"}};n.pathname="/platform/metadata/v1/user";let o=await E(n.toString(),r);return!o.ok||o.headers.get("content-type")?.includes("text/html")?void 0:await o.json()}catch(n){throw Vp(A(n).message)}}async function Di(e,t){let n=await E(`${e}/platform/app-engine/registry/v1/app.default.csp.json`,{headers:{authorization:`Bearer ${t}`}});return n.status>=200&&n.status<=299?(await n.json()).policyDirectives:(p.warn(`The default csp policy from the platform couldn't be applied. App-registry failed with: ${n.status} ${n.statusText}`),{})}function $e(e){let t=new URL(e),[n,...r]=t.hostname.split(".");if(!r||r.length<1)throw new Error(`Invalid environment URL: "${e}"`,{cause:258});return{tenant:n,hostname:r.join(".")}}async function Gp(e,t,n,r){let o=await Di(e,n),i=[3e3,3001,3002,3003,3004,3005,3e4,30001,30002,30003,30004,30005],s=i.flatMap(g=>ie?[`https://${Me(g)}`]:[`http://localhost:${g}`,`https://localhost:${g}`]),a=i.flatMap(g=>ie?[kn(g)]:[`ws://localhost:${g}`,`wss://localhost:${g}`]),c={"script-src":["'unsafe-eval'",...s,...t.map(g=>`'sha256-${g}'`)],"connect-src":[...s,...a],"frame-ancestors":s},{tenant:l,hostname:d}=$e(e),u=g=>g.replaceAll("{tenantId}",l).replaceAll("{hostname}",d),m={},f=[...Object.keys(o),...Object.keys(c)];for(let g of f){let y=new Set;for(let b of o[g]??[])y.add(u(b));for(let b of c[g]??[])y.add(u(b));m[g]=Array.from(y)}return m["frame-src"]=["*"],m["frame-ancestors"]=["*"],r&&Object.entries(r).forEach(([g,y])=>{m[g]?m[g].push(...y.map(b=>b.value)):m[g]=y.map(b=>b.value)}),zp(m)}function zp(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var Ii=new Map;async function Mi(e,t,n,r){let o=`${e}-${t.join(",")}-${r}`,i=Ii.get(o);if(i)return i;let s=await Gp(e,t,n,r);return Ii.set(o,s),s}var ut=require("fs");function K(e){if(!(0,ut.existsSync)(e)&&!(0,ut.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,ut.readFileSync)(e,"utf-8");return JSON.parse(t)}var Ki=require("jsonwebtoken");var _i=require("path"),Ui=require("os"),Be=require("fs"),Wt=require("fs/promises");var Ne=(0,_i.join)((0,Ui.homedir)(),".dt-app",".session"),qp=19;function $i(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function to(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ni(n)]))}function Ni(e){return e==null?e:Array.isArray(e)?e.map(t=>Ni(t)):typeof e=="object"?to(e):typeof e=="string"?Oe(e):e}function Bi(){return Math.floor(Math.random()*Math.pow(10,18))}function Jp(e){return e!==""&&e.length<=qp&&Number.isInteger(Number(e))}function ji(){try{if(!(0,Be.existsSync)(Ne))return;let e=(0,Be.statSync)(Ne).birthtime;Kp(e)&&(0,Be.unlinkSync)(Ne)}catch{p?.debug("Could not identify user uniquely",O)}}function Kp(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function Li(e){try{if((0,Be.existsSync)(Ne)){let n=(await(0,Wt.readFile)(Ne)).toString();Jp(n)?e=Number(n):await(0,Wt.writeFile)(Ne,e.toString())}else await(0,Wt.writeFile)(Ne,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function Wi(e){let t=K(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return Ln(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function Hi(e){return e.reduce((t,n,r,o)=>{if(n.startsWith("--")){let i=n.slice(2),s=o[r+1];s&&!s.startsWith("--")?t[i]=Oe(s):t[i]=!0}return t},{})}function Vi(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function Gi(e){if(!e)return"";let t;if(typeof e=="string")t=e;else{if(!e.userId)return"";t=e.emailAddress}if(!t)return"";let n=`@${t.split("@")[1]}`;return n==="@heimdall.dynatrace.com"?"heimdall":n==="@dynatrace.com"||n==="@ruxitlabs.com"?"internal":"external"}var no=(0,ro.join)((0,Re.homedir)(),".dt-app",".uuid"),O="TELEMETRY",Yp=36,Wn=process.env.NODE_ENV==="test";var Vt,j,Gt,Hn,oo=!1,je;function Xp(e,t){p?.debug("Creating a new HTTP and HTTPS interceptor for tracing",O),[qi.default,Ji.default].forEach(r=>{let o=r.request;r.request=function(){let i;try{arguments[0]instanceof Ht.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new Ht.URL(arguments[0]):i=new Ht.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return o.apply(null,arguments)}for(let l of t)if(l.startsWith(i.origin))return o.apply(null,arguments);p?.debug(`Tracing request ${i.toString()}`,O);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof Ht.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[Le.webRequestTagHeader]=s.getTag(),s.start();let c=o.apply(null,arguments);return c.once("response",l=>{s.stop(l.statusCode)}),c}})}async function Yi(e){if(Wn){p?.debug("Telemetry disabled",O);return}let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,dt.readFileSync)((0,ro.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(ji(),Gt=await Li(Bi()),Vt=new Le.OpenKitBuilder(t.beaconEndpoint,t.applicationId,Gt).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,Re.platform)()).withLogLevel(global.VERBOSE_MODE?Le.LogLevel.Info:Le.LogLevel.Error).build(),await new Promise(r=>{Vt.waitForInit(o=>{o&&(j=Vt.createSession(),oo=!0,Xp(j,[t.beaconEndpoint])),r(o)},3e4)})){p?.debug("Successfully initialized OpenKit",O),p?.debug(`Telemetry enabled: Session ID "${Gt}"`,O),je={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let r="";if((0,dt.existsSync)(no)){let i=(await(0,Vn.readFile)(no)).toString();if(i.length===Yp&&(Hn=i,j.identifyUser(i),p?.debug("Identification successful",O)),e?.oauth2File&&(0,dt.existsSync)(e?.oauth2File)){let s=K(e.oauth2File),a=s?.app_token?.access_token||s?.toolkit_token?.access_token;if(a){let{email:c}=(0,Ki.decode)(a);r=c}}}else if(e?.oauth2File&&(0,dt.existsSync)(e.oauth2File)){let o=await Wi(e.oauth2File);o?.userId&&(Hn=o.userId,r=o.emailAddress,j.identifyUser(o.userId),(0,Vn.writeFile)(no,o.userId),p.debug("Created uuid file to identify user uniquely",O))}je={...je,userType:Gi(r)}}catch{p?.debug("Could not identify user uniquely",O)}}else p?.debug("Failed to initialize OpenKit, disabling telemetry",O)}async function Xi(e){if(!j)return;let t=j.enterAction(e);if(process.version.charAt(0)==="v"?t.reportValue("nodejs_version",process.version.substring(1)):t.reportValue("nodejs_version",process.version),t.reportValue("cli_version",global.DT_APP_VERSION),t.reportValue("operating_system",(0,Re.platform)()),t.reportValue("operating_system_version",(0,Re.version)()),Wn)t.reportValue("yarn_version","test");else try{let n=await V("yarn --version");t.reportValue("yarn_version",n)}catch{}if(Wn)t.reportValue("npm_version","test");else try{let n=await V("npm --version");t.reportValue("npm_version",n.replace(`
`,""))}catch{}if(Wn)t.reportValue("git_version","test");else try{let n=await V("git version");t.reportValue("git_version",n.replace("git version ",""))}catch{}return t}async function Zi(e,t){if(e)try{Object.entries(t)?.forEach(n=>{e.reportValue(`command_arg_${(0,zi.snakeCase)(n[0])}`,Oe(JSON.stringify(n[1])))})}catch{p?.debug("Could not report command args",O)}}function L(e,t){if(!oo||!j||!Gt)return;let n=to($i(e.payload||{})),r=t?.environmentUrl||je?.environmentUrl||"",o=t?.app?.id||je.appId||"",i=t?.app?.version||je.appVersion||"",s=process.version.charAt(0)==="v"?process.version.substring(1):process.version,a=r?{tenantId:$e(r).tenant,sessionType:Vi(r)}:{tenantId:"",sessionType:""},c={...Hn&&{userId:Hn},userType:je.userType||""},l={sessionId:Gt.toString(),"event.type":`dt-app.${e["event.category"]}.${e.name}`,"event.category":e["event.category"],"event.provider":"dt-app",operatingSystemVersion:(0,Re.version)(),nodejsVersion:s,appId:o,appVersion:i,cliVersion:global.DT_APP_VERSION,...a,...c,...n};j.sendBizEvent(l["event.type"],l)}async function We(){if(Vt)return p?.debug("Closing OpenKit connection",O),new Promise(e=>{Vt.shutdown(()=>{p?.debug("Successfully closed OpenKit connection",O),e()}),oo=!1})}var es=x(require("fast-glob")),ts=require("fs"),Qi={created:io.default.green`CREATED:`,updated:"UPDATED:",deleted:io.default.red`DELETED:`,copied:"COPIED:"};function He(e){let t={},n={fileExists:r,throwIfFileDoesNotExist:o,getFile:i,getFilePathsByRegex:s,getFileMap:a,getFileName:c,setFile:l,setFiles:d,mapEsbuildOutputFiles:u,deleteFile:m,writeFileToDisc:f,writeFileMapToDisc:g,addAssetFiles:y,resetFileMap:b};return e&&d(e),n;function r(h){let w=Se(h);return!!t[w]}function o(h){let w=Se(h);if(!r(h))throw L({"event.category":"crash",name:"fileManager.setFile",payload:{error:`Failed to set file ${h} with fileManager.`}}),new Error(`File ${w} does not exist in fileMap!`)}function i(h){return h=Se(v(h)),o(h),t[h]}function s(h){return Object.keys(t).filter(w=>w.match(h))}function a(){return t}function c(h){return h=Se(v(h)),o(h),(0,se.basename)(h)}function l(h,w){h=Se(v(h)),t[h]={content:w}}function d(h){for(let w in h)l(w,h[w].content)}function u(h,w,k="dist"){let ne=v([w,"dist"]);return(h||[]).forEach(we=>{let re=v(we.path),jr=v([k,re.replace(ne,"")]),Lr=Se(jr);t[Lr]={content:Buffer.from(we.contents)}}),n}function m(h){h=Se(v(h)),delete t[h]}async function f(h){h=Se(v(h)),o(h),await(0,zt.writeFile)((0,se.join)(h),t[h].content)}async function g(h){await Promise.all(Object.entries(t).map(async([w,{content:k,mode:ne}])=>{let we=(Buffer.byteLength(k,"utf8")/Math.pow(2,10)).toFixed(2),re=(0,se.join)(h,w);return p.debug(`${ne!==void 0?Qi[ne]:Qi.created} ${re} ${`(${we} KB)`}`,"FILES"),await(0,zt.mkdir)((0,se.dirname)(re),{recursive:!0}),(0,zt.writeFile)(re,k)}))}async function y(h){for(let w of h.assetConfigs){let k=(0,se.isAbsolute)(w.input)?w.input:(0,se.join)(h.root,w.input),ne=await(0,es.default)(w.glob,{cwd:k,dot:!0,ignore:w.ignore});for(let we of ne){let re=v([h.distDir,w.output,we]);l(re,(0,ts.readFileSync)((0,se.join)(k,we)))}}}function b(){t={}}}var M=He();var zn="documents",rs="document-types";async function qn(e,t,n,r){let o=await _n(t);if(!r.startsWith("dynatrace.")){let i;try{i=bi(o)}catch(l){let d=l instanceof Error?l.message:String(l);p.error(d);return}let s=hi(i),a="./assets/agentConfig.js",c=v([n,a]);M.setFile(c,Buffer.from(s)),e.injectScript(a)}e.injectScript(t)}function Pe(e){return(0,ns.existsSync)((0,me.join)(e.cwd,e.functionsFolder))?(0,Ae.sync)(v([e.functionsFolder,e.glob]),{cwd:e.cwd}):[]}function os(e){let t=Pe({cwd:e.cwd,functionsFolder:e.functionsDir,glob:e.glob});if(!t.length)return;S("Available app functions served from '/api':","green"),D();let n={};t.forEach(i=>{n[i.split("/")[i.split("/").length-1]]=H(e.url+v(["/api",tt(i,e.functionsDir)]),"gray")});let r=Jn(t,e.cwd),o=Lt(t,n,r);Ue(o)}async function is(e){let t=await(0,Ae.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,Ae.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;S("Available workflow actions:","green"),D();let r=Jn([...n,...t],e.cwd),o=Zp(e,n,t),i=Lt([...n,...t],o,r);Ue(i)}function Zp(e,t,n){let r={};return t.forEach(o=>{let i=Gn(o),s=(0,me.basename)(o,".action.ts");r[i]=H(`${e.url}/api/${s}`,"gray")}),n.forEach(o=>{let i=Gn(o),s=(0,me.basename)(o,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;r[`${i}_local`]=H(a,"gray"),r[`${i}_environment`]=H(Qp(e.environmentUrl,a,e.locationAppIds),"gray")}),r}function Gn(e){let t=e.split("/");return t[t.length-1]}function Qp(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function ft(e,t){return(await(0,Ae.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(r=>(0,me.join)(e,r))}async function ss(e){let t=await(0,Ae.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;S("Available settings widgets:","green"),D();let n={};t.forEach(i=>{let s=Gn(i),a=(0,me.basename)(s,".widget.tsx"),c=`${e.url}/widgets/settings/${a}`;n[`${s}_local`]=H(c,"gray")});let r=Jn(t,e.cwd),o=Lt(t,n,r,!1);Ue(o)}async function as(e){let t=await(0,Ae.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;S("Available documents:","green"),D();let n={};t.forEach(i=>{let s=Gn(i),a=`${e.appId}.${(0,me.basename)(i).split(".")[0]}`;n[s]=H(a,"gray")});let r=Jn(t,e.cwd),o=Lt(t,n,r);Ue(o)}function Jn(e,t){let n={};return e.forEach(r=>{let o=(0,me.basename)(r);n[o]=el((0,me.join)(t,r),o)}),n}function el(e,t){return process.platform==="win32"&&(e="/"+e.replace(/\\/g,"/").replace(/^\/+/,"")),`\x1B]8;;file://${e.replace(/\\/g,"/")}\x1B\\${t}\x1B]8;;\x1B\\`}var gt=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}});var Yn=require("lodash"),ao=require("micromatch"),ps=require("fs"),Fe=require("path");var Kn={noEmit:!0,skipLibCheck:!0};function cs(e){let{ScriptTarget:t}=Te(e);return{ui:{target:t.ES2021,...Kn},functions:{target:t.ESNext,...Kn},actions:{target:t.ESNext,...Kn},widgets:{target:t.ESNext,...Kn}}}var Xn=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`});function Y(e){let{createCompilerHost:t,createProgram:n}=Te(e.srcRoot),{tsConfigContents:r,tsConfigFileDiagnostics:o}=tl(e.srcRoot,e.tsConfigFullPath),i={...r.options,...cs(e.srcRoot)[e.buildType],incremental:!1},s=t(r.options),a=[],c=(0,ao.not)(e.entrypoints,r.raw.exclude).map(m=>(0,Fe.isAbsolute)(m)?m:(0,Fe.join)(e.srcRoot,m));if(r.options.composite)a=[...new Set([...c,...r.fileNames])];else{let m=r.fileNames.filter(g=>g.endsWith(".d.ts")),f=(0,ao.not)(m,r.raw.exclude).map(g=>(0,Fe.isAbsolute)(g)?g:(0,Fe.join)(e.srcRoot,g));a=[...new Set([...c,...f])]}let l=n({rootNames:a,options:i,host:s,configFileParsingDiagnostics:o,projectReferences:r.projectReferences}),d=l.emit();return[...l.getSyntacticDiagnostics(),...l.getSemanticDiagnostics(),...l.getConfigFileParsingDiagnostics(),...l.getGlobalDiagnostics(),...l.getDeclarationDiagnostics(),...d.diagnostics].map(m=>ei(m,e.appRoot))}function tl(e,t){let{sys:n,readConfigFile:r,parseJsonConfigFileContent:o}=Te(e),i=r(t,c=>(0,ps.readFileSync)(c).toString()),s=[];i.error&&(0,Yn.has)(i.error.file,"parseDiagnostics")&&(s=(0,Yn.get)(i.error?.file,"parseDiagnostics"));let a=o(i.config,n,(0,Fe.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}var er=require("@dynatrace/runtime-simulator"),bo=require("chalk"),vt=require("http2"),Yt=require("path");var Zn=(r=>(r.Windows="windows",r.MacOS="macos",r.Other="other",r))(Zn||{});var ls=require("url");async function us({clientID:e,clientSecret:t,accountURN:n},r,o){if(!e||!t)throw new Error('"clientID" and "clientSecret" are required to fetch an automation token..',{cause:259});let i=new ls.URLSearchParams;i.append("grant_type","client_credentials"),o&&i.append("scope",o.map(s=>s.name).join(" ")),i.append("client_id",e),i.append("client_secret",t),n&&i.append("resource",n);try{let s=await E(`${new URL(r).origin}/sso/oauth2/token`,{method:"POST",body:Buffer.from(i.toString()),headers:{"content-type":"application/x-www-form-urlencoded"}}),a=await s.json();if(s.ok)return a;throw Hr(JSON.stringify(a)??"Could not get token from authentication provider")}catch(s){let a=s,c=a.cause&&typeof a.cause!="number"?a.cause:a;throw p.debug(`Failed to get automation token! Backend responded with: ${c.message}`,"AUTH"),new Error(`${c.message}`,{cause:259})}}var ms=require("url");var co=new Map;async function ds(e){if(co.has(e)){let o=co.get(e);return p.debug(`Found resolved URL in cache: ${o.toString()}`,"HTTP(S)"),o}p.debug(`Execute GET request without allowing redirection to '${e}'`,"HTTP(S)");let t=await E(e,{redirect:"follow"}),n,r=t.headers.get("location");return r?n=new URL(r):n=new URL(t.url),p.debug(`Resolved URL is ${n.toString()}`,"HTTP(S)"),co.set(e,n),n}async function yt(e){try{let t=new ms.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",p.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await ds(t.toString())).origin;return p.debug(`Using SSO-URL '${n}'`,"AUTH"),n}catch(t){let n=A(t);p.debug(`SSO-URL for '${e}' could not be processed.`,"AUTH"),p.debug(`Error: ${n.message}`,"AUTH"),Zo(new Error(`SSO-URL for '${e}' could not be processed.
${n.message}
If you need further assistance visit the connectivity troubleshooting guide here: https://dt-url.net/c4jp0s12`,{cause:258}),"DEC:DA")}}var $s=require("path"),Ns=require("fs");var Ts=x(require("fastify")),xs=x(require("open")),Es=require("mime-types"),Ss=require("querystring");var qt=require("crypto"),Qn=[{name:"app-engine:apps:run",comment:"cli-scope"}];function fs(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function nl(e){return(0,qt.createHash)("sha256").update(e).digest()}var po=fs((0,qt.randomBytes)(46)),gs=fs(nl(po)),hs=(0,qt.randomBytes)(20).toString("hex");async function ys(e,t,n,r){let o=new URL(e);o.pathname="/sso/oauth2/token",o.searchParams.append("grant_type","authorization_code"),o.searchParams.append("code",n),o.searchParams.append("client_id",t),o.searchParams.append("redirect_uri",r.toString()),o.searchParams.append("code_verifier",po);let i=await E(o.toString(),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!i.ok)throw new Error(i.statusText,{cause:259});return await i.json()}async function bs(e,t){if(ie){let n=`https://${Me(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var uo=x(require("fs")),lo;function rl(){try{return uo.default.statSync("/.dockerenv"),!0}catch{return!1}}function ol(){try{return uo.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function vs(){return lo===void 0&&(lo=rl()||ol()),lo}var Ps=require("@dynatrace/devkit");var ws=`<html>
<head>
<meta charset="utf-8" />
<title>dt-app - Dynatrace</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<style>
@font-face {
font-family: 'DynatraceFlow';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://dt-cdn.net/fonts/DTFlow-Regular-v002.woff2)
format('woff2');
}
@font-face {
font-family: 'DynatraceFlow';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://dt-cdn.net/fonts/DTFlow-Medium-v002.woff2)
format('woff2');
}
@font-face {
font-family: 'DynatraceFlow';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(https://dt-cdn.net/fonts/DTFlow-Semibold-v002.woff2)
format('woff2');
}
:root {
--bg-color: rgb(243, 243, 247);
--line-color: #d2d3e1;
--text-color: rgb(43, 42, 88);
--text-link-color: rgb(69, 76, 201);
--text-accent-color: rgb(244, 244, 251);
--primary-color: rgb(71, 78, 207);
--font-family: DynatraceFlow, Roboto, Helvetica, sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: rgb(25, 25, 44);
--text-color: rgb(235, 236, 255);
--line-color: rgb(59, 59, 82);
--primary-color: rgb(153, 155, 237);
--text-accent-color: rgb(31, 32, 55);
--text-link-color: rgb(173, 176, 255);
}
}
body {
font-family: DynatraceFlow, Roboto, Helvetica, sans-serif;
color: var(--text-color);
background-color: var(--bg-color);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 16px;
height: 100%;
text-align: center;
}
* {
overflow-wrap: break-word;
font-style: normal;
color: inherit;
margin: 0px;
}
h1 {
font-size: 32px;
font-weight: 600;
line-height: 1.25;
}
p,div,a {
font-size: 14px;
font-weight: 400;
line-height: 20px;
}
.divider {
width: 100%;
height: 1px;
border: none;
margin: 0;
background-color: var(--line-color);
max-width: 512px;
}
button {
width: fit-content;
font-weight: 500;
font-size: 14px;
padding: 6px 8px;
background-color: var(--primary-color);
color: var(--text-accent-color);
cursor: pointer;
height: 32px;
border-radius: 8px;
border: 0;
outline-color: var(--text-accent-color);
}
button:disabled {
--primary-color: #54558780;
--text-accent-color: #dadbe780;
cursor: not-allowed;
}
a {
color: var(--text-link-color);
outline-color: var(--text-link-color);
text-decoration-color: var(--text-link-color);
}
a > span {
text-decoration: none;
}
a > span > svg {
margin-left: var(--dt-spacings-size-2, 2px);
width: 1lh;
height: 1lh;
max-height: min(1.5em, var(--dt-spacings-size-40, 40px));
max-width: min(1.5em, var(--dt-spacings-size-40, 40px));
vertical-align: middle;
margin-bottom: -0.1em;
margin-top: -0.1em;
}
</style>
<body>
<img style="max-width: 256px;"
src="data:image/svg+xml,%3Csvg width='128' height='128' viewBox='0 0 73 73' fill='none' xmlns='http://www.w3.org/2000/svg' %3E%3Cpath d='M24.736 6.39229C23.83 11.1739 22.7227 18.2708 22.1187 25.4684C21.0617 38.1523 21.716 46.6585 21.716 46.6585L3.84787 63.6207C3.84787 63.6207 2.48888 54.1078 1.78422 43.3869C1.38156 36.743 1.23056 30.9044 1.23056 27.3811C1.23056 27.1797 1.33123 26.9784 1.33123 26.7771C1.33123 26.5254 1.63322 24.1598 3.94853 21.9451C6.46517 19.5291 25.038 4.98297 24.736 6.39229Z' fill='%231496FF' /%3E%3Cpath d='M24.736 6.39226C23.83 11.1739 22.7227 18.2708 22.1187 25.4684C22.1187 25.4684 2.33788 23.1028 1.23056 27.8844C1.23056 27.6327 1.58289 24.7134 3.8982 22.4988C6.41484 20.0828 25.038 4.98294 24.736 6.39226Z' fill='%231284EA' /%3E%3Cpath d='M1.23057 26.7267C1.23057 27.0791 1.23057 27.4314 1.23057 27.834C1.4319 26.9784 1.78423 26.3744 2.48889 25.4181C3.94854 23.5558 6.31418 23.0524 7.2705 22.9518C12.1025 22.2974 19.2497 21.5424 26.4473 21.3411C39.1815 20.9385 47.5871 21.9954 47.5871 21.9954L65.4552 5.03329C65.4552 5.03329 56.0933 3.27164 45.4228 2.01332C38.4265 1.15766 32.2859 0.70467 28.8129 0.503339C28.5613 0.503339 26.095 0.201342 23.7797 2.41598C21.263 4.83196 8.47849 16.9622 3.34455 21.8444C1.02924 24.0591 1.23057 26.5254 1.23057 26.7267Z' fill='%23B4DC00' /%3E%3Cpath d='M64.8009 48.4202C59.9689 49.0745 52.8217 49.8798 45.6241 50.1315C32.8899 50.5341 24.434 49.4771 24.434 49.4771L6.56584 66.4896C6.56584 66.4896 16.0284 68.3519 26.699 69.5599C33.2422 70.3149 39.0305 70.7176 42.5538 70.9189C42.8055 70.9189 43.2081 70.7176 43.4598 70.7176C43.7114 70.7176 46.1777 70.2646 48.4931 68.0499C51.0097 65.634 66.2102 48.2692 64.8009 48.4202Z' fill='%236F2DA8' /%3E%3Cpath d='M64.8009 48.4202C59.969 49.0745 52.8217 49.8798 45.6241 50.1315C45.6241 50.1315 46.9831 70.0129 42.2015 70.8686C42.4531 70.8686 45.7248 70.7176 48.0401 68.503C50.5567 66.087 66.2102 48.2692 64.8009 48.4202Z' fill='%23591F91' /%3E%3Cpath d='M43.2584 70.9693C42.9061 70.9693 42.5538 70.9189 42.1511 70.9189C43.0571 70.7679 43.6611 70.4659 44.6174 69.7613C46.5301 68.4023 47.1341 66.0367 47.3354 65.0803C48.1911 60.2987 49.3487 53.2018 49.9024 46.0042C50.909 33.3203 50.305 24.8644 50.305 24.8644L68.1732 7.85194C68.1732 7.85194 69.4818 17.3145 70.2368 28.0354C70.6898 35.0317 70.8408 41.2226 70.8911 44.6452C70.8911 44.8969 71.0925 47.3632 68.7772 49.5778C66.2605 51.9938 53.476 64.1743 48.3924 69.0566C45.9764 71.2713 43.5101 70.9693 43.2584 70.9693Z' fill='%2373BE28' /%3E%3C/svg%3E"
/>
<h1>App Toolkit: Successfully authenticated</h1>
<p>You have been successfully authenticated!</p>
<div style="display: flex; gap: 8px; flex-direction: column; align-items: center;">
<button id="closeButton" onclick="closeTab()">Close tab</button>
</div>
<div class="divider"></div>
<div>
Explore our
<a href="https://dt-url.net/bm034a8">
Documentation<span><svg focusable="false" role="img" aria-hidden="false" fill="currentColor" width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-label="Opening the link in a new window"><path d="M17.0003 3L17.0003 9H15.5003L15.5003 5.62104L11.0607 10.0607L10 9L14.5 4.5L11.0003 4.5V3H17.0003Z"></path><path d="M8 3H4C3.44772 3 3 3.44772 3 4V16C3 16.5523 3.44772 17 4 17H16C16.5523 17 17 16.5523 17 16V12H15.5V15.5H4.5V4.5H8V3Z"></path></svg></span></a>.
</div>
<script>
const infoText = "The page could not be closed, please close it manually."
const button = document.querySelector("#closeButton")
function closeTab() {
window.close();
window.top.close();
const isClosed = window.closed || window.top.closed;
if (!isClosed) {
button.title = infoText;
button.disabled = true;
const infoP = document.createElement("p")
infoP.textContent = infoText;
button.parentElement?.append(infoP)
alert(infoText)
}
}
</script>
</body>
</html>
`;var bt=null;async function Cs(e,t,n,r,o){return bt!==null||(p.debug("Authenticate with Dynatrace SSO","AUTH"),bt=il(e,t,n,r,o).then(i=>(bt=null,i))),bt}async function il(e,t,n,r,o){let i=(0,Ts.default)({forceCloseConnections:!0});i.addHttpMethod("PROPFIND");let s=await(0,Ps.findPortInRange)("localhost",5343,5363),a=new URL(await bs(s,o)),c=(0,Ss.stringify)({client_id:t,redirect_uri:a.toString(),state:hs,response_type:"code",code_challenge_method:"S256",code_challenge:gs,...n?{scope:n.map(y=>y.name).join(" ")}:{}}),l=new URL(e).origin,d,u=new Promise(y=>{d=y});i.get("/auth/login",async(y,b)=>{let{code:h,state:w}=y.query;return p.debug("Received authorized code for oAuth","AUTH"),d({code:h,state:w}),b.code(200).header("Content-Type",(0,Es.contentType)(".html")).send(ws)});let m=v([l,`oauth2/authorize?${c}`]),f=await E(m);if(!f.ok)throw bt=null,p.debug(f.statusText,"AUTH"),new Error("Authentication failed! Please check if the scopes you specified are valid and if the user has permissions for all of those scopes.",{cause:259});await i.listen({port:s,...vs()&&{host:"0.0.0.0"}}),p.debug(`SSO-link ${m}`,"AUTH"),r?await(0,xs.default)(m):p.log(`Open this url to authenticate: ${m}`);let{code:g}=await u;return i.close(),ys(e,t,g,a)}async function Os(e,t,n){let r=new URL(e);r.pathname="/sso/oauth2/token",r.searchParams.append("grant_type","refresh_token"),r.searchParams.append("client_id",t),r.searchParams.append("refresh_token",n);let o=await E(r.toString(),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"}});if(!o.ok){let i=await o.json();throw new Error(i.error_description?`${i.error_description} (traceId: ${i.issueId})`:o.statusText,{cause:259})}return await o.json()}var Ve=require("fs"),mo=require("path");var Rs=require("lodash");function As(e,t){return e.length!==t.length?!1:sl(e,t)}function sl(e,t){return e.every(n=>typeof n=="object"?!!t.find(r=>(0,Rs.isEqual)(n,r)):t.includes(n))}var Fs=require("jsonwebtoken"),al="AUTH";function ks(e,t,n,r,o){let i=o?.map(l=>l.name)||[],s=e.scope?.split(" ")||[],a=o?As(i,s):!0;return e.environment_url===t&&e.oauth_url===n&&e.oauth_client_id===r&&a}function Ds(e){try{let n=(0,Fs.decode)(e).exp,r=new Date(n*1e3),o=new Date,s=(r.getTime()-o.getTime())*.001;return s<60?(p.debug(`OAuth2 token expired with a value of: ${s} seconds`,al),!1):!0}catch{return!1}}async function Is(e){let{currentAuthWorkflow:t,tokenFilePath:n,environmentUrl:r,oauthUrl:o,oauthClientId:i,appScopes:s,tokenInformation:a}=e,c=(0,Ve.existsSync)(n);if(!a||!c)return"invalid";if(a.authentication_flow!==t)return"invalid";let l=ks(a,r,o,i,s),d=Ds(a.access_token);return l?d?"valid":d?"invalid":"refresh-required":"invalid"}function fo(e,t){(0,Ve.existsSync)((0,mo.dirname)(e))||(0,Ve.mkdirSync)((0,mo.dirname)(e),{recursive:!0}),(0,Ve.writeFileSync)(e,JSON.stringify(t,null,2))}var Jt=new Map;async function Ms(e,t){if(Jt.has(t))return p.debug(`Promise with key ${t} meant to be run once at a time. Initial promise will be returned!`,"promise"),Jt.get(t);let n=e();Jt.set(t,n);try{return await n}catch(r){throw Jt.delete(t),r}finally{Jt.delete(t)}}var go="dt0s08.dt-app-local";var cl=e=>({openAuthUrl:!0,tokenFilePath:(0,$s.join)(e,".dt-app/.tokens.json")});async function U(e,t){let n=await ll(e,t),r=await Is(n);return r==="refresh-required"?Ms(async()=>{try{return await pl(n)}catch(o){return p.debug(`Refresh process for token ${n.tokenType} has failed with: ${o}. Proceeding with SSO flow instead.`,"AUTH"),_s(n,"invalid")}},n.tokenType):_s(n,r)}async function _s(e,t){if(process.env.DT_APP_PLATFORM_TOKEN)return p.debug("Using DT_APP_PLATFORM_TOKEN for authentication.","AUTH"),process.env.DT_APP_PLATFORM_TOKEN;let{currentAuthWorkflow:n,tokenFilePath:r,environmentUrl:o,oauthUrl:i,oauthClientId:s,appScopes:a,tokenType:c,currentTokenFileContent:l,tokenInformation:d,openAuthUrl:u}=e;if(t==="valid")return d.access_token;let m="",f=l;if(n==="automation")try{[f,m]=await Us(f,c,o,s,process.env.DT_APP_OAUTH_CLIENT_SECRET,i,a)}catch(g){let b=(await Promise.all((a||[]).map(h=>Us(f,c,o,s,process.env.DT_APP_OAUTH_CLIENT_SECRET,i,[h]).then(()=>({appScope:h,granted:!0})).catch(()=>({appScope:h,granted:!1}))))).filter(({granted:h})=>!h).map(({appScope:h})=>h.name).join(",");throw b?new Error(`Could not authenticate using the automation token