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.
224 lines (202 loc) • 155 kB
JavaScript
"use strict";var gp=Object.create;var yn=Object.defineProperty;var hp=Object.getOwnPropertyDescriptor;var yp=Object.getOwnPropertyNames;var bp=Object.getPrototypeOf,vp=Object.prototype.hasOwnProperty;var wp=(e,t)=>{for(var n in t)yn(e,n,{get:t[n],enumerable:!0})},Ho=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yp(t))!vp.call(e,o)&&o!==n&&yn(e,o,{get:()=>t[o],enumerable:!(r=hp(t,o))||r.enumerable});return e};var x=(e,t,n)=>(n=e!=null?gp(bp(e)):{},Ho(t||!e||!e.__esModule?yn(n,"default",{value:e,enumerable:!0}):n,e)),Tp=e=>Ho(yn({},"__esModule",{value:!0}),e);var gd={};wp(gd,{APP_REGISTRY_BASE_URL:()=>An,DEFAULT_SSO_CLIENT_ID:()=>Gl,DEFAULT_SSO_URL:()=>Vl,DevServer:()=>gr,FileMode:()=>Sr,OperatingSystem:()=>Wr,RequestOptions:()=>gn,Response:()=>hn,_InternalPrepareManifest:()=>Hn,canBeFormatted:()=>Vc,createDtAppConfigBuffer:()=>rp,createProject:()=>Lo,createProjectCommand:()=>nd,executeFunction:()=>od,extractDtAppConfigFromTs:()=>mr,fetch:()=>Wo,getAvailableEmbeddedTemplates:()=>qu,getBearerToken:()=>W,getCompiledFileName:()=>Ku,getDefaultCliOptions:()=>vt,getDtAppFileConfig:()=>fr,getFilesRecursive:()=>wr,getNormalizedBaseHrefWithSlash:()=>Xt,getPackageManager:()=>sp,getSSOUrl:()=>Pn,loadEmbeddedTemplates:()=>Ju,loadTemplates:()=>Pt,mergeOptions:()=>er,mergeRecursively:()=>ve,writeTemplateFiles:()=>Bo});module.exports=Tp(gd);var F=require("path");var L=require("chalk"),Qe=require("lodash");var G=require("fs"),Go=require("fs/promises"),bn=require("path"),xp=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),Vo=e=>(e>9?"":"0")+e,Ep=e=>`${e.getFullYear()}-${Vo(e.getMonth()+1)}-${Vo(e.getDate())}_log.txt`,Sp=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},$r=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},_r=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,bn.join)(t,".dt-app/logs"),(0,G.existsSync)(this.logFolder)||(0,G.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,bn.join)(this.logFolder,Ep(new Date)),!(0,G.existsSync)(this.logFile)){let t=(0,G.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>xp.test(n));if(t.length>=10){let n=t.map(r=>({path:r,date:Sp(r)})).filter(r=>r.date).sort((r,o)=>r.date.getTime()-o.date.getTime())[0].path;(0,Go.unlink)((0,bn.join)(this.logFolder,n))}(0,G.closeSync)((0,G.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,G.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 zo(e){return vn=new _r,vn.setup(e)}var vn=new $r;var Ko=require("os");var Br=x(require("ora"));var Ur=[],Ze=!1;function Pp(e){return new Promise((t,n)=>{Ur.push(async()=>{try{let r=await e();t(r)}catch(r){n(r)}}),Op()})}async function Op(){if(!Ze){for(Ze=!0;Ur.length>0;)await Ur.shift()();Ze=!1}}async function wn(e){return Pp(e)}var At=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",Ct={interval:80},be=[],Me="idle",kt=(0,Br.default)({spinner:{frames:[""],interval:Ct.interval},isSilent:!At}),Cp=()=>`
${be.map(e=>e.getFrame()).join(`
`)}`;function Rp(){kt.text=Cp()}var Rt;function Ap(){At&&Me!=="running"&&!Ze&&(Rt===void 0&&(Rt=setInterval(Rp,Ct.interval)),kt.start(),Me="running")}function qo(){Me==="running"&&(Me="paused",kt.stop())}function Jo(){Me==="paused"&&!Ze&&(Me="running",kt.start())}function Nr(){Me="idle",kt.stop(),be.forEach(e=>e.abort()),Rt!==void 0&&(clearInterval(Rt),Rt=void 0)}var Tn=class{spinner;constructor(t){this.spinner=(0,Br.default)({...t,isSilent:!At})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=be.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),be.splice(t,1)),be.length===0&&Nr()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),be.includes(this)||be.push(this),Ap(),this}_stop(t,n="abort"){switch(this.text=t??this.text,qo(),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(),Jo(),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")}},ce={create:(e={})=>new Tn({...e,interval:Ct.interval}),start:(e,t={})=>new Tn({...t,interval:Ct.interval}).start(e),pause:qo,resume:Jo,reset:Nr,successAll:e=>be.forEach(t=>t.succeed(e)),failAll:e=>be.forEach(t=>t.fail(e)),disable:()=>{At=!1,Nr()},enable:()=>{At=!0},getInterval:()=>Ct.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 Yo=`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 jr=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>ce.create(),disable:ce.disable,start:t=>ce.start(t),pause:ce.pause,resume:ce.resume,abort:ce.reset};disable(){this.disabled=!0,ce.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,L.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ce.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,L.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,L.red)(this._padString(t,0)),"ERROR")}warn(t){let n=`
${(0,L.yellow)("Warning "+(0,Qe.repeat)("─",this.warningBoxSize-8))}
${(0,L.yellow)(this._padString(t))}
${(0,L.yellow)((0,Qe.repeat)("─",this.warningBoxSize))}
`;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=`
${(0,L.magenta)((0,Qe.repeat)("─",this.boxSize))}
${(0,L.magenta)(this._padString(t))}
${(0,L.magenta)((0,Qe.repeat)("─",this.boxSize))}
`;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await zo(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):wn(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ce.getInterval()),this._printToFile(t,n))}_printToFile(t,n){vn.write(`${Fp().toISOString()} ${n} ${kp(t)}
`)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(r=>`${(0,Qe.repeat)(" ",n)}${r}`).join(Ko.EOL)}};function kp(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 Fp(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var l=new jr;var xn=require("fs"),En=require("path"),Zo=x(require("fast-glob"));var Ft=require("path"),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||{}),Dp=`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 Lr(e){let t=[e,Dp];return new Error(t.filter(Boolean).join(`
`),{cause:259})}function Xo(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes(Ft.sep)?`${t.split(Ft.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function Pe(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(Ft.sep)?`${t.replace(/["']/g,"").split(Ft.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function R(e){return e instanceof Error?e:new Error(String(e))}function Qo(e,t){return e.map(n=>Ip(n,t))}async function Ip(e,t){let n=e;if((0,xn.existsSync)((0,En.join)(t.root,t.actionsDir,`${e.name}.action.ts`))||(0,xn.existsSync)((0,En.join)(t.root,t.actionsDir,`${e.name}.resumable.action.ts`))||(0,xn.existsSync)((0,En.join)(t.root,t.actionsDir,`${e.name}.stateful-action.ts`)))return n.isUiAction=!1,n;if(!(await(0,Zo.default)("api/**/"+e.name+"*.ts",{cwd:t.root})).length)throw new Error(e.name+" has no UI and no function implementation!",{cause:257});return n.isUiAction=!1,n}var Ii=x(require("ajv-errors")),eo=x(require("ajv/dist/2019")),Ue=require("chalk"),Qr=require("path");var Wr=(r=>(r.Windows="windows",r.MacOS="macos",r.Other="other",r))(Wr||{});var ei=require("url");var Sn=require("undici");async function S(e,t){return(0,Sn.fetch)(e,t)}async function ti({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 ei.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 Lr(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 et=require("fs");function z(e){if(!(0,et.existsSync)(e)&&!(0,et.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,et.readFileSync)(e,"utf-8");return JSON.parse(t)}var ri=require("url");var Hr=new Map;async function ni(e){if(Hr.has(e)){let o=Hr.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)"),Hr.set(e,n),n}async function Pn(e){try{let t=new ri.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",l.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await ni(t.toString())).origin;return l.debug(`Using SSO-URL '${n}'`,"AUTH"),n}catch(t){let n=R(t);throw l.debug(`SSO-URL for '${e}' could not be processed.`,"AUTH"),l.debug(`Error: ${n.message}`,"AUTH"),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})}}var Ai=require("path"),ki=require("fs");var mi=x(require("fastify")),fi=x(require("open")),gi=require("mime-types"),hi=require("querystring");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]):/,"")}var Dt=require("crypto"),On=[{name:"app-engine:apps:run",comment:"cli-scope"}];function oi(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Mp(e){return(0,Dt.createHash)("sha256").update(e).digest()}var Vr=oi((0,Dt.randomBytes)(46)),ii=oi(Mp(Vr)),si=(0,Dt.randomBytes)(20).toString("hex");async function ai(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",Vr);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()}var Cn=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function ci(e){if(!Cn)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Cn}-${e}.${t}`}var It=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function pi(e){if(!It)return;let t=new URL(It).hostname;return`${e}-${t}`}var Gr=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,oe=It||Cn||Gr;function $e(e){if(oe)return Gr?Gr.replace(/^https?:\/\//,""):It?pi(e):ci(e)}function Rn(e){let t=$e(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}async function li(e,t){if(oe){let n=`https://${$e(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var qr=x(require("fs")),zr;function Up(){try{return qr.default.statSync("/.dockerenv"),!0}catch{return!1}}function Np(){try{return qr.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function ui(){return zr===void 0&&(zr=Up()||Np()),zr}var yi=require("@dynatrace/devkit");var di=`<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 tt=null;async function bi(e,t,n,r,o){return tt!==null||(l.debug("Authenticate with Dynatrace SSO","AUTH"),tt=Bp(e,t,n,r,o).then(i=>(tt=null,i))),tt}async function Bp(e,t,n,r,o){let i=(0,mi.default)({forceCloseConnections:!0});i.addHttpMethod("PROPFIND");let s=await(0,yi.findPortInRange)("localhost",5343,5363),a=new URL(await li(s,o)),c=(0,hi.stringify)({client_id:t,redirect_uri:a.toString(),state:si,response_type:"code",code_challenge_method:"S256",code_challenge:ii,...n?{scope:n.map(y=>y.name).join(" ")}:{}}),p=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 l.debug("Received authorized code for oAuth","AUTH"),d({code:h,state:w}),b.code(200).header("Content-Type",(0,gi.contentType)(".html")).send(di)});let f=v([p,`oauth2/authorize?${c}`]),g=await S(f);if(!g.ok)throw tt=null,l.debug(g.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,...ui()&&{host:"0.0.0.0"}}),l.debug(`SSO-link ${f}`,"AUTH"),r?await(0,fi.default)(f):l.log(`Open this url to authenticate: ${f}`);let{code:m}=await u;return i.close(),ai(e,t,m,a)}async function vi(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 _e=require("fs"),Jr=require("path");var wi=require("lodash");function Ti(e,t){return e.length!==t.length?!1:jp(e,t)}function jp(e,t){return e.every(n=>typeof n=="object"?!!t.find(r=>(0,wi.isEqual)(n,r)):t.includes(n))}var xi=require("jsonwebtoken"),Lp="AUTH";function Ei(e,t,n,r,o){let i=o?.map(p=>p.name)||[],s=e.scope?.split(" ")||[],a=o?Ti(i,s):!0;return e.environment_url===t&&e.oauth_url===n&&e.oauth_client_id===r&&a}function Si(e){try{let n=(0,xi.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`,Lp),!1):!0}catch{return!1}}async function Pi(e){let{currentAuthWorkflow:t,tokenFilePath:n,environmentUrl:r,oauthUrl:o,oauthClientId:i,appScopes:s,tokenInformation:a}=e,c=(0,_e.existsSync)(n);if(!a||!c)return"invalid";if(a.authentication_flow!==t)return"invalid";let p=Ei(a,r,o,i,s),d=Si(a.access_token);return p?d?"valid":d?"invalid":"refresh-required":"invalid"}function Kr(e,t){(0,_e.existsSync)((0,Jr.dirname)(e))||(0,_e.mkdirSync)((0,Jr.dirname)(e),{recursive:!0}),(0,_e.writeFileSync)(e,JSON.stringify(t,null,2))}var Mt=new Map;async function Oi(e,t){if(Mt.has(t))return l.debug(`Promise with key ${t} meant to be run once at a time. Initial promise will be returned!`,"promise"),Mt.get(t);let n=e();Mt.set(t,n);try{return await n}catch(r){throw Mt.delete(t),r}finally{Mt.delete(t)}}var Yr="dt0s08.dt-app-local";var Wp=e=>({openAuthUrl:!0,tokenFilePath:(0,Ai.join)(e,".dt-app/.tokens.json")});async function W(e,t){let n=await Vp(e,t),r=await Pi(n);return r==="refresh-required"?Oi(async()=>{try{return await Hp(n)}catch(o){return l.debug(`Refresh process for token ${n.tokenType} has failed with: ${o}. Proceeding with SSO flow instead.`,"AUTH"),Ci(n,"invalid")}},n.tokenType):Ci(n,r)}async function Ci(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:d,openAuthUrl:u}=e;if(t==="valid")return d.access_token;let f="",g=p;if(n==="automation")try{[g,f]=await Ri(g,c,o,s,process.env.DT_APP_OAUTH_CLIENT_SECRET,i,a)}catch(m){let b=(await Promise.all((a||[]).map(h=>Ri(g,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! missing permissions: ${b}`):m}return t==="invalid"&&n==="sso"&&([g,f]=await zp(g,c,o,i,s,a,u)),Kr(r,g),f}async function Hp(e){let{currentTokenFileContent:t,tokenType:n,environmentUrl:r,oauthUrl:o,oauthClientId:i,tokenFilePath:s}=e,[a,c]=await Gp(t,n,r,o,i);return Kr(s,a),c}async function Vp(e,t){let{tokenType:n,tokenFilePath:r,environmentUrl:o,openAuthUrl:i}={...Wp(e.cwd),...e};t&&(t=Zr(t,On));let s=e.ssoPublishUrl??await Pn(o),a=e.customClientId??process.env.DT_APP_OAUTH_CLIENT_ID??Yr,c=qp(),p={},d;return(0,ki.existsSync)(r)&&(p=z(r),n==="toolkit"?d=p.toolkit_token:d=p.app_token),{currentAuthWorkflow:c,tokenType:n,tokenFilePath:r,environmentUrl:o,openAuthUrl:i,appScopes:t,oauthUrl:s,oauthClientId:a,currentTokenFileContent:p,tokenInformation:d}}async function Ri(e,t,n,r,o,i,s){let c={...await ti({clientID:r,clientSecret:o},i,s),environment_url:n,oauth_url:i,oauth_client_id:r,authentication_flow:"automation"};return e=Xr(e,c,t),[e,c.access_token]}async function Gp(e,t,n,r,o){let i;t==="toolkit"?i=e.toolkit_token:i=e.app_token;let a={...await vi(r,o,i.refresh_token),environment_url:n,oauth_url:r,oauth_client_id:o,authentication_flow:"sso"};return e=Xr(e,a,t),[e,a.access_token]}async function zp(e,t,n,r,o,i,s){let c={...await bi(r,o,i,s,n),environment_url:n,oauth_url:r,oauth_client_id:o,authentication_flow:"sso"};return e=Xr(e,c,t),[e,c.access_token]}function Xr(e,t,n){return n==="toolkit"?e.toolkit_token=t:e.app_token=t,e}function Zr(e,t){let n=t.concat(e);return[...new Map(n.map(r=>[r.name,r])).values()]}function qp(){return process.env.DT_APP_OAUTH_CLIENT_ID&&process.env.DT_APP_OAUTH_CLIENT_SECRET?"automation":"sso"}var An="/platform/app-engine/registry/v1";function Jp(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(`
`),{cause:266})}async function kn(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 Jp(R(n).message)}}async function Fi(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}`),{})}var H="contains unknown property ${0#}. Please check if there is a typo or remove it",Kp={properties:{id:{type:"string",pattern:"^[a-z0-9]+(\\.[a-z0-9]+)*$",maxLength:50},name:{type:"string",maxLength:40},selfMonitoringAgent:{description:"Agentless real user monitoring url",type:"string"}}},Mi={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://example.com/app.manifest.default.schema.json",type:"object",properties:{id:{type:"string",pattern:"^[a-z0-9\\.]*$"},name:{type:"string"},description:{type:"string"},version:{type:"string"},icon:{nullable:!0,type:"string",format:"relative-path",errorMessage:"must be a relative path"}},additionalProperties:!0,required:["id","name","version","description"]},Yp={errorMessage:{required:{name:"must contain property 'name'. Please specify 'app.name' in your 'app.config.(json|js|ts)' file",description:"must contain property 'description'. Please specify 'app.description' in your 'app.config.(json|js|ts)' file",version:"must contain property 'version'. Please specify 'app.version' in your 'app.config.(json|js|ts)' file"},properties:{id:`is invalid. There could be multiple reasons for that:
If unspecified, the app ID is generated by joining all segments of 'app.name' (separated with a dot). In this case, please check 'app.name' for special characters or try a shorter name.
If you specified an id, please make sure it does not contain special characters or try a shorter one.`,version:"must be a valid semver (MAJOR.MINOR.PATCH)"}}},$t={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://example.com/plugins.schema",type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:{not:!0,errorMessage:H},properties:{name:{type:"string"},setup:{}}}},_t={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://example.com/sourcemap.schema",enum:[!0,!1,"all"],errorMessage:"must be a boolean value or 'all'"},Di={$schema:"https://json-schema.org/draft/2019-09/schema",$id:"https://example.com/assets.schema",type:"array",items:{type:"object",additionalProperties:{not:!0,errorMessage:H},properties:{glob:{type:"string",format:"valid-glob",errorMessage:"has to be a glob pattern"},ignore:{type:"array",items:{type:"string",format:"valid-glob",errorMessage:"has to be a glob pattern"}},input:{type:"string"},output:{type:"string",format:"relative-path",errorMessage:"must be a relative path"}},required:["glob","ignore","input","output"],errorMessage:{required:{glob:"must contain property 'glob'",ignore:"must contain property 'ignore'",input:"must contain property 'input'",output:"must contain property 'output'"}}}};function Xp(e){let t=new eo.default({allErrors:!0,formats:{"absolute-path":{type:"string",validate:r=>(0,Qr.isAbsolute)(r)},"relative-path":{type:"string",validate:r=>!(0,Qr.isAbsolute)(r)},"valid-glob":{type:"string",validate:r=>r!==null&&r.length>0}},strict:!1});(0,Ii.default)(t),t.addSchema($t),t.addSchema(Di),t.addSchema(e),t.addSchema(_t);let n={type:"object",required:["root","environmentUrl","distDir","injectSdk","dryRun","deploy","app","server","build","plugins"],additionalProperties:{not:!0,errorMessage:H},errorMessage:{required:{environmentUrl:"must contain a valid 'environmentUrl'. Please specify one in your 'app.config.(json|js|ts)' file"}},properties:{executionMode:{type:"string"},appFunctionsBuildPlatform:{type:"string"},root:{type:"string",format:"absolute-path",errorMessage:"must be an absolute path"},environmentUrl:{type:"string"},oauthClientId:{type:"string"},oauthClientSecret:{type:"string"},oauthScopes:{type:"array",items:{type:"string"}},distDir:{type:"string",format:"relative-path",errorMessage:"must be a relative path"},oauth2File:{type:"string"},icon:{nullable:!0,type:"string",format:"relative-path",errorMessage:"must be a relative path"},injectSdk:{type:"boolean"},dryRun:{type:"boolean"},noLiveReload:{type:"boolean"},deploy:{type:"object",required:["build"],additionalProperties:{not:!0,errorMessage:H},properties:{build:{type:"boolean"},manifest:{type:"string",nullable:!0}}},server:{type:"object",required:["open","port","host"],additionalProperties:{not:!0,errorMessage:H},properties:{open:{type:"boolean"},port:{type:"number"},host:{type:"string"},showWarnings:{type:"boolean"},enableCSP:{type:"boolean"},https:{nullable:!0,type:"object",required:["key","cert"],properties:{key:{type:"string"},cert:{type:"string"}}}}},dev:{type:"object",required:["fileWatcher"],additionalProperties:{not:!0,errorMessage:H},properties:{fileWatcher:{type:"object",required:["ignore"],additionalProperties:{not:!0,errorMessage:H},properties:{ignore:{type:"array",items:{type:"string",format:"valid-glob",errorMessage:"has to be a glob pattern"}},include:{type:"array",items:{type:"string",format:"valid-glob",errorMessage:"has to be a glob pattern"}}}}}},app:{$ref:e.$id},build:{type:"object",required:["index","mode","baseHref","ui","functions"],additionalProperties:{not:!0,errorMessage:H},properties:{index:{type:"string",format:"relative-path",errorMessage:"must be a relative path"},sourceRoot:{type:"string"},sourceMaps:{$ref:_t.$id},mode:{type:"string"},settingsPath:{type:"string"},baseHref:{type:"string"},typeCheck:{type:"boolean"},ui:{type:"object",required:["entryPoint","tsconfig","assets"],additionalProperties:{not:!0,errorMessage:H},properties:{entryPoint:{type:"string",format:"relative-path",errorMessage:'must be a relative path to a TypeScript file inside the "src" directory',pattern:"^src\\/|\\\\.*|ui\\/|\\\\.*"},additionalEntryPoints:{type:"array",items:{type:"string",format:"relative-path",errorMessage:'must be a relative path to a TypeScript file inside the "src" directory',pattern:"^src\\/|\\\\.*"}},sourceMaps:{$ref:_t.$id},tsconfig:{type:"string",format:"relative-path",errorMessage:"must be a relative path"},plugins:{$ref:$t.$id},assets:{$ref:Di.$id}}},functions:{type:"object",required:["input","glob","tsconfig"],additionalProperties:{not:!0,errorMessage:H},properties:{input:{type:"string",format:"relative-path",errorMessage:"must be a relative path"},glob:{type:"string",format:"valid-glob",errorMessage:"has to be a glob pattern"},sourceMaps:{$ref:_t.$id},tsconfig:{type:"string",format:"relative-path",errorMessage:"must be a relative path"},plugins:{$ref:$t.$id}}},api:{type:"object",additionalProperties:{not:!0,errorMessage:H},properties:{sourceMaps:{$ref:_t.$id}}},widgets:{type:"object",required:[],additionalProperties:{not:!0,errorMessage:H},properties:{plugins:{$ref:$t.$id}}},selfMonitoringAgent:{type:"string"},actions:{type:"object",required:[],additionalProperties:{not:!0,errorMessage:H},properties:{plugins:{$ref:$t.$id}}},dynatraceDependencies:{type:"object",required:[],additionalProperties:{not:!0,errorMessage:H},properties:{addOrOverride:{type:"object",required:[],nullable:!0,additionalProperties:{type:"string"}},ignore:{nullable:!0,type:"array",items:{type:"string"}}}}}},plugins:{type:"array",items:{type:"string"}}}};return t.compile(n)}async function $i(e,t="default"){let n=Qp(e),r=n&&t==="deployment"?await Zp({...n,oauthClientSecret:e.oauthClientSecret,oauthClientId:e.oauthClientId,scopes:e.app.scopes,open:e?.server?.open}):Mi,o=Xp(ve(ve(r,Kp),Yp));if(t==="none"||o(e))return e;for(let i of o.errors)l.info(el(i));throw new Error("App config validation failed",{cause:264})}async function Zp(e){try{let t=await W({tokenType:"toolkit",cwd:e.root,environmentUrl:e.environmentUrl,openAuthUrl:e.open,tokenFilePath:e.oauth2File}),n=await S(`${e.environmentUrl}${An}/app.manifest.schema.json`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(n.ok){let r=await n.json();return delete r.properties.documents,delete r.properties.icon,r.additionalProperties=!0,r}l.debug(`Error code: ${n.status}. Error message: ${n.statusText}. Request Url: ${n.url}`,"DEPLOY")}catch{}return l.info(`> ${Ue.bold`CLI configuration`}: ${Ue.yellow`warning`} Could not fetch JSON schema for validating option 'app' from specified environment '${e.environmentUrl}'. Validation for this option can not be performed according to this environment.`),Mi}function Qp(e){let t={environmentUrl:e.environmentUrl,appName:e.app?e.app.name:void 0,root:e.root,oauth2File:e.oauth2File},n={type:"object",required:["root","environmentUrl","appName"],additionalProperties:!1,properties:{root:{type:"string"},environmentUrl:{type:"string"},oauth2File:{type:"string"},appName:{type:"string"}}};if(new eo.default().compile(n)(t))return t}function el(e){let t=Ue.red`error:`,n=e.instancePath??"";e.schemaPath&&e.schemaPath.indexOf("additionalProperties")>=0&&n.indexOf("app")<0&&(n=n?.substr(0,e.instancePath.lastIndexOf("/")));let r=n?n.split("/").reduce((i,s)=>i?isNaN(+s)?`${i}.${s}`:`${i}[${s}]`:s):"CliOptions",o=e.message?e.message.replace(/"/gi,"'"):"";return`> ${Ue.bold`CLI configuration`}: ${t} '${r}' ${o}.`}function _(e,t){return require.resolve(e,{paths:[t]})}var Y="PLUGIN";function _i(e){return e.plugins.map(t=>tl(t,e.root)).filter(t=>!!t)}function tl(e,t){try{return require(_(e,t)).default}catch(n){l.warn(`Could not require plugin ${e}. It will be ignored.`),l.debug(R(n).toString(),Y)}}var to={"before-build":[],"before-serve":[]};async function nl(e,t){for(let n of rl(e)){l.debug(`Running '${e}' hook of plugin '${n.name}'...`,Y);try{await n.callBack(...t)}catch(r){l.error(`An error occurred during the '${e}' hook of plugin '${n.name}':
${R(r).toString()}`);continue}l.debug(`Finished '${e}' hook of plugin '${n.name}'.`,Y)}}function rl(e){return to[e]}function Ui(e){let t={"before-build":[],"before-serve":[]},n={beforeBuild(r){t["before-build"].push({name:e.name,callBack:r})},beforeServe(r){t["before-serve"].push({name:e.name,callBack:r})}};try{e.setup(n)}catch(r){l.error(`An error occurred during the setup of plugin '${e.name}':
${R(r).toString()}`);return}Object.keys(t).forEach(r=>{ol(r)&&to[r].push(...t[r])})}function ol(e){return["before-build","before-serve"].includes(e)}function il(e){for(let t of e)Ui(t)}var Fn={registeredHooks:to,register:Ui,registerAll:il,invoke:nl};var Mn=x(require("fs"));var $n=require("path");var Dn=require("path");function N(){if(__filename.endsWith("bin.js"))return(0,Dn.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Dn.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Dn.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Ni=x(require("path"));function nt(){return Ni.default.resolve(N(),"utils","snippets")}var Bi=x(require("fastify")),no=require("fs"),ji=x(require("ws"));function Li(e){let t={};e.https&&(t={https:{cert:(0,no.readFileSync)(e.https.cert),key:(0,no.readFileSync)(e.https.key)}});let n=(0,Bi.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(r,o,i)=>{i(null,o)}),n}function Wi({server:e}){return new ji.default.Server({server:e})}function Hi(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}function Vi(){let e=(0,$n.resolve)(nt(),"defaultIndex.snippet.html");return Mn.default.readFileSync(e).toString("utf-8")}function rt(e,t){let{transformSync:n}=require(_("esbuild",t)),r=(0,$n.resolve)(nt(),"sdkWebShim.snippet.ts"),o=Mn.default.readFileSync(r,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(o,i).code}function Gi(e){let t=(0,$n.resolve)(nt(),"selfmon_config.snippet.js");return Mn.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var In;async function _n(e){return In||(In=await(await S(e)).text(),In)}function ot(e){let t=Rn(e.server.port),n=Hi(e.server);return`window.socketUrl = '${t===""?n:t}';`}var zi=x(require("chalk"));var sl=/(?<=(?:\||")cuc=).*?(?=\||")/g,ro;function qi(e){let t;ro?t=ro:(t=sl.exec(e),ro=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${zi.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function Ji(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 _n(e),0)}catch{return 1}}var bt=require("chalk");var Gt=x(require("fast-glob")),Bs=require("lodash"),K=require("path");var Es=require("fs"),Ce=x(require("fast-glob")),Re=require("path");var ie=require("path");function it(e,t){let n=ie.posix.normalize(ie.posix.join(t.split(ie.win32.sep).join(ie.posix.sep),"/")),r=new RegExp(`^.*?${n}`,"g"),o=ie.posix.parse(e.split(ie.win32.sep).join(ie.posix.sep).replace(r,""));return new URL("http://localhost"+ie.posix.normalize(ie.posix.join("/",o.dir,o.name.replace(/\.function$/,"")))).pathname}var q=x(require("chalk"));var pe={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function oo(e,t){t&&console.log(`${e}
`),console.log(q.default.hex(pe.green).bold(`${e}
`))}function Nt(e){if(e){console.log(`════════
`);return}console.log(q.default.hex(pe.blue).bold("══")+q.default.hex(pe.limeGreen).bold("══")+q.default.hex(pe.green).bold("══")+q.default.hex(pe.purple).bold("══")+`
`)}function E(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(J(e,t))}function Xi(e,t="white",n){if(n){console.log(e);return}console.log(J(e,t))}function J(e,t="white"){return{white:q.default.white,blue:q.default.hex(pe.blue),green:q.default.hex(pe.green),purple:q.default.hex(pe.purple),limeGreen:q.default.hex(pe.limeGreen),gray:q.default.dim}[t](e)}function st(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+`
`);return}console.log(q.default.hex(pe.blue)("─".repeat(n))+`
`)}function D(){console.log(`
`)}function Ne(e,t=""){let n=(r,o="")=>{let i="│ ",s="├─ ",a="└─ ",c="";return r.items?.forEach((p,d)=>{let u=d===r.items.length-1,f=u?a:s,g=u?" ":i;c+=`${o}${f}${p.name}
`,p.items?.length&&(c+=n(p,o+g))}),c};console.log(n(e,t))}function Zi(){console.log("")}function Bt(e,t,n=!0){let r={};e.forEach(i=>{let a=i.split("/")[0];r[a]||(r[a]=[]),r[a].push(i)});let o={items:[]};return Object.keys(r).forEach(i=>{let s={name:i,items:[]};r[i].forEach(a=>{let c=a.split("/");if(c.shift(),c.length!==0)if(c.length===1){let p=c[0];s.items.push(p.endsWith("widget.tsx")?Ki(p,t,n):Yi(p,t))}else{let p=s;for(let u=0;u<c.length-1;u++){let f=c[u],g=p.items.find(m=>m.name===f&&Array.isArray(m.items));g||(g={name:f,items:[]},p.items.push(g)),p=g}let d=c[c.length-1];p.items.push(d.endsWith("widget.tsx")?Ki(d,t,n):Yi(d,t))}}),o.items.push(s)}),o}function Ki(e,t,n){let r=[{name:`Local: ${t[e+"_local"]}`}];return n&&r.push({name:`Environment: ${t[e+"_environment"]}`}),{name:e,items:r}}function Yi(e,t){return{name:`${e}: ${t[e]}`}}var po=x(require("chalk")),se=require("path"),Vt=require("fs/promises");function we(e){return e.startsWith("../")?e:e.startsWith("./")?e.slice(1):e.startsWith("/")?e:"/"+e}var He=require("@dynatrace/openkit-js"),ms=require("lodash"),at=require("fs"),Bn=require("fs/promises"),fs=x(require("http")),gs=x(require("https")),Oe=require("os"),ao=require("path"),Lt=require("url");var Qi=require("child_process"),al=require("commander");function V(e,t){let r={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((o,i)=>{(0,Qi.exec)(e,r,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):o(a)})})}function Be(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 cl(e,t,n,r){let o=await Fi(e,n),i=[3e3,3001,3002,3003,3004,3005,3e4,30001,30002,30003,30004,30005],s=i.flatMap(m=>oe?[`https://${$e(m)}`]:[`http://localhost:${m}`,`https://localhost:${m}`]),a=i.flatMap(m=>oe?[Rn(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:d}=Be(e),u=m=>m.replaceAll("{tenantId}",p).replaceAll("{hostname}",d),f={},g=[...Object.keys(o),...Object.keys(c)];for(let m of g){let y=new Set;for(let b of o[m]??[])y.add(u(b));for(let b of c[m]??[])y.add(u(b));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(b=>b.value)):f[m]=y.map(b=>b.value)}),pl(f)}function pl(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var es=new Map;async function ts(e,t,n,r){let o=`${e}-${t.join(",")}-${r}`,i=es.get(o);if(i)return i;let s=await cl(e,t,n,r);return es.set(o,s),s}var hs=require("jsonwebtoken");var ns=require("path"),rs=require("os"),Le=require("fs"),jt=require("fs/promises");var je=(0,ns.join)((0,rs.homedir)(),".dt-app",".session"),ll=19;function os(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function io(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,is(n)]))}function is(e){return e==null?e:Array.isArray(e)?e.map(t=>is(t)):typeof e=="object"?io(e):typeof e=="string"?Pe(e):e}function ss(){return Math.floor(Math.random()*Math.pow(10,18))}function ul(e){return e!==""&&e.length<=ll&&Number.isInteger(Number(e))}function as(){try{if(!(0,Le.existsSync)(je))return;let e=(0,Le.statSync)(je).birthtime;dl(e)&&(0,Le.unlinkSync)(je)}catch{l?.debug("Could not identify user uniquely",O)}}function dl(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function cs(e){try{if((0,Le.existsSync)(je)){let n=(await(0,jt.readFile)(je)).toString();ul(n)?e=Number(n):await(0,jt.writeFile)(je,e.toString())}else await(0,jt.writeFile)(je,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function ps(e){let t=z(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return kn(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function ls(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]=Pe(s):t[i]=!0}return t},{})}function us(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function ds(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 so=(0,ao.join)((0,Oe.homedir)(),".dt-app",".uuid"),O="TELEMETRY",ml=36,Un=process.env.NODE_ENV==="test";var Wt,B,Ht,Nn,co=!1,We;function fl(e,t){l?.debug("Creating a new HTTP and HTTPS interceptor for tracing",O),[fs.default,gs.default].forEach(r=>{let o=r.request;r.request=function(){let i;try{arguments[0]instanceof Lt.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new Lt.URL(arguments[0]):i=new Lt.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return o.apply(null,arguments)}for(let p of t)if(p.startsWith(i.origin))return o.apply(null,arguments);l?.debug(`Tracing request ${i.toString()}`,O);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof Lt.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[He.webRequestTagHeader]=s.getTag(),s.start();let c=o.apply(null,arguments);return c.once("response",p=>{s.stop(p.statusCode)}),c}})}async function ys(e){if(Un){l?.debug("Telemetry disabled",O);return}let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,at.readFileSync)((0,ao.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(as(),Ht=await cs(ss()),Wt=new He.OpenKitBuilder(t.beaconEndpoint,t.applicationId,Ht).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,Oe.platform)()).withLogLevel(global.VERBOSE_MODE?He.LogLevel.Info:He.LogLevel.Error).build(),await new Promise(r=>{Wt.waitForInit(o=>{o&&(B=Wt.createSession(),co=!0,fl(B,[t.beaconEndpoint])),r(o)},3e4)})){l?.debug("Successfully initialized OpenKit",O),l?.debug(`Telemetry enabled: Session ID "${Ht}"`,O),We={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let r="";if((0,at.existsSync)(so)){let i=(await(0,Bn.readFile)(so)).toString();if(i.length===ml&&(Nn=i,B.identifyUser(i),l?.debug("Identification successful",O)),e?.oauth2File&&(0,at.existsSync)(e?.oauth2File)){let s=z(e.oauth2File),a=s?.app_token?.access_token||s?.toolkit_token?.access_token;if(a){let{email:c}=(0,hs.decode)(a);r=c}}}else if(e?.oauth2File&&(0,at.existsSync)(e.oauth2File)){let o=await ps(e.oauth2File);o?.userId&&(Nn=o.userId,r=o.emailAddress,B.identifyUser(o.userId),(0,Bn.writeFile)(so,o.userId),l.debug("Created uuid file to identify user uniquely",O))}We={...We,userType:ds(r)}}catch{l?.debug("Could not identify user uniquely",O)}}else l?.debug("Failed to initialize OpenKit, disabling telemetry",O)}async function bs(e){if(!B)return;let t=B.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,Oe.platform)()),t.reportValue("operating_system_version",(0,Oe.version)()),Un)t.reportValue("yarn_version","test");else try{let n=await V("yarn --version");t.reportValue("yarn_version",n)}catch{}if(Un)t.reportValue("npm_version","test");else try{let n=await V("npm --version");t.reportValue("npm_version",n.replace(`
`,""))}catch{}if(Un)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 vs(e,t){if(e)try{Object.entries(t)?.forEach(n=>{e.reportValue(`command_arg_${(0,ms.snakeCase)(n[0])}`,Pe(JSON.stringify(n[1])))})}catch{l?.debug("Could not report command args",O)}}function j(e,t){if(!co||!B||!Ht)return;let n=io(os(e.payload||{})),r=t?.environmentUrl