UNPKG

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.

234 lines (207 loc) 120 kB
"use strict";var pa=Object.create;var It=Object.defineProperty;var la=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var da=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var fa=(e,t)=>{for(var n in t)It(e,n,{get:t[n],enumerable:!0})},Ir=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ua(t))!ma.call(e,o)&&o!==n&&It(e,o,{get:()=>t[o],enumerable:!(r=la(t,o))||r.enumerable});return e};var E=(e,t,n)=>(n=e!=null?pa(da(e)):{},Ir(t||!e||!e.__esModule?It(n,"default",{value:e,enumerable:!0}):n,e)),ga=e=>Ir(It({},"__esModule",{value:!0}),e);var Lp={};fa(Lp,{DevServer:()=>In,OperatingSystem:()=>on,_ExecuteFunction:()=>_p,_ExtractDtAppConfigFromTs:()=>jp,_Fetch:()=>Bp,_GetBearerToken:()=>Mp,_GetDtAppFileConfig:()=>$p,_GetSSOUrl:()=>Np,_InternalPrepareManifest:()=>On,_MergeOptions:()=>Up,getDefaultCliOptions:()=>De});module.exports=ga(Lp);var R=require("path");var _r={sourcemap:!1,includeVendorSourceMaps:!1},ha={sourcemap:!0,includeVendorSourceMaps:!0};function X(e){if(e.sourcemaps===void 0)return e.dev?ha:_r;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 _r}}var G=require("path");function Me(e,t){let n=G.posix.normalize(G.posix.join(t.split(G.win32.sep).join(G.posix.sep),"/")),r=new RegExp(`^.*?${n}`,"g"),o=G.posix.parse(e.split(G.win32.sep).join(G.posix.sep).replace(r,""));return new URL("http://localhost"+G.posix.normalize(G.posix.join("/",o.dir,o.name.replace(/\.function$/,"")))).pathname}var dt=require("path");var Ve=require("path");var Mr=require("fs"),ya="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",Z=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(t.path.endsWith(".js"))return{contents:`${(0,Mr.readFileSync)(t.path,"utf8")} ${ya}`,loader:"default"}})}});function F(e,t){return require.resolve(e,{paths:[t]})}var Mn=require("path");var $r=require("chalk");var P=(d=>(d[d.POSIX_SIGNAL_BASE=128]="POSIX_SIGNAL_BASE",d[d.UNCAUGHT=256]="UNCAUGHT",d[d.INTERNAL=257]="INTERNAL",d[d.USER=258]="USER",d[d.AUTH=259]="AUTH",d[d.TIMEOUT=260]="TIMEOUT",d[d.COMPILATION=261]="COMPILATION",d[d.NETWORKING=263]="NETWORKING",d[d.VALIDATION=264]="VALIDATION",d[d.BUILD=265]="BUILD",d[d.APP_GATEWAY_COMMUNICATION=266]="APP_GATEWAY_COMMUNICATION",d))(P||{}),ba=`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 Un(e){let t=[e,ba];return new Error(t.filter(Boolean).join(` `),{cause:259})}function $n(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(Mn.sep)?`${t.replace(/["']/g,"").split(Mn.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function A(e){return e instanceof Error?e:new Error(String(e))}function _t(e,t){throw new Error(`ERROR [${(0,$r.green)(t)}]: ${e.message}`)}var tr=require("path"),Zt=require("fs");var Br=require("path");var Bn;function ge(e){return Bn||(Bn=require(F("typescript",e))),Bn}function ue(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,Br.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function Nn(e,t){let n=ge(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 Mt=require("path");function M(){if(__filename.endsWith("bin.js"))return(0,Mt.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Mt.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Mt.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Ao=require("fs"),he=E(require("fast-glob")),re=require("path");function b(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]):/,"")}var jt=E(require("fs"));var Ut=require("undici");async function S(e,t){return(0,Ut.fetch)(e,t)}var Lt=require("path");var Nr=E(require("path"));function Ue(){return Nr.default.resolve(M(),"utils","snippets")}var jr=E(require("fastify")),jn=require("fs"),Lr=E(require("ws"));function Wr(e){let t={};e.https&&(t={https:{cert:(0,jn.readFileSync)(e.https.cert),key:(0,jn.readFileSync)(e.https.key)}});let n=(0,jr.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(r,o,i)=>{i(null,o)}),n}function Hr({server:e}){return new Lr.default.Server({server:e})}function Vr(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}var $t=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function Gr(e){if(!$t)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${$t}-${e}.${t}`}var rt=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function zr(e){if(!rt)return;let t=new URL(rt).hostname;return`${e}-${t}`}var Ln=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,z=rt||$t||Ln;function xe(e){if(z)return Ln?Ln.replace(/^https?:\/\//,""):rt?zr(e):Gr(e)}function Bt(e){let t=xe(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}function qr(){let e=(0,Lt.resolve)(Ue(),"defaultIndex.snippet.html");return jt.default.readFileSync(e).toString("utf-8")}function $e(e,t){let{transformSync:n}=require(F("esbuild",t)),r=(0,Lt.resolve)(Ue(),"sdkWebShim.snippet.ts"),o=jt.default.readFileSync(r,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(o,i).code}function Jr(e){let t=(0,Lt.resolve)(Ue(),"selfmon_config.snippet.js");return jt.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var Nt;async function Wt(e){return Nt||(Nt=await(await S(e)).text(),Nt)}function Be(e){let t=Bt(e.server.port),n=Vr(e.server);return`window.socketUrl = '${t===""?n:t}';`}var Kr=E(require("chalk"));var Ta=/(?<=(?:\||")cuc=).*?(?=\||")/g,Wn;function Yr(e){let t;Wn?t=Wn:(t=Ta.exec(e),Wn=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${Kr.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function Xr(e){try{if(!e.includes("http"))return 3;let t=await S(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 Wt(e),0)}catch{return 1}}var _=require("chalk"),je=require("lodash");var U=require("fs"),Qr=require("fs/promises"),Ht=require("path"),wa=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),Zr=e=>(e>9?"":"0")+e,Pa=e=>`${e.getFullYear()}-${Zr(e.getMonth()+1)}-${Zr(e.getDate())}_log.txt`,Sa=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},Hn=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},Vn=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,Ht.join)(t,".dt-app/logs"),(0,U.existsSync)(this.logFolder)||(0,U.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,Ht.join)(this.logFolder,Pa(new Date)),!(0,U.existsSync)(this.logFile)){let t=(0,U.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>wa.test(n));if(t.length>=10){let n=t.map(r=>({path:r,date:Sa(r)})).filter(r=>r.date).sort((r,o)=>r.date.getTime()-o.date.getTime())[0].path;(0,Qr.unlink)((0,Ht.join)(this.logFolder,n))}(0,U.closeSync)((0,U.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,U.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 eo(e){return Vt=new Vn,Vt.setup(e)}var Vt=new Hn;var ro=require("os");var qn=E(require("ora"));var Gn=[],Ne=!1;function Ca(e){return new Promise((t,n)=>{Gn.push(async()=>{try{let r=await e();t(r)}catch(r){n(r)}}),Ea()})}async function Ea(){if(!Ne){for(Ne=!0;Gn.length>0;)await Gn.shift()();Ne=!1}}async function Gt(e){return Ca(e)}var st=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",ot={interval:80},de=[],Te="idle",at=(0,qn.default)({spinner:{frames:[""],interval:ot.interval},isSilent:!st}),Oa=()=>` ${de.map(e=>e.getFrame()).join(` `)}`;function Aa(){at.text=Oa()}var it;function Ra(){st&&Te!=="running"&&!Ne&&(it===void 0&&(it=setInterval(Aa,ot.interval)),at.start(),Te="running")}function to(){Te==="running"&&(Te="paused",at.stop())}function no(){Te==="paused"&&!Ne&&(Te="running",at.start())}function zn(){Te="idle",at.stop(),de.forEach(e=>e.abort()),it!==void 0&&(clearInterval(it),it=void 0)}var zt=class{spinner;constructor(t){this.spinner=(0,qn.default)({...t,isSilent:!st})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=de.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),de.splice(t,1)),de.length===0&&zn()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),de.includes(this)||de.push(this),Ra(),this}_stop(t,n="abort"){switch(this.text=t??this.text,to(),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(),no(),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")}},Q={create:(e={})=>new zt({...e,interval:ot.interval}),start:(e,t={})=>new zt({...t,interval:ot.interval}).start(e),pause:to,resume:no,reset:zn,successAll:e=>de.forEach(t=>t.succeed(e)),failAll:e=>de.forEach(t=>t.fail(e)),disable:()=>{st=!1,zn()},enable:()=>{st=!0},getInterval:()=>ot.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 oo=`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 Jn=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>Q.create(),disable:Q.disable,start:t=>Q.start(t),pause:Q.pause,resume:Q.resume,abort:Q.reset};disable(){this.disabled=!0,Q.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,_.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},Q.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,_.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,_.red)(this._padString(t,0)),"ERROR")}warn(t){let n=` ${(0,_.yellow)("Warning "+(0,je.repeat)("─",this.warningBoxSize-8))} ${(0,_.yellow)(this._padString(t))} ${(0,_.yellow)((0,je.repeat)("─",this.warningBoxSize))} `;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=` ${(0,_.magenta)((0,je.repeat)("─",this.boxSize))} ${(0,_.magenta)(this._padString(t))} ${(0,_.magenta)((0,je.repeat)("─",this.boxSize))} `;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await eo(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):Gt(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},Q.getInterval()),this._printToFile(t,n))}_printToFile(t,n){Vt.write(`${Fa().toISOString()} ${n} ${Da(t)} `)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(r=>`${(0,je.repeat)(" ",n)}${r}`).join(ro.EOL)}};function Da(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 Fa(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var l=new Jn;var $=E(require("chalk"));var me={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function ao(e){if(e){console.log(`════════ `);return}console.log($.default.hex(me.blue).bold("══")+$.default.hex(me.limeGreen).bold("══")+$.default.hex(me.green).bold("══")+$.default.hex(me.purple).bold("══")+` `)}function ee(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(B(e,t))}function co(e,t="white",n){if(n){console.log(e);return}console.log(B(e,t))}function B(e,t="white"){return{white:$.default.white,blue:$.default.hex(me.blue),green:$.default.hex(me.green),purple:$.default.hex(me.purple),limeGreen:$.default.hex(me.limeGreen),gray:$.default.dim}[t](e)}function Kn(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+` `);return}console.log($.default.hex(me.blue)("─".repeat(n))+` `)}function te(){console.log(` `)}function ct(e,t=""){let n=(r,o="")=>{let c="";return r.items?.forEach((p,u)=>{let d=u===r.items.length-1,f=d?"└─ ":"├─ ",h=d?" ":"│ ";c+=`${o}${f}${p.name} `,p.items?.length&&(c+=n(p,o+h))}),c};console.log(n(e,t))}function pt(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 p=c.split("/");if(p.shift(),p.length!==0)if(p.length===1){let u=p[0];a.items.push(u.endsWith("widget.tsx")?io(u,t,n,r):so(u,t,n))}else{let u=a;for(let f=0;f<p.length-1;f++){let h=p[f],m=u.items.find(y=>y.name===h&&Array.isArray(y.items));m||(m={name:h,items:[]},u.items.push(m)),u=m}let d=p[p.length-1];u.items.push(d.endsWith("widget.tsx")?io(d,t,n,r):so(d,t,n))}}),i.items.push(a)}),i}function io(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 so(e,t,n){return{name:`${n[e]}: ${t[e]}`}}var er=E(require("chalk")),q=require("path"),ut=require("fs/promises");function fe(e){return e.startsWith("../")?e:e.startsWith("./")?e.slice(1):e.startsWith("/")?e:"/"+e}var Qn=require("@dynatrace/openkit-js"),Ua=require("lodash");var lt=require("os"),wo=require("path");var po=require("child_process"),ka=require("commander");function Yn(e,t){let r={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((o,i)=>{(0,po.exec)(e,r,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):o(a)})})}function Ia(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(` `),{cause:266})}async function Xn(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 S(n.toString(),r);return!o.ok||o.headers.get("content-type")?.includes("text/html")?void 0:await o.json()}catch(n){throw Ia(A(n).message)}}async function lo(e,t){let n=await S(`${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:(l.warn(`The default csp policy from the platform couldn't be applied. App-registry failed with: ${n.status} ${n.statusText}`),{})}function we(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 _a(e,t,n,r){let o=await lo(e,n),i=[3e3,3001,3002,3003,3004,3005],s=i.flatMap(m=>z?[`https://${xe(m)}`]:[`http://localhost:${m}`,`https://localhost:${m}`]),a=i.flatMap(m=>z?[Bt(m)]:[`ws://localhost:${m}`,`wss://localhost:${m}`]),c={"script-src":["'unsafe-eval'",...s,...t.map(m=>`'sha256-${m}'`)],"connect-src":[...s,...a],"frame-ancestors":s},{tenant:p,hostname:u}=we(e),d=m=>m.replaceAll("{tenantId}",p).replaceAll("{hostname}",u),f={},h=[...Object.keys(o),...Object.keys(c)];for(let m of h){let y=new Set;for(let v of o[m]??[])y.add(d(v));for(let v of c[m]??[])y.add(d(v));f[m]=Array.from(y)}return f["frame-src"]=["*"],f["frame-ancestors"]=["*"],r&&Object.entries(r).forEach(([m,y])=>{f[m]?f[m].push(...y.map(v=>v.value)):f[m]=y.map(v=>v.value)}),Ma(f)}function Ma(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var uo=new Map;async function mo(e,t,n,r){let o=`${e}-${t.join(",")}-${r}`,i=uo.get(o);if(i)return i;let s=await _a(e,t,n,r);return uo.set(o,s),s}var Le=require("fs");function ne(e){if(!(0,Le.existsSync)(e)&&!(0,Le.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,Le.readFileSync)(e,"utf-8");return JSON.parse(t)}var $a=require("jsonwebtoken");var fo=require("path"),go=require("os");var Vl=(0,fo.join)((0,go.homedir)(),".dt-app",".session");function ho(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function Zn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,yo(n)]))}function yo(e){return e==null?e:Array.isArray(e)?e.map(t=>yo(t)):typeof e=="object"?Zn(e):typeof e=="string"?$n(e):e}function bo(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}var ou=(0,wo.join)((0,lt.homedir)(),".dt-app",".uuid");var vo;var xo,To,Ba=!1,qt;function We(e,t){if(!Ba||!vo||!xo)return;let n=Zn(ho(e.payload||{})),r=t?.environmentUrl||qt?.environmentUrl||"",o=t?.app?.id||qt.appId||"",i=t?.app?.version||qt.appVersion||"",s=process.version.charAt(0)==="v"?process.version.substring(1):process.version,a=r?{tenantId:we(r).tenant,sessionType:bo(r)}:{tenantId:"",sessionType:""},c={...To&&{userId:To},userType:qt.userType||""},p={sessionId:xo.toString(),"event.type":`dt-app.${e["event.category"]}.${e.name}`,"event.category":e["event.category"],"event.provider":"dt-app",operatingSystemVersion:(0,lt.version)(),nodejsVersion:s,appId:o,appVersion:i,cliVersion:global.DT_APP_VERSION,...a,...c,...n};vo.sendBizEvent(p["event.type"],p)}var Co=E(require("fast-glob")),Eo=require("fs"),Po={created:er.default.green`CREATED:`,updated:"UPDATED:",deleted:er.default.red`DELETED:`,copied:"COPIED:"};function Pe(e){let t={},n={fileExists:r,throwIfFileDoesNotExist:o,getFile:i,getFilePathsByRegex:s,getFileMap:a,getFileName:c,setFile:p,setFiles:u,mapEsbuildOutputFiles:d,deleteFile:f,writeFileToDisc:h,writeFileMapToDisc:m,addAssetFiles:y,resetFileMap:v};return e&&u(e),n;function r(g){let x=fe(g);return!!t[x]}function o(g){let x=fe(g);if(!r(g))throw We({"event.category":"crash",name:"fileManager.setFile",payload:{error:`Failed to set file ${g} with fileManager.`}}),new Error(`File ${x} does not exist in fileMap!`)}function i(g){return g=fe(b(g)),o(g),t[g]}function s(g){return Object.keys(t).filter(x=>x.match(g))}function a(){return t}function c(g){return g=fe(b(g)),o(g),(0,q.basename)(g)}function p(g,x){g=fe(b(g)),t[g]={content:x}}function u(g){for(let x in g)p(x,g[x].content)}function d(g,x,T="dist"){let pe=b([x,"dist"]);return(g||[]).forEach(Y=>{let le=b(Y.path),nt=b([T,le.replace(pe,"")]),_n=fe(nt);t[_n]={content:Buffer.from(Y.contents)}}),n}function f(g){g=fe(b(g)),delete t[g]}async function h(g){g=fe(b(g)),o(g),await(0,ut.writeFile)((0,q.join)(g),t[g].content)}async function m(g){await Promise.all(Object.entries(t).map(async([x,{content:T,mode:pe}])=>{let Y=(Buffer.byteLength(T,"utf8")/Math.pow(2,10)).toFixed(2),le=(0,q.join)(g,x);return l.debug(`${pe!==void 0?Po[pe]:Po.created} ${le} ${`(${Y} KB)`}`,"FILES"),await(0,ut.mkdir)((0,q.dirname)(le),{recursive:!0}),(0,ut.writeFile)(le,T)}))}async function y(g){for(let x of g.assetConfigs){let T=(0,q.isAbsolute)(x.input)?x.input:(0,q.join)(g.root,x.input),pe=await(0,Co.default)(x.glob,{cwd:T,dot:!0,ignore:x.ignore});for(let Y of pe){let le=b([g.distDir,x.output,Y]);p(le,(0,Eo.readFileSync)((0,q.join)(T,Y)))}}}function v(){t={}}}var D=Pe();var Kt="documents",Ro="document-types";async function Yt(e,t,n,r){let o=await Wt(t),i=r.startsWith("dynatrace.");if(!i){let s;try{s=Yr(o)}catch(u){let d=u instanceof Error?u.message:String(u);l.error(d);return}let a=Jr(s),c="./assets/agentConfig.js",p=b([n,c]);D.setFile(p,Buffer.from(a)),e.injectScript(c)}e.injectScript(t),i&&e.addInjectionMarker()}function J(e){if(!(0,Ao.existsSync)((0,re.join)(e.cwd,e.sourceRoot,"api")))return[];let t=e.includeJs?"{ts,js}":"ts";return(0,he.sync)(b([e.sourceRoot,"api",`**/*.function.${t}`]),{cwd:e.cwd,ignore:["**/*.test.ts","**/*.spec.ts"]})}function Do(e){let t=J({cwd:e.cwd,sourceRoot:e.sourceRoot});if(!t.length)return;ee("Available app functions served from '/api':","green"),te();let n={};t.forEach(i=>{n[i.split("/")[i.split("/").length-1]]=B(e.url+b(["/api",Me(i,"api").replace(".resumable","")]),"gray")});let r=Xt(t,e.cwd),o=pt(t,n,r);ct(o)}async function Fo(e){let t=await(0,he.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,he.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;ee("Available workflow actions:","green"),te();let r=Xt([...n,...t],e.cwd),o=Na(e,n,t),i=pt([...n,...t],o,r);ct(i)}function Na(e,t,n){let r={};return t.forEach(o=>{let i=Jt(o),s=(0,re.basename)(o,".action.ts");r[i]=B(`${e.url}/api/${s.replace(".resumable","")}`,"gray")}),n.forEach(o=>{let i=Jt(o),s=(0,re.basename)(o,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;r[`${i}_local`]=B(a,"gray"),r[`${i}_environment`]=B(ja(e.environmentUrl,a,e.locationAppIds),"gray")}),r}function Jt(e){let t=e.split("/");return t[t.length-1]}function ja(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function He(e,t){return(await(0,he.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(r=>(0,re.join)(e,r))}async function ko(e){let t=await(0,he.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;ee("Available settings widgets:","green"),te();let n={};t.forEach(i=>{let s=Jt(i),a=(0,re.basename)(s,".widget.tsx"),c=`${e.url}/widgets/settings/${a}`;n[`${s}_local`]=B(c,"gray")});let r=Xt(t,e.cwd),o=pt(t,n,r,!1);ct(o)}async function Io(e){let t=await(0,he.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;ee("Available documents:","green"),te();let n={};t.forEach(i=>{let s=Jt(i),a=`${e.appId}.${(0,re.basename)(i).split(".")[0]}`;n[s]=B(a,"gray")});let r=Xt(t,e.cwd),o=pt(t,n,r);ct(o)}function Xt(e,t){let n={};return e.forEach(r=>{let o=(0,re.basename)(r);n[o]=La((0,re.join)(t,r),o)}),n}function La(e,t){return process.platform==="win32"&&(e="/"+e.replace(/\\/g,"/").replace(/^\/+/,"")),`\x1B]8;;file://${e.replace(/\\/g,"/")}\x1B\\${t}\x1B]8;;\x1B\\`}function Qt(e){return e.map(Wa).filter(t=>!t.filePath?.includes("node_modules/"))}var _o=e=>ue(e,"Error"),Wa=e=>ue(e,"Warning");async function Mo(e,t){let r=J({cwd:e.root,sourceRoot:e.build.sourceRoot}).length>0,o=(0,Zt.existsSync)((0,tr.join)(e.root,t));if(r&&!o)throw new Error(`Failed to build functions A tsconfig.json must exist, if function source files are present in the api directory. Please create a tsconfig.json file in the api directory, or delete the directory. ${(0,Zt.readFileSync)((0,tr.join)(M(),"function/template/tsconfig.json"),"utf-8")}: `,{cause:265});if(!r&&o)throw new Error(`Failed to build functions A tsconfig.json exists, but no functions were found in the api directory. Please create a function in the api directory, or delete the directory. You can create functions with the generate command: $ npm run generate:function `,{cause:265})}function oe(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}async function Uo(e,t,n){let r=require(F("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??[],Z()]);let s=await o({...oe(),entryPoints:t.entryPoints.map(c=>(0,Ve.isAbsolute)(c)?c:(0,Ve.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,Ve.isAbsolute)(t.tsconfig)?t.tsconfig:(0,Ve.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 en(e,t){let n=Date.now();try{let r=(0,dt.join)(e.cwd,"dist"),o=await Uo(r,e,t),i=Date.now(),s=o.warnings.map(p=>ue(p,"Warning")).filter(p=>!p.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:o.outputFiles.reduce((p,u)=>{let d=`${dt.sep}${(0,dt.join)(a,u.path.replace(r,""))}`;return{...p,[d]:{content:Buffer.from(u.contents)}}},{}),diagnostics:s,duration:i-n,metafile:o.metafile}}catch(r){let o=Date.now();if(Ha(r)){let s=[...r.errors.map(a=>ue(a,"Error")),...r.warnings.map(a=>ue(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 Ha(e){return typeof e=="object"&&typeof e?.errors<"u"}var Ge=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}});var nn=require("lodash"),nr=require("micromatch"),Bo=require("fs"),ye=require("path");var tn={noEmit:!0,skipLibCheck:!0};function $o(e){let{ScriptTarget:t}=ge(e);return{ui:{target:t.ES2021,...tn},functions:{target:t.ESNext,...tn},actions:{target:t.ESNext,...tn},widgets:{target:t.ESNext,...tn}}}var rn=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`});function N(e){let{createCompilerHost:t,createProgram:n}=ge(e.srcRoot),{tsConfigContents:r,tsConfigFileDiagnostics:o}=Va(e.srcRoot,e.tsConfigFullPath);if(r.projectReferences&&r.projectReferences.length>0&&r.fileNames.length===0)return Ga(e);let s={...r.options,...$o(e.srcRoot)[e.buildType],incremental:!1},a=t(r.options),c=[],p=(0,nr.not)(e.entrypoints,r.raw.exclude).map(h=>(0,ye.isAbsolute)(h)?h:(0,ye.join)(e.srcRoot,h));if(r.options.composite)c=[...new Set([...p,...r.fileNames])];else{let h=r.fileNames.filter(y=>y.endsWith(".d.ts")),m=(0,nr.not)(h,r.raw.exclude).map(y=>(0,ye.isAbsolute)(y)?y:(0,ye.join)(e.srcRoot,y));c=[...new Set([...p,...m])]}let u=n({rootNames:c,options:s,host:a,configFileParsingDiagnostics:o,projectReferences:r.projectReferences}),d=u.emit();return[...u.getSyntacticDiagnostics(),...u.getSemanticDiagnostics(),...u.getConfigFileParsingDiagnostics(),...u.getGlobalDiagnostics(),...u.getDeclarationDiagnostics(),...d.diagnostics].map(h=>Nn(h,e.appRoot))}function Va(e,t){let{sys:n,readConfigFile:r,parseJsonConfigFileContent:o}=ge(e),i=r(t,c=>(0,Bo.readFileSync)(c).toString()),s=[];i.error&&(0,nn.has)(i.error.file,"parseDiagnostics")&&(s=(0,nn.get)(i.error?.file,"parseDiagnostics"));let a=o(i.config,n,(0,ye.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}function Ga(e){let{sys:t,createSolutionBuilderHost:n,createSolutionBuilder:r}=ge(e.srcRoot),o=[],i=n(t,void 0,a=>{o.push(a)},a=>{o.push(a)});return r(i,[e.tsConfigFullPath],{dry:!1,force:!1,verbose:!1}).build(),o.map(a=>Nn(a,e.appRoot))}var No=require("path"),jo=require("worker_threads");var ze={actions:void 0,functions:void 0,ui:void 0,widgets:void 0};async function Lo(){let e=["actions","functions","ui","widgets"];await Promise.all(e.map(t=>{let n=ze[t];return n?(ze[t]=void 0,n.terminate()):Promise.resolve()})),l.debug("All TypeScript workers terminated","TYPESCRIPT")}function ie(e){if(ze[e.buildType])return;let t=n=>{switch(n.type){case"initialized":l.debug(` ${n.payload} typescript worker thread has been initialized!`,"TYPESCRIPT");break;case"type-error":l.info(n.payload);break;case"send-biz-event":We({"event.category":"error",name:"ts-worker-error",payload:n.payload});break;case"entrypoints-changed":l.debug(`New amount of entrypoints for ${n.payload.buildType}: ${n.payload.entrypoints.length}`,`ENTRYPOINTS_WATCHER-${n.payload.event}`)}};ze[e.buildType]=new jo.Worker((0,No.join)(M(),"ts-worker.js"),{workerData:e}),ze[e.buildType].once("error",n=>{l.error(`TypeScript worker thread error: ${n}`),process.exit(1)}),ze[e.buildType].on("message",n=>{t(n)})}var mt=["assert","assert/strict","buffer","console","crypto","events","http","https","path","path/posix","path/win32","perf_hooks","querystring","stream","stream/consumers","stream/promises","stream/web","string_decoder","timers","timers/promises","url","util","util/types","zlib","fs","fs/promises","process","node:fs","node:fs/promises","node:process","diagnostics_channel","node:assert","node:assert/strict","node:buffer","node:console","node:crypto","node:diagnostics_channel","node:events","node:http","node:https","node:path","node:path/posix","node:path/win32","node:perf_hooks","node:querystring","node:stream","node:stream/consumers","node:stream/promises","node:stream/web","node:string_decoder","node:timers","node:timers/promises","node:url","node:util","node:util/types","node:zlib"];async function Wo(e,t,n){let r=(0,R.join)(e.build.sourceRoot,"api","tsconfig.json"),o=n||J({cwd:e.root,sourceRoot:e.build.sourceRoot}).map(f=>b([e.root,f]));if(o.length===0)return{fileMap:{},diagnostics:[],duration:0};let i=(0,R.join)(e.distDir,"/api"),s=X({sourcemaps:e.build.sourceMaps,dev:t});t&&s.sourcemap&&(s.sourcemap="inline");let a=[];e.build.typeCheck&&(t?ie({buildType:"functions",appRoot:e.root,tsconfigFullPath:(0,R.join)(e.root,r),entrypoints:o,glob:b([e.build.sourceRoot,"api"])}):a=N({appRoot:e.root,srcRoot:(0,R.join)(e.root,e.build.sourceRoot,"api"),entrypoints:o,tsConfigFullPath:(0,R.join)(e.root,r),buildType:"functions"}));let c=await en({cwd:e.root,entryPoints:o,outbase:(0,R.join)(e.root,e.build.sourceRoot,"api"),tsconfig:r,plugins:[Ge(),...e.build.api?.plugins||[]],platform:e.appFunctionsBuildPlatform==="node"?"node":"browser",external:e.appFunctionsBuildPlatform==="node"?[]:mt,target:"esnext",format:"esm",outDir:i,metafile:!0,sourcemapOptions:s,sourceRoot:rr((0,R.join)(e.build.sourceRoot,"api"))?(0,R.resolve)(e.root,(0,R.dirname)((0,R.join)(e.build.sourceRoot,"api")).split(R.sep)[0]):void 0,minify:!t,production:!t,define:{"process.env.NODE_ENV":e.build.mode==="production"?'"production"':'"development"'}}),p=c.fileMap,u=[...c.diagnostics,...a],d=c.duration;return t?{fileMap:Object.entries(c.fileMap).map(h=>{try{let m="sourceMappingURL=data:application/json;base64,",y=h[1].content.toString("utf-8"),v=y.lastIndexOf(m);v>=0&&(h[1].sourceMap=Buffer.from(y.substring(v+m.length),"base64"))}catch{}return h}).reduce((h,[m,y])=>{if(!m.endsWith(".js.map")){let v=Me(m,i);h[v]={...y,filename:(0,R.parse)(m).base,isOfType:"function"}}return h},{}),diagnostics:u,duration:d}:{fileMap:p,diagnostics:u,duration:d,metafile:c.metafile}}function rr(e){return(0,R.join)(e).split(R.sep).filter(n=>n).length>1}var or;async function Ho(e){if(!or)try{let{invokeDtRuntime:s}=require(F("@dynatrace/js-runtime",e.root));or=s}catch{}let n=await(async()=>{let{fileMap:s}=await Wo(e.config,!1,[e.functionPath]);return Object.values(s)[0]})();if(!n)throw new Error(`function ${e.functionPath} not found`,{cause:257});let r="";try{r=we(e.config.environmentUrl).tenant}catch{}let o={cwd:e.root,urlPathname:"js-runtime",scriptName:e.functionPath,sourceMap:n.sourceMap,code:n.content,payload:e.payload,config:{appId:e.config.app.id,appVersion:e.config.app.version,appName:e.config.app.name,tenantId:r,environmentUrl:e.config.environmentUrl,token:e.token,devProxyUrl:e.devProxyUrl,userDetails:e.userDetails}};return await or(o)??""}var on=(r=>(r.Windows="windows",r.MacOS="macos",r.Other="other",r))(on||{});var Vo=require("url");async function Go({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 Vo.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 S(`${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 Un(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 l.debug(`Failed to get automation token! Backend responded with: ${c.message}`,"AUTH"),new Error(`${c.message}`,{cause:259})}}var qo=require("url");var ir=new Map;async function zo(e){if(ir.has(e)){let o=ir.get(e);return l.debug(`Found resolved URL in cache: ${o.toString()}`,"HTTP(S)"),o}l.debug(`Execute GET request without allowing redirection to '${e}'`,"HTTP(S)");let t=await S(e,{redirect:"follow"}),n,r=t.headers.get("location");return r?n=new URL(r):n=new URL(t.url),l.debug(`Resolved URL is ${n.toString()}`,"HTTP(S)"),ir.set(e,n),n}async function sn(e){try{let t=new qo.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",l.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await zo(t.toString())).origin;return l.debug(`Using SSO-URL '${n}'`,"AUTH"),n}catch(t){let n=A(t);l.debug(`SSO-URL for '${e}' could not be processed.`,"AUTH"),l.debug(`Error: ${n.message}`,"AUTH"),_t(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 yi=require("path"),bi=require("fs");var ti=E(require("fastify")),ni=E(require("open")),ri=require("mime-types"),oi=require("querystring");var ft=require("crypto"),an=[{name:"app-engine:apps:run",comment:"cli-scope"}];function Jo(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qa(e){return(0,ft.createHash)("sha256").update(e).digest()}var sr=Jo((0,ft.randomBytes)(46)),Ko=Jo(qa(sr)),Yo=(0,ft.randomBytes)(20).toString("hex");async function Xo(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",sr);let i=await S(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 Zo(e,t){if(z){let n=`https://${xe(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var cr=E(require("fs")),ar;function Ja(){try{return cr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Ka(){try{return cr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Qo(){return ar===void 0&&(ar=Ja()||Ka()),ar}var ii=require("@dynatrace/devkit");var ei=`<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 qe=null;async function si(e,t,n,r,o){return qe!==null||(l.debug("Authenticate with Dynatrace SSO","AUTH"),qe=Ya(e,t,n,r,o).then(i=>(qe=null,i))),qe}async function Ya(e,t,n,r,o){let i=(0,ti.default)({forceCloseConnections:!0});i.addHttpMethod("PROPFIND");let s=await(0,ii.findPortInRange)("localhost",5343,5363),a=new URL(await Zo(s,o)),c=(0,oi.stringify)({client_id:t,redirect_uri:a.toString(),state:Yo,response_type:"code",code_challenge_method:"S256",code_challenge:Ko,...n?{scope:n.map(y=>y.name).join(" ")}:{}}),p=new URL(e).origin,u,d=new Promise(y=>{u=y});i.get("/auth/login",async(y,v)=>{let{code:g,state:x}=y.query;return l.debug("Received authorized code for oAuth","AUTH"),u({code:g,state:x}),v.code(200).header("Content-Type",(0,ri.contentType)(".html")).send(ei)});let f=b([p,`oauth2/authorize?${c}`]),h=await S(f);if(!h.ok)throw qe=null,l.debug(h.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,...Qo()&&{host:"0.0.0.0"}}),l.debug(`SSO-link ${f}`,"AUTH"),r?await(0,ni.default)(f):l.log(`Open this url to authenticate: ${f}`);let{code:m}=await d;return i.close(),Xo(e,t,m,a)}async function ai(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 S(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 Ee=require("fs"),pr=require("path");var ci=require("lodash");function pi(e,t){return e.length!==t.length?!1:Xa(e,t)}function Xa(e,t){return e.every(n=>typeof n=="object"?!!t.find(r=>(0,ci.isEqual)(n,r)):t.includes(n))}var li=require("jsonwebtoken"),Za="AUTH";function ui(e,t,n,r,o){let i=o?.map(p=>p.name)||[],s=e.scope?.split(" ")||[],a=o?pi(i,s):!0;return e.environment_url===t&&e.oauth_url===n&&e.oauth_client_id===r&&a}function di(e){try{let n=(0,li.decode)(e).exp,r=new Date(n*1e3),o=new Date,s=(r.getTime()-o.getTime())*.001;return s<60?(l.debug(`OAuth2 token expired with a value of: ${s} seconds`,Za),!1):!0}catch{return!1}}async function mi(e){let{currentAuthWorkflow:t,tokenFilePath:n,environmentUrl:r,oauthUrl:o,oauthClientId:i,appScopes:s,tokenInformation:a}=e,c=(0,Ee.existsSync)(n);if(!a||!c)return"invalid";if(a.authentication_flow!==t)return"invalid";let p=ui(a,r,o,i,s),u=di(a.access_token);return p?u?"valid":u?"invalid":"refresh-required":"invalid"}function lr(e,t){(0,Ee.existsSync)((0,pr.dirname)(e))||(0,Ee.mkdirSync)((0,pr.dirname)(e),{recursive:!0}),(0,Ee.writeFileSync)(e,JSON.stringify(t,null,2))}var gt=new Map;async function fi(e,t){if(gt.has(t))return l.debug(`Promise with key ${t} meant to be run once at a time. Initial promise will be returned!`,"promise"),gt.get(t);let n=e();gt.set(t,n);try{return await n}catch(r){throw gt.delete(t),r}finally{gt.delete(t)}}var Qa="dt0s08.dt-app-local";var ec=e=>({openAuthUrl:!0,tokenFilePath:(0,yi.join)(e,".dt-app/.tokens.json")});async function j(e,t){let n=await nc(e,t),r=await mi(n);return r==="refresh-required"?fi(async()=>{try{return await tc(n)}catch(o){return l.debug(`Refresh process for token ${n.tokenType} has failed with: ${o}. Proceeding with SSO flow instead.`,"AUTH"),gi(n,"invalid")}},n.tokenType):gi(n,r)}async function gi(e,t){if(process.env.DT_APP_PLATFORM_TOKEN)return l.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:p,tokenInformation:u,openAuthUrl:d}=e;if(t==="valid")return u.access_token;let f="",h=p;if(n==="automation")try{[h,f]=await hi(h,c,o,s,process.env.DT_APP_OAUTH_CLIENT_SECRET,i,a)}catch(m){let v=(await Promise.all((a||[]).map(g=>hi(h,c,o,s,process.env.DT_APP_OAUTH_CLIENT_SECRET,i,[g]).then(()=>({appScope:g,granted:!0})).catch(()=>({appScope:g,granted:!1}))))).filter(({granted:g})=>!g).map(({appScope:g})=>g.name).join(",");throw v?new Error(`Could not authenticate using the automation token! missing permissions: ${v}`):m}return t==="invalid"&&n==="sso"&&([h,f]=await oc(h,c,o,i,s,a,d)),lr(r,h),f}async function tc(e){let{currentTokenFileContent:t,tokenType:n,environmentUrl:r,oauthUrl:o,oauthClientId:i,tokenFilePath:s}=e,[a,c]=await rc(t,n,r,o,i);return lr(s,a),c}async function nc(e,t){let{tokenType:n,tokenFilePath:r,environmentUrl:o,openAuthUrl:i}={...ec(e.cwd),...e};t&&(t=dr(t,an));let s=e.ssoPublishUrl??await sn(o),a=process.env.DT_APP_OAUTH_CLIENT_ID??Qa,c=ic(),p={},u;return(0,bi.existsSync)(r)&&(p=ne(r),n==="toolkit"?u=p.toolkit_token:u=p.app_token),{currentAuthWorkflow:c,tokenType:n,tokenFilePath:r,environmentUrl:o,openAuthUrl:i,appScopes:t,oauthUrl:s,oauthClientId:a,currentTokenFileContent:p,tokenInformation:u}}async function hi(e,t,n,r,o,i,s){let c={...await Go({clientID:r,clientSecret:o},i,s),environment_url:n,oauth_url:i,oauth_client_id:r,authentication_flow:"automation"};return e=ur(e,c,t),[e,c.access_token]}async function rc(e,t,n,r,o){let i;t==="toolkit"?i=e.toolkit_token:i=e.app_token;let a={...await ai(r,o,i.refresh_token),environment_url:n,oauth_url:r,oauth_client_id:o,authentication_flow:"sso"};return e=ur(e,a,t),[e,a.access_token]}async function oc(e,t,n,r,o,i,s){let c={...await si(r,o,i,s,n),environment_url:n,oauth_url:r,oauth_client_id:o,authentication_flow:"sso"};return e=ur(e,c,t),[e,c.access_token]}function ur(e,t,n){return n==="toolkit"?e.toolkit_token=t:e.app_token=t,e}function dr(e,t){let n=t.concat(e);return[...new Map(n.map(r=>[r.name,r])).values()]}function ic(){return process.env.DT_APP_OAUTH_CLIENT_ID&&process.env.DT_APP_OAUTH_CLIENT_SECRET?"automation":"sso"}var Oe=require("path");var ae=require("path");var L="PLUGIN";function vi(e){return e.plugins.map(t=>sc(t,e.root)).filter(t=>!!t)}function sc(e,t){try{return require(F(e,t)).default}catch(n){l.warn(`Could not require plugin ${e}. It