UNPKG

dt-app

Version:

The Dynatrace App Toolkit is a tool you can use from your command line to create, develop, and deploy apps on your Dynatrace environment.

81 lines (62 loc) 286 kB
#!/usr/bin/env node "use strict";var Dw=Object.create;var tc=Object.defineProperty;var Rw=Object.getOwnPropertyDescriptor;var Ow=Object.getOwnPropertyNames;var kw=Object.getPrototypeOf,Fw=Object.prototype.hasOwnProperty;var g=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var nc=(e,t)=>{for(var n in t)tc(e,n,{get:t[n],enumerable:!0})},Iw=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ow(t))!Fw.call(e,r)&&r!==n&&tc(e,r,{get:()=>t[r],enumerable:!(o=Rw(t,r))||o.enumerable});return e};var A=(e,t,n)=>(n=e!=null?Dw(kw(e)):{},Iw(t||!e||!e.__esModule?tc(n,"default",{value:e,enumerable:!0}):n,e));async function Wl(e){return Dn=new rc,Dn.setup(e)}var Ne,Ll,hi,Nw,jl,_w,Mw,oc,rc,Dn,ic=g(()=>{"use strict";Ne=require("fs"),Ll=require("fs/promises"),hi=require("path"),Nw=new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}_log.txt/),jl=e=>(e>9?"":"0")+e,_w=e=>`${e.getFullYear()}-${jl(e.getMonth()+1)}-${jl(e.getDate())}_log.txt`,Mw=e=>{try{let t=e.split("-");return new Date(Number(t[0]),Number(t[1]),Number(t[2].split("_")[0]))}catch{return}},oc=class{async setup(t){return Promise.resolve()}write(t){}getLogFile(){return""}},rc=class{logFolder;logFile;stream;async setup(t){this.logFolder=(0,hi.join)(t,".dt-app/logs"),(0,Ne.existsSync)(this.logFolder)||(0,Ne.mkdirSync)(this.logFolder,{recursive:!0}),await this.rotate()}async rotate(){if(this.logFile=(0,hi.join)(this.logFolder,_w(new Date)),!(0,Ne.existsSync)(this.logFile)){let t=(0,Ne.readdirSync)(this.logFolder).map(n=>n.trim()).filter(n=>Nw.test(n));if(t.length>=10){let n=t.map(o=>({path:o,date:Mw(o)})).filter(o=>o.date).sort((o,r)=>o.date.getTime()-r.date.getTime())[0].path;(0,Ll.unlink)((0,hi.join)(this.logFolder,n))}(0,Ne.closeSync)((0,Ne.openSync)(this.logFile,"w"))}await new Promise(t=>{this.stream=(0,Ne.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}};Dn=new oc});function $w(e){return new Promise((t,n)=>{sc.push(async()=>{try{let o=await e();t(o)}catch(o){n(o)}}),Uw()})}async function Uw(){if(!po){for(po=!0;sc.length>0;)await sc.shift()();po=!1}}async function yi(e){return $w(e)}var sc,po,bi=g(()=>{"use strict";sc=[],po=!1});function jw(){ar.text=Bw()}function Lw(){sr&&mt!=="running"&&!po&&(G.length>=2?(Kt===void 0&&(Kt=setInterval(jw,ir.interval)),ar.start(),mt="running"):G.length===1&&(G[0].startOraSpinner(),mt="running"))}function Vl(){mt==="running"&&(mt="paused",G.length>=2?ar.stop():G.length===1&&G[0].stopOraSpinner())}function Hl(){mt==="paused"&&!po&&(mt="running",G.length>=2?ar.start():G.length===1&&G[0].startOraSpinner())}function ac(){mt="idle",G.length>=2?ar.stop():G.length===1&&G[0].stopOraSpinner(),G.forEach(e=>e.abort()),Kt!==void 0&&(clearInterval(Kt),Kt=void 0)}var cc,sr,ir,G,mt,ar,Bw,Kt,wi,ft,zl=g(()=>{"use strict";cc=A(require("ora"));bi();sr=process.env.DT_APP_DEACTIVATE_SPINNER!=="true",ir={interval:80},G=[],mt="idle",ar=(0,cc.default)({spinner:{frames:[""],interval:ir.interval},isSilent:!sr}),Bw=()=>` ${G.map(e=>e.getFrame()).join(` `)}`;wi=class{spinner;constructor(t){this.spinner=(0,cc.default)({...t,isSilent:!sr})}get text(){return this.spinner.text}set text(t){this.spinner.text=t}cleanup(){let t=G.indexOf(this);t>-1&&(this.spinner.isSpinning&&this.spinner.stop(),G.splice(t,1)),G.length===0&&ac()}startOraSpinner(){this.spinner.isSpinning||this.spinner.start()}stopOraSpinner(){this.spinner.isSpinning&&this.spinner.stop()}getFrame(){return this.spinner.frame()}start(t){t&&(this.text=t);let n=G.length===1;return G.includes(this)||G.push(this),n&&G.length===2&&mt==="running"&&(G[0].stopOraSpinner(),Kt!==void 0&&(clearInterval(Kt),Kt=void 0),mt="idle"),Lw(),this}_stop(t,n="abort"){switch(this.text=t??this.text,Vl(),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(),Hl(),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")}},ft={create:(e={})=>new wi({...e,interval:ir.interval}),start:(e,t={})=>new wi({...t,interval:ir.interval}).start(e),pause:Vl,resume:Hl,reset:ac,successAll:e=>G.forEach(t=>t.succeed(e)),failAll:e=>G.forEach(t=>t.fail(e)),disable:()=>{sr=!1,ac()},enable:()=>{sr=!0},getInterval:()=>ir.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}}});function Ww(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 Vw(){let e=new Date,t=e.getTimezoneOffset()*6e4;return e.setTime(e.getTime()-t),e}var Ce,lo,Gl,Jl,pc,l,v=g(()=>{"use strict";Ce=require("chalk"),lo=require("lodash");ic();Gl=require("os");zl();bi();Jl=`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.`,pc=class{boxSize=80;warningBoxSize=90;disabled=!1;spinner={create:()=>ft.create(),disable:ft.disable,start:t=>ft.start(t),pause:ft.pause,resume:ft.resume,abort:ft.reset};disable(){this.disabled=!0,ft.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,Ce.yellow)("DEBUG")}${this._padString(`[${n}] ${t}`,1)}`),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ft.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,Ce.green)(this._padString(t,0)),"INFO")}error(t){this._log((0,Ce.red)(this._padString(t,0)),"ERROR")}warn(t){let n=` ${(0,Ce.yellow)("Warning "+(0,lo.repeat)("─",this.warningBoxSize-8))} ${(0,Ce.yellow)(this._padString(t))} ${(0,Ce.yellow)((0,lo.repeat)("─",this.warningBoxSize))} `;this._log(n,"WARNING")}logBox(t){if(this.disabled)return;let n=` ${(0,Ce.magenta)((0,lo.repeat)("─",this.boxSize))} ${(0,Ce.magenta)(this._padString(t))} ${(0,Ce.magenta)((0,lo.repeat)("─",this.boxSize))} `;this._log(n,"INFO")}clean(){this.spinner.abort()}async initLogFile(t){this.disabled||await Wl(t)}debounceTimeout;_log(t,n){this.disabled||(this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.spinner.pause(),n==="ERROR"?console.log(t):yi(()=>Promise.resolve(console.log(t))),this.debounceTimeout=setTimeout(()=>{this.spinner.resume()},ft.getInterval()),this._printToFile(t,n))}_printToFile(t,n){Dn.write(`${Vw().toISOString()} ${n} ${Ww(t)} `)}_padString(t,n=2){return`${t}`.split(/[\n\r]/).map(o=>`${(0,lo.repeat)(" ",n)}${o}`).join(Gl.EOL)}};l=new pc});var cr=g(()=>{"use strict"});function vi(e){let t=[e,Hw];return new Error(t.filter(Boolean).join(` `),{cause:259})}function Yl(e){return e?e.replace(/\(|\)/g,"").split(" ").filter(Boolean).map(t=>t.includes(pr.sep)?`${t.split(pr.sep).pop()}`:t).join(" "):"No stacktrace is available for this error"}function Yt(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(pr.sep)?`${t.replace(/["']/g,"").split(pr.sep).pop()}`:t).join(" ").substring(0,200).trim():""}function x(e){return e instanceof Error?e:new Error(String(e))}function Ti(e,t){throw new Error(`ERROR [${(0,Kl.green)(t)}]: ${e.message}`)}var pr,Kl,lr,R,Hw,C=g(()=>{"use strict";pr=require("path");cr();Kl=require("chalk"),lr=(o=>(o.GENERIC_CLI_ERROR="DEC:D9",o.CONNECTION_ERROR="DEC:DA",o.INVALID_APP_STRUCTURE="DEC:E3",o))(lr||{}),R=(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))(R||{}),Hw=`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 W(e){if(!(0,uo.existsSync)(e)&&!(0,uo.lstatSync)(e,{throwIfNoEntry:!1})?.isFile())throw new Error(`[read-json.ts] File does not exist: ${e}`,{cause:257});let t=(0,uo.readFileSync)(e,"utf-8");return JSON.parse(t)}var uo,Pe=g(()=>{"use strict";uo=require("fs");C()});function iu(e){if(!Si)return;let t=process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN;return`${Si}-${e}.${t}`}var Si,su=g(()=>{"use strict";Si=process.env.CODESPACE_NAME&&process.env.CODESPACE_NAME.trim()!==""?process.env.CODESPACE_NAME:void 0});function au(e){if(!dr)return;let t=new URL(dr).hostname;return`${e}-${t}`}var dr,cu=g(()=>{"use strict";dr=process.env.GITPOD_WORKSPACE_URL&&process.env.GITPOD_WORKSPACE_URL.trim()!==""?process.env.GITPOD_WORKSPACE_URL:void 0});function Ze(e){if(le)return dc?dc.replace(/^https?:\/\//,""):dr?au(e):iu(e)}function Ei(e){let t=Ze(e);return t?`wss://${t.replace(/^https?:\/\//,"")}`:""}var dc,le,_t=g(()=>{"use strict";su();cu();dc=process.env.DT_APP_DEV_ENVIRONMENT_URL&&process.env.DT_APP_DEV_ENVIRONMENT_URL.trim()!==""?process.env.DT_APP_DEV_ENVIRONMENT_URL:void 0,le=dr||Si||dc});function ue(e,t){let o={cwd:t||process.cwd(),maxBuffer:10485760};return new Promise((r,i)=>{(0,lu.exec)(e,o,(s,a,c)=>{s!==null?i(s):typeof c!="string"?i(c):r(a)})})}var lu,Kw,On=g(()=>{"use strict";lu=require("child_process"),Kw=require("commander")});async function k(e,t){return(0,fo.fetch)(e,t)}var fo,re=g(()=>{"use strict";fo=require("undici")});function uu(e,t,n,o,r){let i=JSON.stringify(t,null,2),a=`${e} HTTP ${n} ${o} ${t?.message??""}`+` ${qw(t,r)}`;return l.debug(`${a}${i}`,Yw),new Error(a,{cause:266})}function qw(e,t){return e?.details?.constraintViolations?e.details.constraintViolations.reduce((n,o)=>{let r=Xw(o,t);return`${n} ${r}`},""):""}function Xw(e,t){let{errorCode:n,errorCodeProperties:o,message:r}=e,i=r;if(n&&t){let s=o?.dependency,a=t.find(c=>c.name===s)?.packageJsonDep;if(n==="DependencyUnknown"&&(i=`Unknown service ${s} is listed in the dynatrace-metadata.json file of your dependency ${a}. Please verify that this service exists and is correctly referenced in your dependency.`),n==="DependencyVersionIncompatible"){let c=o?.availableVersion,p=o?.incompatibleVersion;i=`The service ${s} listed in the dynatrace-metadata.json file of your dependency ${a} references a version that does not exist on your tenant. Your dependency is requiring version: ${p??"unknown"}. The compatible version is: ${c??"unknown"}. To resolve this, update your dependency ${a} to use a compatible service version. Refer to your dependency's documentation or changelog for upgrade/downgrade instructions.`}}return i}function Pi(e){let t=["Error while connecting to the app registry",e];return new Error(t.filter(Boolean).join(` `),{cause:266})}async function xi(e,t,n){try{let o=new URL(e);o.pathname=`${mr}/apps/${n}`,o.searchParams.append("add-fields","manifest,resourceStatus.subResourceStatuses"),o.searchParams.append("latest-app-version","true");let r={headers:{authorization:`Bearer ${t}`}},i=await k(o.toString(),r);return await Zw(i)===0?void 0:await i.json()}catch(o){throw Pi(x(o).message)}}async function Zw(e){if(e.ok&&e.headers.get("content-type")?.includes("text/html"))return 1;if(!e.ok){if(e.status===403)throw vi(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 go(e,t){try{let n=new URL(e),o={headers:{authorization:`Bearer ${t}`,"content-type":"application/octet-stream"}};n.pathname="/platform/metadata/v1/user";let r=await k(n.toString(),o);return!r.ok||r.headers.get("content-type")?.includes("text/html")?void 0:await r.json()}catch(n){throw Pi(x(n).message)}}async function du(e,t,n,o){try{let r=new URL(e);r.pathname=`${mr}/apps`;let i=await k(r.toString(),{method:"POST",body:t,headers:{authorization:`Bearer ${n}`,"content-type":"application/zip"}});if(!i.ok){let s=await i.json();return uu("Failed to install the app",s.error,i.status,i.statusText,o)}}catch(r){return Pi(x(r).message)}}async function mu(e,t,n){try{let o=new URL(e);o.pathname=`${mr}/apps/${t}`;let r=await k(o.toString(),{method:"DELETE",headers:{authorization:`Bearer ${n}`}});if(!r.ok){let i=await r.json();return uu("Failed to uninstall the app",i.error,r.status,r.statusText)}}catch(o){return Pi(x(o).message)}}async function fu(e,t){let n=await k(`${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 mr,Yw,qt=g(()=>{"use strict";re();v();C();mr="/platform/app-engine/registry/v1",Yw="APP-REGISTRY"});function ho(e){let t=new URL(e),[n,...o]=t.hostname.split(".");if(!o||o.length<1)throw new Error(`Invalid environment URL: "${e}"`,{cause:258});return{tenant:n,hostname:o.join(".")}}async function Qw(e,t,n,o){let r=await fu(e,n),i=Ai.flatMap(f=>le?[`https://${Ze(f)}`]:[`http://localhost:${f}`,`https://localhost:${f}`]),s=Ai.flatMap(f=>le?[Ei(f)]:[`ws://localhost:${f}`,`wss://localhost:${f}`]),a={"script-src":["'unsafe-eval'",...i,...t.map(f=>`'sha256-${f}'`)],"connect-src":[...i,...s],"frame-ancestors":i},{tenant:c,hostname:p}=ho(e),u=f=>f.replaceAll("{tenantId}",c).replaceAll("{hostname}",p),d={},m=[...Object.keys(r),...Object.keys(a)];for(let f of m){let h=new Set;for(let y of r[f]??[])h.add(u(y));for(let y of a[f]??[])h.add(u(y));d[f]=Array.from(h)}return d["frame-src"]=["*"],d["frame-ancestors"]=["*"],o&&Object.entries(o).forEach(([f,h])=>{d[f]?d[f].push(...h.map(y=>y.value)):d[f]=h.map(y=>y.value)}),ev(d)}function ev(e){return Object.entries(e).map(([t,n])=>`${t} ${n.join(" ")}`).join("; ")}async function Di(e,t,n,o){let r=`${e}-${t.join(",")}-${o}`,i=gu.get(r);if(i)return i;let s=await Qw(e,t,n,o);return gu.set(r,s),s}var Ai,gu,yo=g(()=>{"use strict";_t();qt();C();Ai=[3e3,3001,3002,3003,3004,3005];gu=new Map});function tv(e){let t=new yu.default({allErrors:!0,formats:{"relative-path":{type:"string",validate:r=>!(0,bu.isAbsolute)(r)},"valid-glob":{type:"string",validate:r=>{if(!r||r.length===0)return!1;try{return(0,vu.parse)(r),!0}catch{return!1}}},url:{type:"string",validate:r=>{try{let i=new URL(r);return i.protocol==="http:"||i.protocol==="https:"}catch{return!1}}},regex:!0},strict:!1});(0,hu.default)(t);let n=(0,wu.readFileSync)(e,"utf-8"),o=JSON.parse(n);return{appConfigSchema:o,validateAppConfigSchema:t.compile(o)}}async function Tu(e,t,n="default"){if(n==="none"||process.env.DT_APP_SKIP_CONFIG_VALIDATION==="true")return t;let{validateAppConfigSchema:o}=tv(e);if(o(t))return t;for(let r of o.errors)l.info(mc({error:r}));throw new Error("App config validation failed",{cause:264})}function mc({title:e="App config",error:t}){let n=Ri.red`error:`,o=t.instancePath??"";t.schemaPath&&t.schemaPath.indexOf("additionalProperties")>=0&&o.indexOf("app")<0&&(o=o?.substr(0,t.instancePath.lastIndexOf("/")));let r=o?o.split("/").reduce((s,a)=>s?isNaN(+a)?`${s}.${a}`:`${s}[${a}]`:a):"CliOptions",i=t.message?t.message.replace(/"/gi,"'"):"";return`> ${(0,Ri.bold)(e)}: ${n} '${r}' ${i}.`}function Su(e){if(e.distDir)throw new Error('The "distDir" option is no longer supported. Please remove "distDir" from the app.config.');if(e?.server?.open)throw new Error('The "server.open" option is no longer supported. Please remove "server.open" from the app.config.')}var hu,yu,Ri,bu,wu,vu,fc=g(()=>{"use strict";hu=A(require("ajv-errors")),yu=A(require("ajv/dist/2019")),Ri=require("chalk"),bu=require("path"),wu=require("fs"),vu=require("micromatch");v();C()});function ie(e,t){return require.resolve(e,{paths:[t]})}var gt=g(()=>{"use strict"});function Eu(e){return e.plugins.map(t=>nv(t,e.root)).filter(t=>!!t)}function nv(e,t){try{return require(ie(e,t)).default}catch(n){l.warn(`Could not require plugin ${e}. It will be ignored.`),l.debug(x(n).toString(),Ve)}}var Ve,fr=g(()=>{"use strict";v();gt();C();Ve="PLUGIN"});async function ov(e,t){for(let n of rv(e)){l.debug(`Running '${e}' hook of plugin '${n.name}'...`,Ve);try{await n.callBack(...t)}catch(o){l.error(`An error occurred during the '${e}' hook of plugin '${n.name}': ${x(o).toString()}`);continue}l.debug(`Finished '${e}' hook of plugin '${n.name}'.`,Ve)}}function rv(e){return gc[e]}function Cu(e){let t={"before-build":[],"before-serve":[]},n={beforeBuild(o){t["before-build"].push({name:e.name,callBack:o})},beforeServe(o){t["before-serve"].push({name:e.name,callBack:o})}};try{e.setup(n)}catch(o){l.error(`An error occurred during the setup of plugin '${e.name}': ${x(o).toString()}`);return}Object.keys(t).forEach(o=>{iv(o)&&gc[o].push(...t[o])})}function iv(e){return["before-build","before-serve"].includes(e)}function sv(e){for(let t of e)Cu(t)}var gc,bo,Oi=g(()=>{"use strict";v();fr();C();gc={"before-build":[],"before-serve":[]};bo={registeredHooks:gc,register:Cu,registerAll:sv,invoke:ov}});function wo(e){return(0,ki.basename)(e,(0,ki.extname)(e))}function Pu(e){(0,kn.existsSync)(e)&&(0,kn.rmSync)(e,{recursive:!0})}function ht(e){(0,kn.existsSync)(e)||(0,kn.mkdirSync)(e)}var ki,kn,Mt=g(()=>{"use strict";ki=require("path"),kn=require("fs")});function _(){if(__filename.endsWith("bin.js"))return(0,Fi.resolve)(__dirname);if(__filename.endsWith("index.js"))return(0,Fi.resolve)(__dirname,"src");if(__filename.endsWith(".ts"))return(0,Fi.resolve)(__dirname,"..");throw new Error("Could not retrieve lib source folder!",{cause:257})}var Fi,ne=g(()=>{"use strict";Fi=require("path");C()});function hc(e,t){try{let n=av(e,t??""),o=(0,Xt.join)(n,"lib","src","app.config.schema.json");if((0,gr.existsSync)(o))return o}catch{}return(0,Xt.join)(_(),"app.config.schema.json")}function vo(e,t){let n=hc(e,t);if(!(0,gr.existsSync)(n))return;let o=(0,Xt.join)(e,t??"",".dt-app"),r=(0,Xt.join)(o,"app.config.schema.json");ht(o),(0,gr.copyFileSync)(n,r)}function av(e,t){return(0,Xt.resolve)(require.resolve("dt-app",{paths:[(0,Xt.join)(e,t)]}),"../..")}var Xt,gr,hr=g(()=>{"use strict";Xt=require("path"),gr=require("fs");Mt();ne()});function ve(e){if(e.sourcemaps===void 0)return e.dev?cv:xu;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 xu}}var xu,cv,$t=g(()=>{"use strict";xu={sourcemap:!1,includeVendorSourceMaps:!1},cv={sourcemap:!0,includeVendorSourceMaps:!0}});function yr(e,t){let n=Qe.posix.normalize(Qe.posix.join(t.split(Qe.win32.sep).join(Qe.posix.sep),"/")),o=new RegExp(`^.*?${n}`,"g"),r=Qe.posix.parse(e.split(Qe.win32.sep).join(Qe.posix.sep).replace(o,""));return new URL("http://localhost"+Qe.posix.normalize(Qe.posix.join("/",r.dir,r.name.replace(/\.function$/,"")))).pathname}var Qe,Ii=g(()=>{"use strict";Qe=require("path")});var Au,pv,lv,He,Fn=g(()=>{"use strict";Au=require("fs"),pv="//# sourceMappingURL=data:application/json;base64,ewogICJtYXBwaW5ncyI6ICJBQUFBQSIsCiAgInNvdXJjZXMiOiBbIiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiIl0sCiAgIm5hbWVzIjogWyIiXSwKICAidmVyc2lvbiI6IDMsCiAgImZpbGUiOiAiIgp9",lv=[".js",".mjs",".cjs"],He=()=>({name:"excludeVendorFromSourceMap",setup(e){e.onLoad({filter:/node_modules/},t=>{if(lv.some(n=>t.path.endsWith(n)))return{contents:`${(0,Au.readFileSync)(t.path,"utf8")} ${pv}`,loader:"default"}})}})});function xe(e){return yc||(yc=require(ie("typescript",e))),yc}var yc,To=g(()=>{"use strict";gt()});function Ut(e,t){return{category:t,text:e.text,filePath:e.location?.file?(0,Du.resolve)(e.location.file):void 0,line:e.location?.line??1,column:(e.location?.column??0)+1}}function bc(e,t){let n=xe(t),o=`TS${e.code}`,r=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:o,category:i,text:r,filePath:e.file.fileName,column:a+1,line:s+1}}return{code:o,category:i,text:r,filePath:void 0,line:1,column:1}}var Du,_e=g(()=>{"use strict";Du=require("path");To()});function E(e,t){let o=(Array.isArray(e)?e:e.split(/[\/\\]/g)).map(r=>r?r.replace(/\\/g,"/"):"").join("/").replace(/\/\.\//g,"/").replace(/(?<!:)\/{2,}/g,"/").replace(/^.\//,"");return t?.keepFullPath?o:o.replace(/^([a-zA-Z]):/,"")}var q=g(()=>{"use strict"});function ze(e,t){t&&console.log(`${e} `),console.log(Me.default.hex(yt.green).bold(`${e} `))}function Z(e){if(e){console.log(`════════ `);return}console.log(Me.default.hex(yt.blue).bold("══")+Me.default.hex(yt.limeGreen).bold("══")+Me.default.hex(yt.green).bold("══")+Me.default.hex(yt.purple).bold("══")+` `)}function F(e,t="white",n){if(n){process.stdout.write(e);return}process.stdout.write(Ae(e,t))}function So(e,t="white",n){if(n){console.log(e);return}console.log(Ae(e,t))}function Ae(e,t="white"){return{white:Me.default.white,blue:Me.default.hex(yt.blue),green:Me.default.hex(yt.green),purple:Me.default.hex(yt.purple),limeGreen:Me.default.hex(yt.limeGreen),gray:Me.default.dim}[t](e)}function Eo(e){let n=process.stdout.columns<=100?process.stdout.columns:100;if(e){console.log("─".repeat(n)+` `);return}console.log(Me.default.hex(yt.blue)("─".repeat(n))+` `)}function L(){console.log(` `)}function Zt(e,t=""){let n=(o,r="")=>{let c="";return o.items?.forEach((p,u)=>{let d=u===o.items.length-1,m=d?"└─ ":"├─ ",f=d?" ":"│ ";c+=`${r}${m}${p.name} `,p.items?.length&&(c+=n(p,r+f))}),c};console.log(n(e,t))}function Ni(){console.log("")}function br(e,t,n,o=!0){let r={};e.forEach(s=>{let c=s.split("/")[0];r[c]||(r[c]=[]),r[c].push(s)});let i={items:[]};return Object.keys(r).forEach(s=>{let a={name:s,items:[]};r[s].forEach(c=>{let p=c.split("/");if(p.shift(),p.length!==0)if(p.length===1){let u=p[0];a.items.push(u.endsWith("widget.tsx")?Ru(u,t,n,o):Ou(u,t,n))}else{let u=a;for(let m=0;m<p.length-1;m++){let f=p[m],h=u.items.find(y=>y.name===f&&Array.isArray(y.items));h||(h={name:f,items:[]},u.items.push(h)),u=h}let d=p[p.length-1];u.items.push(d.endsWith("widget.tsx")?Ru(d,t,n,o):Ou(d,t,n))}}),i.items.push(a)}),i}function Ru(e,t,n,o){let r=[{name:`Local: ${t[e+"_local"]}`}];return o&&r.push({name:`Environment: ${t[e+"_environment"]}`}),{name:n[e],items:r}}function Ou(e,t,n){return{name:`${n[e]}: ${t[e]}`}}var Me,yt,de=g(()=>{"use strict";Me=A(require("chalk")),yt={green:"#73be28",purple:"#6f2da8",blue:"#1496ff",limeGreen:"#b4dc00"}});function he(e){if(!(0,ku.existsSync)((0,De.join)(e.cwd,e.sourceRoot,"api")))return[];let t=e.includeJs?"{ts,js}":"ts";return(0,Qt.sync)(E([e.sourceRoot,"api",`**/*.function.${t}`]),{cwd:e.cwd,ignore:["**/*.test.ts","**/*.spec.ts"]})}function Fu(e){let t=he({cwd:e.cwd,sourceRoot:e.sourceRoot});if(!t.length)return;F("Available app functions served from '/api':","green"),L();let n={};t.forEach(i=>{n[i.split("/")[i.split("/").length-1]]=Ae(e.url+E(["/api",yr(i,"api").replace(".resumable","")]),"gray")});let o=Mi(t,e.cwd),r=br(t,n,o);Zt(r)}async function Iu(e){let t=await(0,Qt.default)(`${e.actionsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]}),n=await(0,Qt.default)(`${e.actionsDir}/*.action.ts`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(n.length===0&&t.length===0)return;F("Available workflow actions:","green"),L();let o=Mi([...n,...t],e.cwd),r=uv(e,n,t),i=br([...n,...t],r,o);Zt(i)}function uv(e,t,n){let o={};return t.forEach(r=>{let i=(0,De.basename)(r),s=(0,De.basename)(r,".action.ts");o[i]=Ae(`${e.url}/api/${s.replace(".resumable","")}`,"gray")}),n.forEach(r=>{let i=(0,De.basename)(r),s=(0,De.basename)(r,".widget.tsx"),a=`${e.url}/widgets/actions/${s}`;o[`${i}_local`]=Ae(a,"gray"),o[`${i}_environment`]=Ae(dv(e.environmentUrl,a,e.locationAppIds),"gray")}),o}function dv(e,t,n){return`${e}/ui/apps/dynatrace.automations/dev-helper?src=${t}&locationAppIds=${n}`}async function bt(e,t){return(await(0,Qt.default)(t,{cwd:e,ignore:["**/*.{test,spec}.ts","node_modules"]})).map(o=>(0,De.join)(e,o))}async function Nu(e){let t=await(0,Qt.default)(`${e.widgetSettingsDir}/*.widget.tsx`,{cwd:e.cwd,ignore:["**/*.{test,spec}.ts","node_modules"]});if(t.length===0)return;F("Available settings widgets:","green"),L();let n={};t.forEach(i=>{let s=(0,De.basename)(i),a=(0,De.basename)(s,".widget.tsx"),c=`${e.url}/widgets/settings/${a}`;n[`${s}_local`]=Ae(c,"gray")});let o=Mi(t,e.cwd),r=br(t,n,o,!1);Zt(r)}async function _u(e){let t=await(0,Qt.default)(`${e.documentsDir}/*.*`,{cwd:e.cwd,onlyFiles:!0});if(!t.length)return;F("Available documents:","green"),L();let n={};t.forEach(i=>{let s=(0,De.basename)(i),a=`${e.appId}.${(0,De.basename)(i).split(".")[0]}`;n[s]=Ae(a,"gray")});let o=Mi(t,e.cwd),r=br(t,n,o);Zt(r)}function Mi(e,t){let n={};return e.forEach(o=>{let r=(0,De.basename)(o);n[r]=mv((0,De.join)(t,o),r)}),n}function mv(e,t){return process.platform==="win32"&&(e="/"+e.replace(/\\/g,"/").replace(/^\/+/,"")),`\x1B]8;;file://${e.replace(/\\/g,"/")}\x1B\\${t}\x1B]8;;\x1B\\`}var ku,Qt,De,Ge,_i,ye=g(()=>{"use strict";ku=require("fs"),Qt=A(require("fast-glob")),De=require("path");q();Ii();de();Ge="documents",_i="document-types"});function Ui(e){return e.map(fv).filter(t=>!t.filePath?.includes("node_modules/"))}async function Mu(e,t){let o=he({cwd:e.root,sourceRoot:e.build.sourceRoot}).length>0,r=(0,$i.existsSync)((0,wc.join)(e.root,t));if(o&&!r)throw new Error(`Failed to build functions A tsconfig.json must exist, if function source files are present in the api directory. Please create a tsconfig.json file in the api directory, or delete the directory. ${(0,$i.readFileSync)((0,wc.join)(_(),"function/template/tsconfig.json"),"utf-8")}: `,{cause:265});if(!o&&r)throw new Error(`Failed to build functions A tsconfig.json exists, but no functions were found in the api directory. Please create a function in the api directory, or delete the directory. You can create functions with the generate command: $ npm run generate:function `,{cause:265})}function vt(){return{sourcemap:!0,color:!0,loader:{".node":"empty"},bundle:!0,logLevel:"silent",charset:"utf8",write:!1}}var wc,$i,en,fv,Po=g(()=>{"use strict";wc=require("path"),$i=require("fs");_e();C();ne();ye();en=e=>Ut(e,"Error"),fv=e=>Ut(e,"Warning")});async function $u(e,t,n){let o=require(ie("esbuild",t.cwd));if(!o.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. ${o.version?`Your current esbuild version being used is ${o.version}.`:""}`,{cause:258});let{context:r}=o,i=t.sourcemapOptions?.sourcemap??!1;i&&!t.sourcemapOptions?.includeVendorSourceMaps&&(t.plugins=[...t.plugins??[],He()]);let s=await r({...vt(),entryPoints:t.entryPoints.map(c=>(0,xo.isAbsolute)(c)?c:(0,xo.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,xo.isAbsolute)(t.tsconfig)?t.tsconfig:(0,xo.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()}}var xo,Uu=g(()=>{"use strict";xo=require("path");Fn();gt();C();Po()});async function vc(e,t){let n=Date.now();try{let o=(0,wr.join)(e.cwd,"dist"),r=await $u(o,e,t),i=Date.now(),s=r.warnings.map(p=>Ut(p,"Warning")).filter(p=>!p.filePath?.includes("node_modules/")),a=e.outDir??"dist";return{fileMap:r.outputFiles.reduce((p,u)=>{let d=`${wr.sep}${(0,wr.join)(a,u.path.replace(o,""))}`;return{...p,[d]:{content:Buffer.from(u.contents)}}},{}),diagnostics:s,duration:i-n}}catch(o){let r=Date.now();if(gv(o)){let s=[...o.errors.map(a=>Ut(a,"Error")),...o.warnings.map(a=>Ut(a,"Warning")).filter(a=>!a.filePath?.includes("node_modules/"))];return{fileMap:{},diagnostics:s,duration:r-n}}throw o instanceof Error?o:new Error(String(o),{cause:261})}}function gv(e){return typeof e=="object"&&typeof e?.errors<"u"}var wr,Tc=g(()=>{"use strict";wr=require("path");Uu();_e();C()});var vr,Bi=g(()=>{"use strict";vr=()=>({name:"skip-css",setup(e){e.onResolve({filter:/\.css$/},({path:t})=>({path:t,external:!0,namespace:"skip-css"}))}})});var et=g(()=>{"use strict"});function Sc(e){let{ScriptTarget:t}=xe(e);return{ui:{target:t.ES2022,...ji},functions:{target:t.ESNext,...ji},actions:{target:t.ESNext,...ji},widgets:{target:t.ESNext,...ji}}}var ji,Bu=g(()=>{"use strict";To();et();ji={noEmit:!0,skipLibCheck:!0}});function tt(e){let{createCompilerHost:t,createProgram:n}=xe(e.srcRoot),{tsConfigContents:o,tsConfigFileDiagnostics:r}=hv(e.srcRoot,e.tsConfigFullPath);if(o.projectReferences&&o.projectReferences.length>0&&o.fileNames.length===0)return yv(e);let s={...o.options,...Sc(e.srcRoot)[e.buildType],incremental:!1},a=t(o.options),c=[],p=(0,Ec.not)(e.entrypoints,o.raw.exclude).map(f=>(0,tn.isAbsolute)(f)?f:(0,tn.join)(e.srcRoot,f));if(o.options.composite)c=[...new Set([...p,...o.fileNames])];else{let f=o.fileNames.filter(y=>y.endsWith(".d.ts")),h=(0,Ec.not)(f,o.raw.exclude).map(y=>(0,tn.isAbsolute)(y)?y:(0,tn.join)(e.srcRoot,y));c=[...new Set([...p,...h])]}let u=n({rootNames:c,options:s,host:a,configFileParsingDiagnostics:r,projectReferences:o.projectReferences}),d=u.emit();return[...u.getSyntacticDiagnostics(),...u.getSemanticDiagnostics(),...u.getConfigFileParsingDiagnostics(),...u.getGlobalDiagnostics(),...u.getDeclarationDiagnostics(),...d.diagnostics].map(f=>bc(f,e.appRoot))}function hv(e,t){let{sys:n,readConfigFile:o,parseJsonConfigFileContent:r}=xe(e),i=o(t,c=>(0,ju.readFileSync)(c).toString()),s=[];i.error&&(0,Li.has)(i.error.file,"parseDiagnostics")&&(s=(0,Li.get)(i.error?.file,"parseDiagnostics"));let a=r(i.config,n,(0,tn.dirname)(t));return s.push(...a.errors),{tsConfigContents:a,tsConfigFileDiagnostics:s}}function yv(e){let{sys:t,createSolutionBuilderHost:n,createSolutionBuilder:o}=xe(e.srcRoot),r=[],{noEmit:i,...s}=Sc(e.appRoot)[e.buildType],a=n(t,void 0,u=>{u.code!==6357&&r.push(u)},u=>{u.code!==6357&&r.push(u)}),c=a.writeFile;return a.writeFile=(u,d,m)=>{(u.endsWith(".d.ts")||u.endsWith(".d.ts.map")||u.endsWith(".tsbuildinfo"))&&c?.(u,d,m)},o(a,[e.tsConfigFullPath],{dry:!1,force:!1,verbose:!1,...s}).build(),r.map(u=>bc(u,e.appRoot))}var Li,Ec,ju,tn,Wi,In=g(()=>{"use strict";Li=require("lodash"),Ec=require("micromatch"),ju=require("fs"),tn=require("path");_e();To();Bu();et();Wi=e=>({actions:`${e}/*.action.ts`,widgets:`${e}/*.widget.tsx`})});function Vu(e){return e instanceof Error?{error:{name:e.name,message:e.message,stack:e.stack,cause:e.cause}}:e}function Cc(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Hu(n)]))}function Hu(e){return e==null?e:Array.isArray(e)?e.map(t=>Hu(t)):typeof e=="object"?Cc(e):typeof e=="string"?Yt(e):e}function zu(){return Math.floor(Math.random()*Math.pow(10,18))}function wv(e){return e!==""&&e.length<=bv&&Number.isInteger(Number(e))}function Gu(){try{if(!(0,_n.existsSync)(Nn))return;let e=(0,_n.statSync)(Nn).birthtime;vv(e)&&(0,_n.unlinkSync)(Nn)}catch{l?.debug("Could not identify user uniquely",O)}}function vv(e){return(new Date().getTime()-e.getTime())/(1e3*3600)>=24}async function Ju(e){try{if((0,_n.existsSync)(Nn)){let n=(await(0,Tr.readFile)(Nn)).toString();wv(n)?e=Number(n):await(0,Tr.writeFile)(Nn,e.toString())}else await(0,Tr.writeFile)(Nn,e.toString())}catch(t){console.error("Error initializing session file:",t)}return e}async function Ku(e){let t=W(e),n=t?.app_token?.access_token||t?.toolkit_token?.access_token;if(n)return go(t.app_token?.environment_url||t.toolkit_token?.environment_url||"",n)}function J(e){return e.reduce((t,n,o,r)=>{if(n.startsWith("--")){let i=n.slice(2),s=r[o+1];s&&!s.startsWith("--")?t[i]=Yt(s):t[i]=!0}return t},{})}function Yu(e){return e.includes("dev")?"dev":e.includes("hardening")?"hardening":"prod"}function Pc(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 Lu,Wu,_n,Tr,O,Nn,bv,V=g(()=>{"use strict";Lu=require("path"),Wu=require("os"),_n=require("fs"),Tr=require("fs/promises");C();v();Pe();qt();O="TELEMETRY",Nn=(0,Lu.join)((0,Wu.homedir)(),".dt-app",".session"),bv=19});async function Vi(){let e=["actions","functions","ui","widgets"];await Promise.all(e.map(t=>{let n=Ao[t];return n?(Ao[t]=void 0,n.terminate()):Promise.resolve()})),l.debug("All TypeScript workers terminated","TYPESCRIPT")}function nt(e,t){if(Ao[e.buildType])return;let n=o=>{switch(o.type){case"initialized":l.debug(` ${o.payload} typescript worker thread has been initialized!`,"TYPESCRIPT");break;case"type-error":l.info(o.payload),t?.onTypeError?.(o.payload);break;case"type-check-complete":t?.onTypeCheckComplete?.(o.payload.errorCount);break;case"send-biz-event":$({"event.category":"error",name:"ts-worker-error",payload:o.payload});break;case"entrypoints-changed":l.debug(`New amount of entrypoints for ${o.payload.buildType}: ${o.payload.entrypoints.length}`,`ENTRYPOINTS_WATCHER-${o.payload.event}`)}};Ao[e.buildType]=new Xu.Worker((0,qu.join)(_(),"ts-worker.js"),{workerData:e}),Ao[e.buildType].once("error",o=>{l.error(`TypeScript worker thread error: ${o}`),process.exit(1)}),Ao[e.buildType].on("message",o=>{n(o)})}var qu,Xu,Ao,nn=g(()=>{"use strict";qu=require("path"),Xu=require("worker_threads");et();ne();v();oe();V();Ao={actions:void 0,functions:void 0,ui:void 0,widgets:void 0}});function Qu(e){return(0,Mn.join)(e).split(Mn.sep).filter(n=>n).length>1}var Mn,Zu,Hi,Do=g(()=>{"use strict";Mn=require("path");$t();Ii();Tc();ye();Bi();In();et();q();nn();Zu=A(require("@dynatrace/js-runtime/capabilities/capabilities.json")),Hi=Zu.default.supportedModules});function ot(){return ed.default.resolve(_(),"utils","snippets")}var ed,Sr=g(()=>{"use strict";ne();ed=A(require("path"))});function od(e){let t={};e.https&&(t={https:{cert:(0,xc.readFileSync)(e.https.cert),key:(0,xc.readFileSync)(e.https.key)}});let n=(0,td.default)({...t,bodyLimit:50*1048576,forceCloseConnections:!0});return n.removeAllContentTypeParsers(),n.addContentTypeParser("*",{parseAs:"buffer"},(o,r,i)=>{i(null,r)}),n}function rd(){return new nd.WebSocketServer({noServer:!0})}function id(e){let t=e.https?"wss":"ws",n=e.host==="127.0.0.1"?"localhost":e.host;return`${t}://${n}:${e.port}`}var td,xc,nd,zi,Er=g(()=>{"use strict";td=A(require("fastify")),xc=require("fs"),nd=require("ws"),zi="/__dt_app_live_reload__"});var $n,Cr=g(()=>{"use strict";$n="x-dt-app-dev-server-session-token"});function sd(){let e=(0,xr.resolve)(ot(),"defaultIndex.snippet.html");return Pr.default.readFileSync(e).toString("utf-8")}function Tt(e,t){let{transformSync:n}=require(ie("esbuild",t)),o=(0,xr.resolve)(ot(),"sdkWebShim.snippet.ts"),r=Pr.default.readFileSync(o,"utf-8"),i={loader:"ts",define:{"process.env.INJECT":JSON.stringify(e)}};return n(r,i).code}function ad(e){let t=(0,xr.resolve)(ot(),"selfmon_config.snippet.js");return Pr.default.readFileSync(t,"utf-8").replace("{{PLATFORM_PREFIX}}",e)}async function Ji(e){return Gi||(Gi=await(await k(e)).text(),Gi)}function St(e){let t=Ei(e.server.port),n=id(e.server);return`window.socketUrl = '${t||n}${zi}';`}function Ro(e){let t=(0,xr.resolve)(ot(),"devServerSessionToken.snippet.ts"),n=Pr.default.readFileSync(t,"utf-8"),{transformSync:o}=require("esbuild");return o(n,{loader:"ts",define:{"process.env.SESSION_TOKEN":JSON.stringify(e),"process.env.SESSION_HEADER":JSON.stringify($n)}}).code}var Pr,xr,Gi,on=g(()=>{"use strict";Pr=A(require("fs"));re();xr=require("path");gt();Sr();Er();_t();Cr()});function pd(e){let t;Ac?t=Ac:(t=Tv.exec(e),Ac=t);try{return t[0]}catch{throw new Error(`The self monitoring agent could not be retrieved, please check if ${cd.default.cyan`options.app.selfMonitoringAgent`} is configured to the correct url.`,{cause:263})}}async function ld(e){try{if(!e.includes("http"))return 3;let t=await k(e),n=t.status,r=t.headers.get("content-type")?.includes("javascript"),s=(await t.text()).includes("cuc=");return n===404||!r||!s?2:(await Ji(e),0)}catch{return 1}}var cd,Tv,Ac,Dc=g(()=>{"use strict";re();on();cd=A(require("chalk"));C();Tv=/(?<=(?:\||")cuc=).*?(?=\||")/g});function dd(e,t){return e.map(n=>Sv(n,t))}async function Sv(e,t){let n=e;if((0,Ki.existsSync)((0,Yi.join)(t.root,t.actionsDir,`${e.name}.action.ts`))||(0,Ki.existsSync)((0,Yi.join)(t.root,t.actionsDir,`${e.name}.resumable.action.ts`))||(0,Ki.existsSync)((0,Yi.join)(t.root,t.actionsDir,`${e.name}.stateful-action.ts`)))return n;if(!(await(0,ud.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}var Ki,Yi,ud,md=g(()=>{"use strict";Ki=require("fs"),Yi=require("path"),ud=A(require("fast-glob"));C()});function Oc(e){return(0,$e.join)(e,"/.dt-app/.tokens.json")}function Ue(e,t,n){if((0,Ar.existsSync)((0,$e.join)(e,t,"ui","main.tsx")))return{entryPoint:(0,$e.join)(e,t,"ui","main.tsx"),assetsInput:n.assets[0].input,tsConfigFullPath:(0,$e.join)(e,t,"ui","tsconfig.json")};l.debug(`No ${(0,$e.join)(e,t,"ui","main.tsx")} found. Defaulting to legacy structure.`,"UI");let r=(0,$e.join)(e,t,"tsconfig.json"),i=(0,$e.join)(e,t,"main.tsx");if(!(0,Ar.existsSync)(r)){if(!(0,Ar.existsSync)(i))return l.debug(`No UI entry point found at ${i}. Returning null — UI build will be skipped.`,"UI"),null;Ti(new Error("tsconfig.json not found. Please make sure it is located next to the main.tsx file."),"DEC:E3")}let s={entryPoint:i,assetsInput:n.assets[0].input,tsConfigFullPath:r};return l.debug(`Paths that are used: ${JSON.stringify(s)}`,"LEGACY"),s}function Xi(e,t,n){return{appFunctionsBuildPlatform:"browser",root:n??process.cwd(),distDir:"dist",dryRun:!1,noLiveReload:!1,noSecurityHardening:!1,injectSdk:!0,build:{index:(0,$e.join)("src/index.html"),sourceRoot:t??"./",sourceMaps:void 0,ui:{assets:[{glob:"**/*",ignore:[],input:t?(0,$e.join)(t,"ui/assets"):(0,$e.join)("ui/assets"),output:"assets"}]},api:{plugins:[]},mode:e?"development":"production",namedChunks:!1,baseHref:"/ui/",dynatraceDependencies:{addOrOverride:{},ignore:[]},typeCheck:!0},server:{open:!0,port:3e3,host:"127.0.0.1",showWarnings:!1,enableCSP:!0},plugins:[]}}function rn(e){return e.endsWith("/")?e:`${e}/`}function Ev(e){try{return new URL(e).origin}catch{return e}}function qi(e,t){return(0,ko.mergeWith)((0,ko.cloneDeep)(e),t,(n,o,r)=>{if(o===void 0)return n;if(Array.isArray(o))return o.length>0&&Cv(o[0])&&r in fd?o.map(i=>(0,ko.merge)({},fd[r],i)):[...o]})}function Cv(e){return Object.prototype.toString.call(e)==="[object Object]"}function gd(e,t){let n=t.root?t.root:process.cwd(),o=e.build?.sourceRoot,r=[];e.build?.settingsPath&&r.push('The configuration "build.settingsPath" has been removed in dt-app v1.0. The settings have to be inside <source_root>/settings/schemas directory. The current default location is ./settings/schemas/'),e.build?.ui?.additionalEntryPoints&&r.push('The configuration "build.ui.additionalEntryPoints" has been removed in dt-app v1.0. The additionalEntryPoints for the ui have to be inside <source_root>/ui directory. The current default location is ./ui/'),e.build?.ui?.entryPoint&&r.push('The configuration "build.ui.entryPoint" has been removed in dt-app v1.0. The main entry point for the ui has to be inside <source_root>/ui directory. The current default location is ./ui/main.tsx.'),e.build?.ui?.tsconfig&&r.push('The configuration "build.ui.tsconfig" has been removed in dt-app v1.0. The tsconfig for the ui has to be inside <source_root>/ui directory. The current default location is ./ui/tsconfig.json.'),!o&&(0,Ar.existsSync)((0,$e.join)(n,"src","main.tsx"))&&r.push(`In dt-app v1.0, UI sources are expected to be located in the project's sourceRoot directory. To specify a different source root, please use the "build.sourceRoot" configuration.`),e.build?.functions&&r.push('The configuration "build.functions" has been removed in dt-app v1.0. To configure your App Functions please use "build.api" instead.'),e.build?.functions?.input&&r.push('The configuration "build.functions.input" has been removed in dt-app v1.0. To specify the location of your App Functions, please use "build.sourceRoot" instead.'),e.build?.functions?.glob&&r.push('All the app functions in v1.0 will have to have a postfix ".function.ts". will be removed in dt-app v1.0. To specify the glob for your app functions, please use "build.sourceRoot" instead. All the app functions in v1.0 will have to have a postfix ".function.ts".'),e.build?.functions?.tsconfig&&r.push('The configuration "build.functions.tsconfig" has been removed in dt-app v1.0. The App Functions tsconfig has to be inside the <source_root>/api directory'),e.build?.functions?.plugins&&r.push('The "build.functions.plugins" are deprecated and will be removed in the next major release of App Toolkit'),e.build?.actions?.plugins&&r.push('The "build.actions.plugins" are deprecated and will be removed in the next major release of App Toolkit'),e.build?.widgets?.plugins&&r.push('The "build.widgets.plugins" are deprecated and will be removed in the next major release of App Toolkit'),e.root&&r.push('The configuration "root" has been removed in dt-app v1.0. To specify the root of your project, please use the flag `--cwd` instead.'),e.oauthClientId&&r.push('The configuration "oauthClientId" has been removed in dt-app v1.0.'),e.distDir&&r.push('The configuration "distDir" has been removed in dt-app v1.0. Default value "./dist" will be used.'),e.oauth2File&&r.push('The configuration "oauth2File" has been removed in dt-app v1.0. Default value "./dt-app/.tokens.json" will be used.'),e.dev?.fileWatcher?.ignore&&r.push('The configuration "dev.fileWatcher.ignore" has been removed in dt-app v1.0. Development server will ignore redundant files by default.'),e.dev?.fileWatcher?.include&&r.push('The configuration "dev.fileWatcher.include" has been removed in dt-app v1.0. Development server will include all required files by default.'),e.server?.open&&r.push('The configuration "server.open" has been removed in dt-app v1.0. To specify if the project should be opened, please use the flag `--open` instead.'),process.env.DT_APP_SIGNING_PK&&r.push('The env variable "DT_APP_SIGNING_PK" has been removed in dt-app v1.0.'),process.env.DT_APP_SIGNING_CERT&&r.push('The env variable "DT_APP_SIGNING_CERT" has been removed in dt-app v1.0.'),process.env.DEBUG&&r.push('The env variable "DEBUG" has been removed in dt-app v1.0. Please user --verbose flag instead.'),process.env.DT_APP_SERVERLESS_MAX_CONNECTIONS&&r.push('The env variable "DT_APP_SERVERLESS_MAX_CONNECTIONS" has been removed in dt-app v1.0. Default value of 128 will be used instead.'),t?.injectSdk!==void 0&&r.push('The flag "--no-sdk-injection" has been removed in dt-app v1.0. Please use app.config instead'),t.global&&r.push('The flag "--global" has been removed in dt-app v1.0.'),e.build?.ui?.sourceMaps&&r.push('The configuration "build.ui.sourceMaps" has been removed in dt-app v1.0. Please use centralize "build.sourceMaps" configuration instead.'),e.build?.functions?.sourceMaps&&r.push('The configuration "build.functions.sourceMaps" has been removed in dt-app v1.0. Please use centralize "build.sourceMaps" configuration instead.'),t.build?.mode==="development"&&r.push('The flags "--prod" and "--no-prod" are deprecated and will be removed in dt-app v1.0. Please use "build.mode" configuration instead.'),r.length&&l.warn(r.join(` `))}function hd(e){let t=Ue(e.root,e.build.sourceRoot,e.build.ui);t!==null&&(e.build.ui.assets[0].input=t.assetsInput)}async function yd(e){if(!e.app?.actions)return;let t=e.build.sourceRoot?(0,$e.join)(e.build.sourceRoot,"actions"):"actions";e.app.actions=await Promise.all(dd(e.app.actions,{root:e.root,actionsDir:t}))}async function bd(e){if(!e.app?.selfMonitoringAgent)return;let t=e.app.selfMonitoringAgent,n=await ld(t);n===3&&(l.warn(`Failed to configure self monitoring agent. Self monitoring agent url missing ${(0,Oo.green)("https://")}. Please prepend to the url in the ${(0,Oo.blue)("app.config.ts")}.`),e.app.selfMonitoringAgent=void 0),n===1&&(l.warn(`Failed to configure self monitoring agent. Could not reach ${t}. Please make sure its accessible from the environment you're running.`),e.app.selfMonitoringAgent=void 0),n===2&&(l.warn(`Failed to configure self monitoring agent. Could not find a self monitoring script at the configured url ${t}. Please make sure you've configured the right url and that it is reachable.`),e.app.selfMonitoringAgent=void 0),e.build.mode==="production"&&n!==0&&(l.error(`Exiting production build. If you wish to build anyways, please set the ${(0,Oo.blue)("build.mode")} to ${(0,Oo.green)("'development'")} in your app config.`),process.exit(1))}function Zi(e,t,n=process.env,o=!1){!e.environmentUrl&&n.DT_APP_ENVIRONMENT_URL?.trim()&&(e.environmentUrl=n.DT_APP_ENVIRONMENT_URL);let r=qi(t,e),i=qi(Xi(o,r.build?.sourceRoot,r?.root),r);return i.oauth2File=Oc(i.root),i.environmentUrl&&(i.environmentUrl=Ev(i.environmentUrl)),i}var $e,Ar,ko,Oo,fd,me=g(()=>{"use strict";$e=require("path"),Ar=require("fs"),ko=require("lodash"),Oo=require("chalk");Do();Dc();md();v();C();fd={assets:{ignore:[]},actions:{build:{entryPoint:"src/main.tsx",tsconfig:"tsconfig.json"}}}});function Pv(){let e=null;return{async init(t,n,o=process.env,r="default",i=!1,s){if(e)throw new Error("Config module has already been initialized. Cannot initialize twice.");gd(n,t),Su(n);let a=t.root??process.cwd(),c=t.environmentUrl??o.DT_APP_ENVIRONMENT_URL?.trim()??n.environmentUrl;await Tu(hc(a),{...n,environmentUrl:c},r);let p=Zi(t,n,o,i);hd(p),await yd(p),await bd(p),bo.registerAll(Eu({root:p.root,plugins:p.plugins})),s&&(p=await s(p)),e=wd(p)},getConfig(){if(!e)throw new Error("Config module has not been initialized. Call init() first.");return e},isInitialized(){return e!==null},invalidate(){e=null}}}function wd(e){return Object.getOwnPropertyNames(e).forEach(t=>{let n=e[t];n&&typeof n=="object"&&!Object.isFrozen(n)&&wd(n)}),Object.freeze(e)}var T,M=g(()=>{"use strict";fc();Oi();fr();hr();me();T=Pv()});function Av(){return parseInt(process.env.DT_APP_DISABLE_TELEMETRY)===1}function Dv(e,t){l?.debug("Creating a new HTTP and HTTPS interceptor for tracing",O),[Td.default,Sd.default].forEach(o=>{let r=o.request;o.request=function(){let i;try{arguments[0]instanceof Dr.URL?i=arguments[0]:typeof arguments[0]=="string"?i=new Dr.URL(arguments[0]):i=new Dr.URL(`${arguments[0].protocol}//${arguments[0].hostname}${arguments[0].path}`)}catch{return r.apply(null,arguments)}for(let p of t)if(p.startsWith(i.origin))return r.apply(null,arguments);l?.debug(`Tracing request ${i.toString()}`,O);let s=e.traceWebRequest(i.toString()),a=0;(arguments[0]instanceof Dr.URL||typeof arguments[0]=="string")&&(a=1),arguments[a]=arguments[a]??{},arguments[a].headers||(arguments[a].headers={}),arguments[a].headers[jn.webRequestTagHeader]=s.getTag(),s.start();let c=r.apply(null,arguments);return c.once("response",p=>{s.stop(p.statusCode)}),c}})}async function an(e){if(Av()){l?.debug("Telemetry disabled",O);return}!e&&T.isInitialized()&&(e=T.getConfig()),l?.debug("Initializing telemetry",O);let t=process.env.DT_APP_TELEMETRY_DEV_ENDPOINT==="1"?JSON.parse((0,Bn.readFileSync)((0,Fc.join)(__dirname,"cli","../../../src/utils/reporting/telemetry.dev.json"),"utf8")):{beaconEndpoint:"https://bf96767wvv.bf.dynatrace.com/mbeacon",applicationId:"4b1eddd3-a461-4e9b-9596-6d61a8a2e876"};if(l?.debug(`Using telemetry endpoint ${t.beaconEndpoint}`,O),Gu(),Or=await Ju(zu()),Rr=new jn.OpenKitBuilder(t.beaconEndpoint,t.applicationId,Or).withApplicationVersion(global.DT_APP_VERSION).withOperatingSystem((0,sn.platform)()).withLogLevel(global.VERBOSE_MODE?jn.LogLevel.Info:jn.LogLevel.Error).build(),await new Promise(o=>{Rr.waitForInit(r=>{r&&(X=Rr.createSession(),Nc=!0,Dv(X,[t.beaconEndpoint])),o(r)},3e4)})){l?.debug("Successfully initialized OpenKit",O),l?.debug(`Telemetry enabled: Session ID "${Or}"`,O),Un={appId:e?.app?.id,appVersion:e?.app?.version,environmentUrl:e?.environmentUrl};try{let o="";if((0,Bn.existsSync)(kc)){let i=(await(0,ts.readFile)(kc)).toString();if(i.length===xv&&(es=i,X.identifyUser(i),l?.debug("Identification successful",O)),e?.oauth2File&&(0,Bn.existsSync)(e?.oauth2File)){let s=W(e.oauth2File),a=s?.app_token?.access_token||s?.toolkit_token?.access_token;if(a){let{email:c}=(0,Ic.decode)(a);o=c}}}else if(e?.oauth2File&&(0,Bn.existsSync)(e.oauth2File)){let r=await Ku(e.oauth2File);r?.userId&&(es=r.userId,o=r.emailAddress,X.identifyUser(r.userId),(0,ts.wri