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.
239 lines (206 loc) • 219 kB
JavaScript
#!/usr/bin/env node
"use strict";var Gm=Object.create;var aa=Object.defineProperty;var zm=Object.getOwnPropertyDescriptor;var Jm=Object.getOwnPropertyNames;var Km=Object.getPrototypeOf,qm=Object.prototype.hasOwnProperty;var Ym=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jm(t))!qm.call(e,o)&&o!==n&&aa(e,o,{get:()=>t[o],enumerable:!(r=zm(t,o))||r.enumerable});return e};var x=(e,t,n)=>(n=e!=null?Gm(Km(e)):{},Ym(t||!e||!e.__esModule?aa(n,"default",{value:e,enumerable:!0}):n,e));var jm=require("dotenv"),Fn=require("path"),Fr=require("fs"),sa=require("os");var xt=require("@dynatrace/openkit-js"),Ma=require("lodash"),Tt=require("fs"),Wr=require("fs/promises"),Na=x(require("http")),_a=x(require("https")),Qe=require("os"),ki=require("path"),Bn=require("url");var re=require("chalk"),Wt=require("lodash");var pe=require("fs"),pa=require("fs/promises"),Dr=require("path"),Xm=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),ca=e=>(e>9?"":"0")+e,Zm=e=>`${e.getFullYear()}-${ca(e.getMonth()+1)}-${ca(e.getDate())}_log.txt`,Qm=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},wi=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},vi=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,Dr.join)(t,".dt-app/logs"),(0,pe.existsSync)(this.logFolder)||(0,pe.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,Dr.join)(this.logFolder,Zm(new Date)),!(0,pe.existsSync)(this.logFile)){let t=(0,pe.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>Xm.test(n));if(t.length>=10){let n=t.map(r=>({path:r,date:Qm(r)})).filter(r=>r.date).sort((r,o)=>r.date.getTime()-o.date.getTime())[0].path;(0,pa.unlink)((0,Dr.join)(this.logFolder,n))}(0,pe.closeSync)((0,pe.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,pe.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 la(e){return gt=new vi,gt.setup(e)}var gt=new wi;var ma=require("os");var Ei=x(require("ora"));var Ti=[],Lt=!1;function ef(e){return new Promise((t,n)=>{Ti.push(async()=>{try{let r=await e();t(r)}catch(r){n(r)}}),tf()})}async function tf(){if(!Lt){for(Lt=!0;Ti.length>0;)await Ti.shift()();Lt=!1}}async function Rr(e){return ef(e)}var In=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",Dn={interval:80},Be=[],ht="idle",Mn=(0,Ei.default)({spinner:{frames:[""],interval:Dn.interval},isSilent:!In}),nf=()=>`
${Be.map(e=>e.getFrame()).join(`
`)}`;function rf(){Mn.text=nf()}var Rn;function of(){In&&ht!=="running"&&!Lt&&(Rn===void 0&&(Rn=setInterval(rf,Dn.interval)),Mn.start(),ht="running")}function ua(){ht==="running"&&(ht="paused",Mn.stop())}function da(){ht==="paused"&&!Lt&&(ht="running",Mn.start())}function xi(){ht="idle",Mn.stop(),Be.forEach(e=>e.abort()),Rn!==void 0&&(clearInterval(Rn),Rn=void 0)}var Ir=class{spinner;constructor(t){this.spinner=(0,Ei.default)({...t,isSilent:!In})}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&&xi()}getFrame(){return this.spinner.frame()}start(t){return t&&(this.text=t),Be.includes(this)||Be.push(this),of(),this}_stop(t,n="abort"){switch(this.text=t??this.text,ua(),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(),da(),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")}},ke={create:(e={})=>new Ir({...e,interval:Dn.interval}),start:(e,t={})=>new Ir({...t,interval:Dn.interval}).start(e),pause:ua,resume:da,reset:xi,successAll:e=>Be.forEach(t=>t.succeed(e)),failAll:e=>Be.forEach(t=>t.fail(e)),disable:()=>{In=!1,xi()},enable:()=>{In=!0},getInterval:()=>Dn.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 fa=`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 Ci=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>ke.create(),disable:ke.disable,start:t=>ke.start(t),pause:ke.pause,resume:ke.resume,abort:ke.reset};disable(){this.disabled=!0,ke.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,re.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ke.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,re.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,re.red)(this._padString(t,0)),"ERROR")}warn(t){let n=`
${(0,re.yellow)("Warning "+(0,Wt.repeat)("─",this.warningBoxSize-8))}
${(0,re.yellow)(this._padString(t))}
${(0,re.yellow)((0,Wt.repeat)("─",this.warningBoxSize))}
`;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=`
${(0,re.magenta)((0,Wt.repeat)("─",this.boxSize))}
${(0,re.magenta)(this._padString(t))}
${(0,re.magenta)((0,Wt.repeat)("─",this.boxSize))}
`;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await la(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):Rr(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ke.getInterval()),this._printToFile(t,n))}_printToFile(t,n){gt.write(`${af().toISOString()} ${n} ${sf(t)}
`)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(r=>`${(0,Wt.repeat)(" ",n)}${r}`).join(ma.EOL)}};function sf(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 af(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var p=new Ci;var ga=require("child_process"),cf=require("commander");function q(e,t){let r={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((o,i)=>{(0,ga.exec)(e,r,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):o(a)})})}var Mr=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0;function ha(e){if(!Mr)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Mr}-${e}.${t}`}var Nn=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0;function ya(e){if(!Nn)return;let t=new URL(Nn).hostname;return`${e}-${t}`}var Ai=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,ye=Nn||Mr||Ai;function yt(e){if(ye)return Ai?Ai.replace(/^https?:\/\//,""):Nn?ya(e):ha(e)}function Nr(e){let t=yt(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}var Vt=require("undici");async function S(e,t){return(0,Vt.fetch)(e,t)}var _n=require("path"),C=(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))(C||{}),uf=`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 _r(e){let t=[e,uf];return new Error(t.filter(Boolean).join(`
`),{cause:259})}function ba(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes(_n.sep)?`${t.split(_n.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function Ze(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(_n.sep)?`${t.replace(/["']/g,"").split(_n.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function b(e){return e instanceof Error?e:new Error(String(e))}var $n="/platform/app-engine/registry/v1",df="APP-REGISTRY";function wa(e,t,n,r,o){let i=JSON.stringify(t,null,2),a=`${e}
HTTP ${n} ${r}
${t?.message??""}`+`
${mf(t,o)}`;return p.debug(`${a}${i}`,df),new Error(a,{cause:266})}function mf(e,t){return e?.details?.constraintViolations?e.details.constraintViolations.reduce((n,r)=>{let o=ff(r,t);return`${n}
${o}`},""):""}function ff(e,t){let{errorCode:n,errorCodeProperties:r,message:o}=e,i=o;if(n&&t){let s=r?.dependency,a=t.find(c=>c.name===s)?.packageJsonDep;if(n==="DependencyUnknown"&&(i=`Unknown endpoint ${s} being used in your dependency ${a}. Please check that dependency.`),n==="DependencyVersionIncompatible"){let c=r?.availableVersion,l=r?.incompatibleVersion;i=`The endpoint ${s} found in your dependency ${a} is using an incompatible version. Please check that dependency and upgrade or downgrade accordingly.${l||c?`
`:""} ${l?`Incompatible version found in your dependencies: ${l}
`:""}${c?`Available version for the endpoint: ${c}`:""}`}}return i}function $r(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(`
`),{cause:266})}async function Ur(e,t,n){try{let r=new URL(e);r.pathname=`${$n}/apps/${n}`,r.searchParams.append("add-fields","manifest,resourceStatus.subResourceStatuses"),r.searchParams.append("latest-app-version","true");let o={headers:{authorization:`Bearer ${t}`}},i=await S(r.toString(),o);return await gf(i)===0?void 0:await i.json()}catch(r){throw $r(b(r).message)}}async function gf(e){if(e.ok&&e.headers.get("content-type")?.includes("text/html"))return 1;if(!e.ok){if(e.status===403)throw _r(e.statusText+`
`);if(e.status===404)return 0;{let t=await e.json(),n=t&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error&&"message"in t.error?t.error.message:"";throw new Error(`Failed fetching app: ${e.status} ${e.statusText} ${n}`,{cause:263})}}if(e.headers.get("content-type")?.includes("text/html"))throw new Error("Fetching the app returned an unexpected response. Please re-check your environment url.",{cause:263})}async function Br(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 $r(b(n).message)}}async function va(e,t,n,r){try{let o=new URL(e);o.pathname=`${$n}/apps`;let i=await S(o.toString(),{method:"POST",body:t,headers:{authorization:`Bearer ${n}`,"content-type":"application/zip"}});if(!i.ok){let s=await i.json();return wa("Failed to install the app",s.error,i.status,i.statusText,r)}}catch(o){return $r(b(o).message)}}async function Ta(e,t,n){try{let r=new URL(e);r.pathname=`${$n}/apps/${t}`;let o=await S(r.toString(),{method:"DELETE",headers:{authorization:`Bearer ${n}`}});if(!o.ok){let i=await o.json();return wa("Failed to uninstall the app",i.error,o.status,o.statusText)}}catch(r){return $r(b(r).message)}}async function xa(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:(p.warn(`The default csp policy from the platform couldn't be applied. App-registry failed with: ${n.status} ${n.statusText}`),{})}function Ht(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 hf(e,t,n,r){let o=await xa(e,n),i=[3e3,3001,3002,3003,3004,3005,3e4,30001,30002,30003,30004,30005],s=i.flatMap(m=>ye?[`https://${yt(m)}`]:[`http://localhost:${m}`,`https://localhost:${m}`]),a=i.flatMap(m=>ye?[Nr(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:l,hostname:u}=Ht(e),d=m=>m.replaceAll("{tenantId}",l).replaceAll("{hostname}",u),f={},g=[...Object.keys(o),...Object.keys(c)];for(let m of g){let y=new Set;for(let w of o[m]??[])y.add(d(w));for(let w of c[m]??[])y.add(d(w));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(w=>w.value)):f[m]=y.map(w=>w.value)}),yf(f)}function yf(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}var Ea=new Map;async function Ca(e,t,n,r){let o=`${e}-${t.join(",")}-${r}`,i=Ea.get(o);if(i)return i;let s=await hf(e,t,n,r);return Ea.set(o,s),s}var Gt=require("fs");function M(e){if(!(0,Gt.existsSync)(e)&&!(0,Gt.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,Gt.readFileSync)(e,"utf-8");return JSON.parse(t)}var Fi=require("jsonwebtoken");var Aa=require("path"),Sa=require("os"),wt=require("fs"),Un=require("fs/promises");var bt=(0,Aa.join)((0,Sa.homedir)(),".dt-app",".session"),bf=19;function Pa(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function Si(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Oa(n)]))}function Oa(e){return e==null?e:Array.isArray(e)?e.map(t=>Oa(t)):typeof e=="object"?Si(e):typeof e=="string"?Ze(e):e}function ka(){return Math.floor(Math.random()*Math.pow(10,18))}function wf(e){return e!==""&&e.length<=bf&&Number.isInteger(Number(e))}function Fa(){try{if(!(0,wt.existsSync)(bt))return;let e=(0,wt.statSync)(bt).birthtime;vf(e)&&(0,wt.unlinkSync)(bt)}catch{p?.debug("Could not identify user uniquely",E)}}function vf(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function Da(e){try{if((0,wt.existsSync)(bt)){let n=(await(0,Un.readFile)(bt)).toString();wf(n)?e=Number(n):await(0,Un.writeFile)(bt,e.toString())}else await(0,Un.writeFile)(bt,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function Ra(e){let t=M(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return Br(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function U(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]=Ze(s):t[i]=!0}return t},{})}function Ia(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function Pi(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 Oi=(0,ki.join)((0,Qe.homedir)(),".dt-app",".uuid"),E="TELEMETRY",Tf=36,zt=process.env.NODE_ENV==="test";function $a(){if(process.env.DT_APP_FORCE_TELEMETRY){zt=!1;return}zt=process.env.NODE_ENV==="test"||parseInt(process.env.DT_APP_DISABLE_TELEMETRY)===1}var jn,H,Ln,Lr,Di=!1,vt;function xf(e,t){p?.debug("Creating a new HTTP and HTTPS interceptor for tracing",E),[Na.default,_a.default].forEach(r=>{let o=r.request;r.request=function(){let i;try{arguments[0]instanceof Bn.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new Bn.URL(arguments[0]):i=new Bn.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return o.apply(null,arguments)}for(let l of t)if(l.startsWith(i.origin))return o.apply(null,arguments);p?.debug(`Tracing request ${i.toString()}`,E);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof Bn.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[xt.webRequestTagHeader]=s.getTag(),s.start();let c=o.apply(null,arguments);return c.once("response",l=>{s.stop(l.statusCode)}),c}})}async function B(e){if(zt){p?.debug("Telemetry disabled",E);return}let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,Tt.readFileSync)((0,ki.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(Fa(),Ln=await Da(ka()),jn=new xt.OpenKitBuilder(t.beaconEndpoint,t.applicationId,Ln).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,Qe.platform)()).withLogLevel(global.VERBOSE_MODE?xt.LogLevel.Info:xt.LogLevel.Error).build(),await new Promise(r=>{jn.waitForInit(o=>{o&&(H=jn.createSession(),Di=!0,xf(H,[t.beaconEndpoint])),r(o)},3e4)})){p?.debug("Successfully initialized OpenKit",E),p?.debug(`Telemetry enabled: Session ID "${Ln}"`,E),vt={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let r="";if((0,Tt.existsSync)(Oi)){let i=(await(0,Wr.readFile)(Oi)).toString();if(i.length===Tf&&(Lr=i,H.identifyUser(i),p?.debug("Identification successful",E)),e?.oauth2File&&(0,Tt.existsSync)(e?.oauth2File)){let s=M(e.oauth2File),a=s?.app_token?.access_token||s?.toolkit_token?.access_token;if(a){let{email:c}=(0,Fi.decode)(a);r=c}}}else if(e?.oauth2File&&(0,Tt.existsSync)(e.oauth2File)){let o=await Ra(e.oauth2File);o?.userId&&(Lr=o.userId,r=o.emailAddress,H.identifyUser(o.userId),(0,Wr.writeFile)(Oi,o.userId),p.debug("Created uuid file to identify user uniquely",E))}vt={...vt,userType:Pi(r)}}catch{p?.debug("Could not identify user uniquely",E)}}else p?.debug("Failed to initialize OpenKit, disabling telemetry",E)}async function j(e){if(!H)return;let t=H.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,Qe.platform)()),t.reportValue("operating_system_version",(0,Qe.version)()),zt)t.reportValue("yarn_version","test");else try{let n=await q("yarn --version");t.reportValue("yarn_version",n)}catch{}if(zt)t.reportValue("npm_version","test");else try{let n=await q("npm --version");t.reportValue("npm_version",n.replace(`
`,""))}catch{}if(zt)t.reportValue("git_version","test");else try{let n=await q("git version");t.reportValue("git_version",n.replace("git version ",""))}catch{}return t}async function X(e,t,n){if(e)try{if(n==="deploy"||n==="publish"){let i=!!t.selfMonitoringAgent;e.reportValue("selfmon_enabled",`${i}`)}if(t.oauth2File&&(0,Tt.existsSync)(t.oauth2File)){let i=M(t.oauth2File),s=i?.app_token?.access_token||i?.toolkit_token?.access_token;if(s){let{email:a}=(0,Fi.decode)(s);e.reportValue("userType",Pi(a))}}if(e.reportValue("app_id",t.appId),e.reportValue("app_version",t.appVersion),!t.environmentUrl.startsWith("http"))return;let{tenant:o}=Ht(t.environmentUrl);e.reportValue("tenant_id",o),t.environmentUrl.includes("dev")?e.reportValue("session_type","dev"):t.environmentUrl.includes("hardening")?e.reportValue("session_type","hardening"):e.reportValue("session_type","prod")}catch{p?.debug("Could not report additional action information",E)}}async function L(e,t){if(e)try{Object.entries(t)?.forEach(n=>{e.reportValue(`command_arg_${(0,Ma.snakeCase)(n[0])}`,Ze(JSON.stringify(n[1])))})}catch{p?.debug("Could not report command args",E)}}function P(e,t){if(!Di||!H||!Ln)return;let n=Si(Pa(e.payload||{})),r=t?.environmentUrl||vt?.environmentUrl||"",o=t?.app?.id||vt.appId||"",i=t?.app?.version||vt.appVersion||"",s=process.version.charAt(0)==="v"?process.version.substring(1):process.version,a=r?{tenantId:Ht(r).tenant,sessionType:Ia(r)}:{tenantId:"",sessionType:""},c={...Lr&&{userId:Lr},userType:vt.userType||""},l={sessionId:Ln.toString(),"event.type":`dt-app.${e["event.category"]}.${e.name}`,"event.category":e["event.category"],"event.provider":"dt-app",operatingSystemVersion:(0,Qe.version)(),nodejsVersion:s,appId:o,appVersion:i,cliVersion:global.DT_APP_VERSION,...a,...c,...n};H.sendBizEvent(l["event.type"],l)}var jr=e=>{let n=e.length;for(let r=e.length-1;r>=0;r--){let o=e.charCodeAt(r);o>127&&o<=2047?n++:o>2047&&o<=65535&&(n+=2),o>=56320&&o<=57343&&r--}return n>=14336};async function Ua(e,t){if(!H)return;let n=H.enterAction(e),{icons:r,packages:o,...i}=t;if(r){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,icons:r};jr(JSON.stringify(s))||H.sendBizEvent("designSystemIconsMetrics",s)}if(o){let s={appId:i.appId,appVersion:i.appVersion,appCommand:i.appCommand,packages:o};jr(JSON.stringify(s))||H.sendBizEvent("dynatracePackageVersions",s)}if(i)if(!jr(JSON.stringify(i)))H.sendBizEvent("designSystemComponentMetrics",i);else{for(i.incomplete=!0;jr(JSON.stringify(i));)delete i.components[Object.keys(i.components).pop()];H.sendBizEvent("designSystemComponentMetrics",i)}return n}async function D(){if(jn)return p?.debug("Closing OpenKit connection",E),new Promise(e=>{jn.shutdown(()=>{p?.debug("Successfully closed OpenKit connection",E),e()}),Di=!1})}var Jt=require("fs"),Wn=require("os"),Ba=require("path"),Ri=(0,Ba.join)((0,Wn.homedir)(),".dt-app","history"),Et,ja="◬";function La(){Wa();let e=process.argv.slice(1);if(!(e.length<1)){e[0].endsWith(".js")&&(e=e.slice(1));try{(0,Jt.appendFileSync)(Ri,`${e.join(" ")}${ja}${Wn.EOL}`)}catch{}}}function Wa(){Et||(Et=(0,Jt.existsSync)(Ri)?(0,Jt.readFileSync)(Ri,"utf-8").split(Wn.EOL):[],Et.length>0&&Et[Et.length-1]===""&&Et.pop())}function Ef(){return Wa(),Et??[]}function Va(){let e=Ef();if(e.length===0)return{command:"(none)"};let t=e[e.length-1],[n]=t.split(ja);return{command:n}}var Ha=require("child_process"),Ga=require("semver");function za(e){let{engines:t}=e;if(t){for(let[n,r]of Object.entries(t))if(n==="node"||n==="npm"){let o=(0,Ha.execSync)(`${n} --version`).toString();if(!(0,Ga.satisfies)(o,r))throw new Error(`Your ${n} version does not satisfy the version requirements of ${r}, installed: ${o}`,{cause:258})}}}var Cf="%";function Ja(){let e=process.argv.indexOf("--verbose");if(e<0)return;let t=process.argv[e+1],n=!t||t.startsWith("-")?Cf:t;global.VERBOSE_MODE=n}function Vr(){console.log(`${global.DT_APP_VERSION}`)}function Ka(...e){let t=process.version.replace("v","").split(".").shift(),n=Number(t);return e.includes(n)?!0:(p.warn(`To prevent potential issues, please use dt-app with the officially supported Node.js version ${e[0]}.`),!1)}var fi=require("commander");var xs=require("path"),hn=require("commander");function oe(e,t){return require.resolve(e,{paths:[t]})}var W=require("path"),wo=require("fs");var Xa=require("path");var et=require("path"),Ct=require("fs"),qa=require("lodash");function Kt(e){return(0,et.basename)(e,(0,et.extname)(e))}function Ya(e){(0,Ct.existsSync)(e)&&(0,Ct.rmSync)(e,{recursive:!0})}function qt(e){(0,Ct.existsSync)(e)||(0,Ct.mkdirSync)(e)}function ie({name:e,suffix:t,allowNested:n=!0,overrideNameWithKebabCase:r=!0}){let{name:o,dir:i,base:s}=(0,et.parse)(e),a=n?o:s,c=`${r?(0,qa.kebabCase)(a):a}.${t}`;return n?(0,et.join)(i,c):c}function Yt(e,t){let n=e.split("/").filter(Boolean),r="../".repeat(n.length);return t.compilerOptions.typeRoots=t.compilerOptions.typeRoots.map(o=>r+o),t}function At(e,t){let n=(0,Xa.join)(e,".dt-app",t);return qt(n),n}var Hr=require("path");function F(){if(__filename.endsWith("bin.js"))return(0,Hr.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Hr.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Hr.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Vn=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}});var fc=require("fs"),nt=x(require("fast-glob")),rt=require("path");function T(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 Ce=require("path");function Hn(e,t){let n=Ce.posix.normalize(Ce.posix.join(t.split(Ce.win32.sep).join(Ce.posix.sep),"/")),r=new RegExp(`^.*?${n}`,"g"),o=Ce.posix.parse(e.split(Ce.win32.sep).join(Ce.posix.sep).replace(r,""));return new URL("http://localhost"+Ce.posix.normalize(Ce.posix.join("/",o.dir,o.name.replace(/\.function$/,"")))).pathname}var zr=x(require("fs"));var Jr=require("path");var Za=x(require("path"));function Xt(){return Za.default.resolve(F(),"utils","snippets")}var Qa=x(require("fastify")),Ii=require("fs"),ec=x(require("ws"));function tc(e){let t={};e.https&&(t={https:{cert:(0,Ii.readFileSync)(e.https.cert),key:(0,Ii.readFileSync)(e.https.key)}});let n=(0,Qa.default)({...t,bodyLimit:50*1048576});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(r,o,i)=>{i(null,o)}),n}function nc({server:e}){return new ec.default.Server({server:e})}function rc(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}function oc(){let e=(0,Jr.resolve)(Xt(),"defaultIndex.snippet.html");return zr.default.readFileSync(e).toString("utf-8")}function Zt(e,t){let{transformSync:n}=require(oe("esbuild",t)),r=(0,Jr.resolve)(Xt(),"sdkWebShim.snippet.ts"),o=zr.default.readFileSync(r,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(o,i).code}function ic(e){let t=(0,Jr.resolve)(Xt(),"selfmon_config.snippet.js");return zr.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}var Gr;async function Kr(e){return Gr||(Gr=await(await S(e)).text(),Gr)}function Qt(e){let t=Nr(e.server.port),n=rc(e.server);return`window.socketUrl = '${t===""?n:t}';`}var sc=x(require("chalk"));var Af=/(?<=(?:\||")cuc=).*?(?=\||")/g,Mi;function ac(e){let t;Mi?t=Mi:(t=Af.exec(e),Mi=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${sc.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function cc(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 Kr(e),0)}catch{return 1}}var le=x(require("chalk"));var Fe={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"};function N(e,t){t&&console.log(`${e}
`),console.log(le.default.hex(Fe.green).bold(`${e}
`))}function O(e){if(e){console.log(`════════
`);return}console.log(le.default.hex(Fe.blue).bold("══")+le.default.hex(Fe.limeGreen).bold("══")+le.default.hex(Fe.green).bold("══")+le.default.hex(Fe.purple).bold("══")+`
`)}function A(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(ue(e,t))}function qr(e,t="white",n){if(n){console.log(e);return}console.log(ue(e,t))}function ue(e,t="white"){return{white:le.default.white,blue:le.default.hex(Fe.blue),green:le.default.hex(Fe.green),purple:le.default.hex(Fe.purple),limeGreen:le.default.hex(Fe.limeGreen),gray:le.default.dim}[t](e)}function en(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+`
`);return}console.log(le.default.hex(Fe.blue)("─".repeat(n))+`
`)}function R(){console.log(`
`)}function tt(e,t=""){let n=(r,o="")=>{let i="│ ",s="├─ ",a="└─ ",c="";return r.items?.forEach((l,u)=>{let d=u===r.items.length-1,f=d?a:s,g=d?" ":i;c+=`${o}${f}${l.name}
`,l.items?.length&&(c+=n(l,o+g))}),c};console.log(n(e,t))}function Yr(){console.log("")}function Gn(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 l=c[0];s.items.push(l.endsWith("widget.tsx")?pc(l,t,n):lc(l,t))}else{let l=s;for(let d=0;d<c.length-1;d++){let f=c[d],g=l.items.find(m=>m.name===f&&Array.isArray(m.items));g||(g={name:f,items:[]},l.items.push(g)),l=g}let u=c[c.length-1];l.items.push(u.endsWith("widget.tsx")?pc(u,t,n):lc(u,t))}}),o.items.push(s)}),o}function pc(e,t,n){let r=[{name:`Local: ${t[e+"_local"]}`}];return n&&r.push({name:`Environment: ${t[e+"_environment"]}`}),{name:e,items:r}}function lc(e,t){return{name:`${e}: ${t[e]}`}}var Ni=x(require("chalk")),Ae=require("path"),zn=require("fs/promises");function je(e){return e.startsWith("../")?e:e.startsWith("./")?e.slice(1):e.startsWith("/")?e:"/"+e}var dc=x(require("fast-glob")),mc=require("fs"),uc={created:Ni.default.green`CREATED:`,updated:"UPDATED:",deleted:Ni.default.red`DELETED:`,copied:"COPIED:"};function St(e){let t={},n={fileExists:r,throwIfFileDoesNotExist:o,getFile:i,getFilePathsByRegex:s,getFileMap:a,getFileName:c,setFile:l,setFiles:u,mapEsbuildOutputFiles:d,deleteFile:f,writeFileToDisc:g,writeFileMapToDisc:m,addAssetFiles:y,resetFileMap:w};return e&&u(e),n;function r(h){let v=je(h);return!!t[v]}function o(h){let v=je(h);if(!r(h))throw P({"event.category":"crash",name:"fileManager.setFile",payload:{error:`Failed to set file ${h} with fileManager.`}}),new Error(`File ${v} does not exist in fileMap!`)}function i(h){return h=je(T(h)),o(h),t[h]}function s(h){return Object.keys(t).filter(v=>v.match(h))}function a(){return t}function c(h){return h=je(T(h)),o(h),(0,Ae.basename)(h)}function l(h,v){h=je(T(h)),t[h]={content:v}}function u(h){for(let v in h)l(v,h[v].content)}function d(h,v,I="dist"){let J=T([v,"dist"]);return(h||[]).forEach(ee=>{let Ee=T(ee.path),yi=T([I,Ee.replace(J,"")]),bi=je(yi);t[bi]={content:Buffer.from(ee.contents)}}),n}function f(h){h=je(T(h)),delete t[h]}async function g(h){h=je(T(h)),o(h),await(0,zn.writeFile)((0,Ae.join)(h),t[h].content)}async function m(h){await Promise.all(Object.entries(t).map(async([v,{content:I,mode:J}])=>{let ee=(Buffer.byteLength(I,"utf8")/Math.pow(2,10)).toFixed(2),Ee=(0,Ae.join)(h,v);return p.debug(`${J!==void 0?uc[J]:uc.created} ${Ee} ${`(${ee} KB)`}`,"FILES"),await(0,zn.mkdir)((0,Ae.dirname)(Ee),{recursive:!0}),(0,zn.writeFile)(Ee,I)}))}async function y(h){for(let v of h.assetConfigs){let I=(0,Ae.isAbsolute)(v.input)?v.input:(0,Ae.join)(h.root,v.input),J=await(0,dc.default)(v.glob,{cwd:I,dot:!0,ignore:v.ignore});for(let ee of J){let Ee=T([h.distDir,v.output,ee]);l(Ee,(0,mc.readFileSync)((0,Ae.join)(I,ee)))}}}function w(){t={}}}var _=St();var Le="documents",Zr="document-types";async function Qr(e,t,n,r){let o=await Kr(t);if(!r.startsWith("dynatrace.")){let i;try{i=ac(o)}catch(l){let u=l instanceof Error?l.message:String(l);p.error(u);return}let s=ic(i),a="./assets/agentConfig.js",c=T([n,a]);_.setFile(c,Buffer.from(s)),e.injectScript(a)}e.injectScript(t)}function de(e){return(0,fc.existsSync)((0,rt.join)(e.cwd,e.functionsFolder))?(0,nt.sync)(T([e.functionsFolder,e.glob]),{cwd:e.cwd}):[]}function gc(e){let t=de({cwd:e.cwd,functionsFolder:e.functionsDir,glob:e.glob});if(!t.length)return;A("Available app functions served from '/api':","green"),R();let n={};t.forEach(o=>{n[o.split("/")[o.split("/").length-1]]=ue(e.url+T(["/api",Hn(o,e.functionsDir)]),"gray")});let r=Gn(t,n);tt(r)}async function hc(e){let t=await(0,nt.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,nt.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;A("Available workflow actions:","green"),R();let r=Sf(e,n,t),o=Gn([...n,...t],r);tt(o)}function Sf(e,t,n){let r={};return t.forEach(o=>{let i=Xr(o),s=(0,rt.basename)(o,".action.ts");r[i]=`${e.url}/api/${s}`}),n.forEach(o=>{let i=Xr(o),s=(0,rt.basename)(o,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;r[`${i}_local`]=ue(a,"gray"),r[`${i}_environment`]=ue(Pf(e.environmentUrl,a,e.locationAppIds),"gray")}),r}function Xr(e){let t=e.split("/");return t[t.length-1]}function Pf(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function nn(e,t){return(await(0,nt.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(r=>(0,rt.join)(e,r))}async function yc(e){let t=await(0,nt.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;A("Available settings widgets:","green"),R();let n={};t.forEach(o=>{let i=Xr(o),s=(0,rt.basename)(i,".widget.tsx"),a=`${e.url}/widgets/settings/${s}`;n[`${i}_local`]=ue(a,"gray")});let r=Gn(t,n,!1);tt(r)}async function bc(e){let t=await(0,nt.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;A("Available documents:","green"),R();let n={};t.forEach(o=>{let i=Xr(o),s=`${e.appId}.${(0,rt.basename)(o).split(".")[0]}`;n[i]=ue(s,"gray")});let r=Gn(t,n);tt(r)}var to=require("lodash"),$i=require("micromatch"),xc=require("fs"),ot=require("path");var wc=require("path");var _i;function me(e){return _i||(_i=require(oe("typescript",e))),_i}function We(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,wc.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function vc(e,t){let n=me(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 eo={noEmit:!0,skipLibCheck:!0};function Tc(e){let{ScriptTarget:t}=me(e);return{ui:{target:t.ES2021,...eo},functions:{target:t.ESNext,...eo},actions:{target:t.ESNext,...eo},widgets:{target:t.ESNext,...eo}}}var no=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`});function Se(e){let{createCompilerHost:t,createProgram:n}=me(e.srcRoot),{tsConfigContents:r,tsConfigFileDiagnostics:o}=Of(e.srcRoot,e.tsConfigFullPath),i={...r.options,...Tc(e.srcRoot)[e.buildType],incremental:!1},s=t(r.options),a=[],c=(0,$i.not)(e.entrypoints,r.raw.exclude).map(f=>(0,ot.isAbsolute)(f)?f:(0,ot.join)(e.srcRoot,f));if(r.options.composite)a=[...new Set([...c,...r.fileNames])];else{let f=r.fileNames.filter(m=>m.endsWith(".d.ts")),g=(0,$i.not)(f,r.raw.exclude).map(m=>(0,ot.isAbsolute)(m)?m:(0,ot.join)(e.srcRoot,m));a=[...new Set([...c,...g])]}let l=n({rootNames:a,options:i,host:s,configFileParsingDiagnostics:o,projectReferences:r.projectReferences}),u=l.emit();return[...l.getSyntacticDiagnostics(),...l.getSemanticDiagnostics(),...l.getConfigFileParsingDiagnostics(),...l.getGlobalDiagnostics(),...l.getDeclarationDiagnostics(),...u.diagnostics].map(f=>vc(f,e.appRoot))}function Of(e,t){let{sys:n,readConfigFile:r,parseJsonConfigFileContent:o}=me(e),i=r(t,c=>(0,xc.readFileSync)(c).toString()),s=[];i.error&&(0,to.has)(i.error.file,"parseDiagnostics")&&(s=(0,to.get)(i.error?.file,"parseDiagnostics"));let a=o(i.config,n,(0,ot.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}function ro(e){return e.filter(t=>t.category==="Error"||!t.filePath||!t.filePath.includes("node_modules"))}function on(e,t){return t?ro(e):e.filter(n=>n.category==="Error")}var Ec=require("@babel/code-frame"),be=require("chalk"),Cc=require("fs"),Ac=x(require("ansi-to-html"));var kf=new Ac.default({});function we(e){for(let t of e)p.info(Ff(t))}var Ff=e=>{let t=e.filePath?`${(0,be.cyan)(e.filePath)}:${(0,be.yellow)(e.line)}:${(0,be.yellow)(e.column)}`:"<no file>",n=e.category==="Error"?(0,be.red)("Error:"):(0,be.yellow)("Warning:"),r=e.code?(0,be.gray)(` ${e.code}`):"",o=`> ${t} - ${n}${r} ${e.text}`,i=(0,be.bold)(`${Sc(e)}`);return`${o}
${i}`},oo=e=>{try{return`<div class="dt-app-codesnippet" style="background-color:#15171B">${kf.toHtml(Sc(e))}</div>`}catch(t){console.error(t)}return""},Sc=e=>{try{if(!e.filePath)return"";let t=(0,Cc.readFileSync)(e.filePath,"utf-8"),n=t==="",r={start:{line:e.line,column:n?1:e.column}};return(0,Ec.codeFrameColumns)(n?" ":t,r,{forceColor:!0})}catch(t){console.error(t)}return""};var Pc=require("fs"),Df="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",De=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(t.path.endsWith(".js"))return{contents:`${(0,Pc.readFileSync)(t.path,"utf8")}
${Df}`,loader:"default"}})}});function io(e){return{sourcemap:e?"inline":!1,includeVendorSourceMaps:!1}}var Oc=e=>`
import Widget from "${e.replace(".tsx","").replaceAll("\\","/")}";
import { _WidgetWrapper as WidgetWrapper } from '@dynatrace-sdk/automation-action-utils';
import { AppRoot } from '@dynatrace/strato-components-preview';
import React from 'react';
import { createRoot } from 'react-dom/client';
const WrappedWidget: React.FunctionComponent =
WidgetWrapper(Widget);
createRoot(document.getElementById('root')!).render(
<AppRoot>
<WrappedWidget />
</AppRoot>
);
`,kc=e=>`
import { runner } from '@dynatrace-sdk/automation-action-utils/actions';
import action from '${e.replace(".ts","").replaceAll("\\","/")}';
export default async function (payload: unknown = undefined) {
return runner(null, payload, action);
}
`;var kt=require("path");var Fc={sourcemap:!1,includeVendorSourceMaps:!1},Rf={sourcemap:!0,includeVendorSourceMaps:!0};function Pt(e){if(e.sourcemaps===void 0)return e.dev?Rf:Fc;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 Fc}}var Jn=require("path");var an=require("path");var sn=require("path"),so=require("fs");var Dc=require("fast-glob"),Rc=require("path");async function Ic(e,t){let n=me(e),r=(0,Dc.sync)(T([e,t.input,t.glob]));return n.createProgram(r,{}).getSourceFiles().map(i=>(0,Rc.relative)(e,i.fileName)).filter(i=>!i.includes("node_modules"))}function ao(e){return e.map(If).filter(t=>!t.filePath?.includes("node_modules/"))}var Mc=e=>We(e,"Error"),If=e=>We(e,"Warning");async function Nc(e,t){let n=e.build.functions,o=(await Ic(e.root,n)).length>0,i=(0,so.existsSync)((0,sn.join)(e.root,t));if(o&&!i)throw new Error(`Failed to build functions
${(0,sn.join)(n.input,n.tsconfig)} must exist, if function source files are present in the ${n.input} directory.
Please create a tsconfig.json file in the ${n.input} directory, or delete the directory.
Example ${(0,sn.join)(n.input,"tsconfig.json")}
${(0,so.readFileSync)((0,sn.join)(F(),"function/template/tsconfig.json"),"utf-8")}:
`,{cause:265});if(!o&&i)throw new Error(`Failed to build functions
${(0,sn.join)(n.input,n.tsconfig)} exists, but no functions were found in the ${n.input} directory.
Please create a function in the ${n.input} directory, or delete the directory.
You can create functions with the generate command:
$ yarn generate:function
`,{cause:265})}function Re(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}async function co(e,t,n){let r=require(oe("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??[],De()]);let s=await o({...Re(),entryPoints:t.entryPoints.map(c=>(0,an.isAbsolute)(c)?c:(0,an.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,an.isAbsolute)(t.tsconfig)?t.tsconfig:(0,an.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 Ui(e,t){let n=Date.now();try{let r=(0,Jn.join)(e.cwd,"dist"),o=await co(r,e,t),i=Date.now(),s=o.warnings.map(l=>We(l,"Warning")).filter(l=>!l.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:o.outputFiles.reduce((l,u)=>{let d=`${Jn.sep}${(0,Jn.join)(a,u.path.replace(r,""))}`;return{...l,[d]:{content:Buffer.from(u.contents)}}},{}),diagnostics:s,duration:i-n,metafile:o.metafile}}catch(r){let o=Date.now();if(Mf(r)){let s=[...r.errors.map(a=>We(a,"Error")),...r.warnings.map(a=>We(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 Mf(e){return typeof e=="object"&&typeof e?.errors<"u"}var fo=require("@dynatrace/runtime-simulator"),Ji=require("chalk"),pn=require("http2"),Zn=require("path");var _c=require("url");async function po({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 _c.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 _r(JSON.stringify(a)??"Could not get token from authentication provider")}catch(s){let a=s,c=a.cause&&typeof a.cause!="number"?a.cause:a;throw p.debug(`Failed to get automation token! Backend responded with: ${c.message}`,"AUTH"),new Error(`${c.message}`,{cause:259})}}var Uc=require("url");var Bi=new Map;async function $c(e){if(Bi.has(e)){let o=Bi.get(e);return p.debug(`Found resolved URL in cache: ${o.toString()}`,"HTTP(S)"),o}p.debug(`Execute GET request without allowing redirection to '${e}'`,"HTTP(S)");let t=await S(e,{redirect:"follow"}),n,r=t.headers.get("location");return r?n=new URL(r):n=new URL(t.url),p.debug(`Resolved URL is ${n.toString()}`,"HTTP(S)"),Bi.set(e,n),n}async function Bc(e){try{let t=new Uc.URL(e);t.pathname="platform/oauth2/authorization/dynatrace-sso",p.debug(`Retrieving SSO-URL for environment '${e}'`,"AUTH");let n=(await $c(t.toString())).origin;return p.debug(`Using SSO-URL '${n}'`,"AUTH"),n}catch(t){let n=b(t);throw p.debug(`SSO-URL for '${e}' could not be processed.`,"AUTH"),p.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 ap=require("path"),cp=require("fs");var Jc=x(require("fastify")),Kc=x(require("open")),qc=require("mime-types"),Yc=require("querystring");var Kn=require("crypto"),lo=[{name:"app-engine:apps:run",comment:"cli-scope"}];function jc(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Nf(e){return(0,Kn.createHash)("sha256").update(e).digest()}var ji=jc((0,Kn.randomBytes)(46)),Lc=jc(Nf(ji)),Wc=(0,Kn.randomBytes)(20).toString("hex");async function Vc(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",ji);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 Hc(e,t){if(ye){let n=`https://${yt(e)}/auth/login`;return`${t}/platform-reserved/app-registry/v1/cde-auth?cde-uri=${encodeURIComponent(n)}`}return`http://localhost:${e}/auth/login`}var Wi=x(require("fs")),Li;function _f(){try{return Wi.default.statSync("/.dockerenv"),!0}catch{return!1}}function $f(){try{return Wi.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Gc(){return Li===void 0&&(Li=_f()||$f()),Li}var Xc=require("@dynatrace/devkit");var zc=`<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