@datadog/vite-plugin 3.2.7 → 3.2.9-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/index.js +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/index.mjs +1 -1
- package/dist/src/index.mjs.map +1 -1
- package/package.json +3 -2
package/dist/src/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{File as o}from"buffer";import r,{mkdtemp as s}from"fs/promises";import i from"fs";import{JsonStreamStringify as a}from"json-stream-stringify";import u from"path";import{Readable as c}from"stream";import{spawn as d}from"child_process";import{randomBytes as l,createHash as p,randomUUID as f}from"crypto";import m from"http";import h,{tmpdir as g}from"os";import*as y from"eslint-scope";import b from"jszip";import{glob as w}from"glob";import v from"pretty-bytes";import $ from"p-queue";import k from"@jridgewell/remapping";import{performance as x}from"perf_hooks";import{instrument as S}from"@datadog/js-instrumentation-wasm";import{simpleGit as E}from"simple-git";import I from"magic-string";import*as D from"vite";import A from"node:url";import P from"node:path";import j from"node:module";const M=A.fileURLToPath(import.meta.url),T=P.dirname(M),C=j.createRequire(import.meta.url),O="__datadog-helper-file",N=new RegExp(O),R=["development","production","test"],_=["datadoghq.com","us3.datadoghq.com","us5.datadoghq.com","datadoghq.eu","ddog-gov.com","us2.ddog-gov.com","ap1.datadoghq.com","ap2.datadoghq.com","datad0g.com"],F=_[0],z="datadog-build-plugins",L=t.bold.green,U=t.bold.yellow,B=["API_KEY","APP_KEY","SOURCEMAP_INTAKE_URL","APPS_INTAKE_URL","APPS_PUBLISH","APPS_UPLOAD_ASSETS","APPS_VERSION_NAME","APPS_AUTH_METHOD","SITE"],q=e=>process.env[`DATADOG_${e}`]||process.env[`DD_${e}`],V=(e,t)=>{if(void 0===e)return t;const n=e.toLowerCase();return!!["1","true","yes","on"].includes(n)||!["0","false","no","off"].includes(n)&&t},K=e=>{const t=[];return process.env[`DD_${e}`]&&t.push(`DD_${e}`),process.env[`DATADOG_${e}`]&&t.push(`DATADOG_${e}`),t},H=(e,t,n)=>{if(void 0===e)return;const o=(e=>{if("string"!=typeof e)return;const t=e.toLowerCase(),n=_.find((e=>e===t));if(n)return{site:n};const o=_.filter((e=>t.endsWith(`.${e}`)));if(!o.length)return;const r=o.reduce(((e,t)=>t.length>e.length?t:e)),s=t.slice(0,t.length-r.length-1);return s&&/^[a-z0-9-]+$/.test(s)?{site:r,subdomain:s}:void 0})(e);if(o)return o;n.push(`${t} "${e}" is not a supported Datadog site. See the site parameters in https://docs.datadoghq.com/getting_started/site/.`)},W=e=>null===e||"object"!=typeof e?"":Object.entries(e).map((([e,t])=>`${e}: ${"string"==typeof t?t:JSON.stringify(t)}`)).join(", "),J=e=>({"DD-EVP-ORIGIN":`${e.bundler}-build-plugin_${e.plugin}`,"DD-EVP-ORIGIN-VERSION":e.version}),G=async e=>{const{getForm:t,defaultHeaders:n={},zip:o=!0}=e,r=await t(),s=new Request("fake://url",{method:"POST",body:r});return{data:o?s.body.pipeThrough(new CompressionStream("gzip")):s.body,headers:{"Content-Encoding":o?"gzip":"multipart/form-data",...n,...Object.fromEntries(s.headers.entries())}}},Y=[400,401,403,404,405,409,413],Q=async e=>{const{auth:t,url:o,method:r="GET",getData:s,type:i="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return n((async(e,n)=>{let a;try{const e={method:r,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t&&"accessToken"in t?t.accessToken&&(n.Authorization=`Bearer ${t.accessToken}`):(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey)),"function"==typeof s){const{data:t,headers:o}=await s();e.body=t,n={...n,...o}}a=await fetch(o,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){let t=`HTTP ${a.status} ${a.statusText}`;try{const e=(e=>{try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t)if("errors"in t&&Array.isArray(t.errors)){const e=t.errors.map(W).filter((e=>e.length>0)).join("\n");if(e)return e}else{const e=W(t);if(e)return e}}catch{}return e})(await a.text());e&&(t+=`\n${e}`)}catch{}if(Y.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===i?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},Z=e=>({message:t,context:n})=>Q({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:e.packageName||z,message:t,service:"build-plugins",team:"language-foundations",env:e.env,version:e.version,bundler:{name:e.bundler.name,version:e.bundler.version},metadata:e.metadata,...n};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}}),X=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),ee=e=>e.includes(O),te=e=>{const t={bundler:e.bundler,errors:e.errors,metadata:e.metadata,warnings:e.warnings,logs:e.logs,timings:e.timings,start:e.start,end:e.end,duration:e.duration,writeDuration:e.writeDuration,entries:[],inputs:[],outputs:[]};for(const n of e.entries||[]){const e={...n,inputs:[],outputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),n.outputs&&(e.outputs=n.outputs.map((e=>e.filepath))),t.entries.push(e)}for(const n of e.inputs||[]){const e={...n,dependencies:[],dependents:[]};if(n.dependencies)for(const t of n.dependencies)e.dependencies.push(t.filepath);if(n.dependents)for(const t of n.dependents)e.dependents.push(t.filepath);t.inputs.push(e)}for(const n of e.outputs||[]){const e={...n,inputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),t.outputs.push(e)}return t},ne=e=>{const t=!!e.errorTracking?.sourcemaps,n=e.enableGit??!0;return t&&n},oe=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),o=n.getUTCHours(),r=n.getUTCMinutes(),s=n.getUTCSeconds(),i=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${o?`${o}h `:""}${r?`${r}m `:""}${s?`${s}s`:""}`.trim();return`${a}${!a||i?` ${i}ms`:""}`.trim()},re=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const o=Math.max(4,t-n.length),r=Math.min(10,Math.floor(o/2)),s=o-r;return`${e.slice(0,r)}${n}${e.slice(-s)}`},se=(e="")=>{try{if(!e||e.startsWith("git@"))return e;const t=new URL(e),n="/"===t.pathname?"":t.pathname;return`${t.protocol?`${t.protocol}//`:""}${t.host}${n}`}catch{return e}},ie=e=>e.trim().toLowerCase().replace(/[^a-z0-9_:./-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown",ae=e=>Object.entries(e).map((([e,n])=>` - ${e}: ${t.bold.green((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if(Array.isArray(e))return e.join(", ");if("object"==typeof e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return e?.toString()??""})(n))}`)).join("\n"),ue={debug:0,info:1,warn:2,error:3,none:4},ce=e=>e.split(">").map(X).join(">"),de=(e,n,o,r)=>{const s=ce(e);return(i,a="debug",{forward:u,context:c}={})=>{let d=t.dim,l=console.log;"error"===a?(d=t.red,l=console.error):"warn"===a?(d=t.yellow,l=console.warn):"info"===a&&(d=t.cyan,l=console.log);const p=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.name}|${s}]`,f="string"==typeof i?i:JSON.stringify(i,null,2);if(o.logs.push({bundler:n.bundler.name,pluginName:e,type:a,message:f,time:Date.now()}),"error"===a&&o.errors.push(f),"warn"===a&&o.warnings.push(f),u){const t=async()=>{try{const t=Z(n);await t({message:f,context:{plugin:e,status:a,...c}})}catch(t){de(e,n,o,r)(`Error forwarding log: ${t}`,"debug")}};o.queue.push(t())}ue[a]>=ue[r]&&l(`${d(p)} ${f}`)}},le=(e,n,o)=>(r,s={})=>{const{level:i="debug",start:a=!0,log:u=!0,tags:c=[]}=s,d={pluginName:e,label:r,spans:[],tags:[...c,`plugin:${e}`,`level:${i}`],logLevel:i,total:0};n.push(d);const l=()=>d.spans.filter((e=>!e.end)),p=n=>{l().length||(!d.spans.length&&u&&o(t.dim(`[${t.cyan(r)}] : start`),"debug"),d.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},f=(e,n=!0)=>{const s=l();if(s?.length){s.length>1&&o(`Timer ${t.cyan(r)} has more than one ongoing span.`,"debug");for(const t of s)t.end=e||Date.now()}else n&&o(`Timer ${t.cyan(r)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),p(e)}return{timer:d,resume:p,end:e=>{f(e,!1);const n=d.spans.reduce(((e,t)=>e+(t.end-t.start)),0);d.total=n,u&&o(`[${t.cyan(r)}] : ${t.cyan(oe(n))}`,i)},pause:f,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else d.tags.push(...e)}}},pe=(e,t,n="warn")=>o=>{const r=de(o,e,t,n);return{getLogger:r=>pe(e,t,n)(`${ce(o)}>${r}`),time:le(o,t.timings,r),error:(e,t)=>r(e,"error",t),warn:(e,t)=>r(e,"warn",t),info:(e,t)=>r(e,"info",t),debug:(e,t)=>r(e,"debug",t)}},fe=["buildEnd","buildStart","load","resolveId","transform","watchChange","writeBundle","buildRoot","init","buildReport","bundlerReport","git"],me=(e,t,n,o)=>{const r=n=>function(...r){const s=o.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),i=n.apply(this,r);return i instanceof Promise?i.finally((()=>{s.end()})):(s.end(),i)};return"object"==typeof n&&null!==n&&"handler"in n?{...n,handler:r(n.handler)}:r(n)},he=(e,t,n)=>{const o=e.getLogger(z);return e=>{const r=o.time(`hook | init ${n}`,{log:!1}),s=t(e).map((e=>((e,t)=>{const n={...e},o=X(e.name);for(const r of fe){const s=e[r];s&&(n[r]=me(o,r,s,t))}return n})(e,o))),i=s.map((e=>`plugin:${e.name}`));return r.tag(i),r.end(),s}},ge=new Set,ye=(e,t,n)=>{const o=e[t];if(o&&"object"==typeof o&&"enable"in o){const e=o.enable;if("boolean"!=typeof e&&void 0!==e&&(ge.has(t)||(ge.add(t),n.warn(`\`${t}.enable\` should be a boolean, got ${typeof e}. Non-boolean values are coerced today but will be rejected in the next major.`))),void 0!==e)return!!e}return!!o},be="apps",we="datadog-apps-plugin",ve="api/unstable/app-builder-code/apps",$e="datadog-apps-assets.zip",ke=/\.backend\.(ts|tsx|js|jsx)$/,xe=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],Se=["apiKey","oauth"],Ee=e=>{const t=e[be]||{},n=(e=>{if(void 0!==e){if(Se.includes(e))return e;throw new Error(`apps.authOverrides.method must be one of: ${Se.join(", ")}`)}})(q("APPS_AUTH_METHOD")||t.authOverrides?.method)||((e=>Boolean((q("API_KEY")||e.auth?.apiKey)&&(q("APP_KEY")||e.auth?.appKey)))(e)?"apiKey":"oauth");return{include:t.include||[],dryRun:t.dryRun??!V(q("APPS_UPLOAD_ASSETS"),!1),identifier:t.identifier?.trim(),name:t.name?.trim()||e.metadata?.name?.trim(),...null!=t.description&&{description:t.description},...null!=t.selfService&&{selfService:t.selfService},...null!=t.permissions&&{permissions:t.permissions},authOverrides:{method:n}}},Ie=async e=>r.rm(e,{force:!0,maxRetries:3,recursive:!0}),De=async e=>r.mkdir(e,{recursive:!0}),Ae=(e,t)=>{var n;n=u.dirname(e),i.mkdirSync(n,{recursive:!0}),i.writeFileSync(e,t,{encoding:"utf-8"})},Pe=e=>i.readFileSync(e,{encoding:"utf-8"}),je=e=>{try{return i.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},Me=async(e,t)=>{if("function"==typeof i.openAsBlob){const n=await i.openAsBlob(e,{type:t.contentType});return new o([n],t.filename)}{const n=c.toWeb(i.createReadStream(e)),r=await new Response(n).blob();return new o([r],t.filename,{type:t.contentType})}},Te=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await r.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t};var Ce=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Ce||{});const Oe=()=>import("oauth4webapi"),Ne=t.cyan.bold,Re=e=>e.toString("base64url"),_e=(e,t)=>{const n=(e=>"datad0g.com"===e?"f4bacdd2-0c8c-49f5-bf3e-a62ba3ec02e6":"e17b9ffa-3daf-4124-ba1b-4ac8c547d506")(e);return{authorizationUrl:`https://${t?`${t}.${e}`:`app.${e}`}/oauth2/v1/authorize`,cacheTokens:!0,clientId:n,openBrowser:!0,redirectUri:"http://localhost:8060",timeoutMs:3e5,tokenUrl:`https://api.${e}/oauth2/v1/token`}},Fe=e=>({client_id:e}),ze=e=>({issuer:new URL(e.authorizationUrl).origin,authorization_endpoint:e.authorizationUrl,token_endpoint:e.tokenUrl}),Le=(e,t)=>`${e}:${t.clientId}:${((e,t)=>p("sha256").update([t.clientId,e,t.authorizationUrl,t.tokenUrl].join("|")).digest("hex").slice(0,16))(e,t)}`,Ue=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=UTF-8"}),e.end(n)},Be=(e,t,n=Date.now())=>({accessToken:e.access_token,expiresAt:"number"==typeof e.expires_in?n+1e3*e.expires_in:void 0,expiresIn:e.expires_in,refreshToken:e.refresh_token,scope:e.scope,site:t,tokenType:e.token_type}),qe=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ve=e=>e instanceof Error?e.message:String(e),Ke=e=>{const t=Ve(e).toLowerCase();return"NoEntry"===(e=>qe(e)&&"string"==typeof e.code?e.code:void 0)(e)||t.includes("noentry")||t.includes("no matching entry")||t.includes("not found")},He=async(e,t)=>{const{AsyncEntry:n}=await import("@napi-rs/keyring");return new n("datadog-build-plugins:oauth",Le(e,t))},We=(e,t)=>new Error(`Could not ${e} Datadog OAuth token in the OS credential store. ${t instanceof Error?t.message:String(t)}`),Je=async(e,t)=>{try{const n=await He(e,t),o=await n.getPassword();if(!o)return;const r=JSON.parse(o);return(e=>{if(qe(e)&&1===e.version&&qe(e.token)&&"string"==typeof e.token.accessToken&&"string"==typeof e.token.clientId&&"string"==typeof e.token.site)return e})(r)?.token}catch(e){if(Ke(e))return;throw We("read",e)}},Ge=async(e,t,n,o=e.site)=>{if(t.cacheTokens)try{await(async(e,t,n)=>{try{const o=await He(e,n),r={version:1,token:t};await o.setPassword(JSON.stringify(r))}catch(e){throw We("save",e)}})(o,((e,t)=>({accessToken:e.accessToken,clientId:t,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(e,t.clientId),t),n.debug("Saved Datadog OAuth token to the OS credential store.")}catch(e){n.warn(`Could not save Datadog OAuth token to the OS credential store; continuing without a persistent cache. ${Ve(e)}`)}},Ye=async(e,t,n)=>{if(t.cacheTokens)try{await(async(e,t)=>{try{const n=await He(e,t);await n.deletePassword()}catch(e){if(!Ke(e))throw We("delete",e)}})(e,t)}catch(e){n.warn(`Could not delete cached Datadog OAuth token. ${Ve(e)}`)}},Qe=async(e,t,n)=>{if(!t.cacheTokens)return;let o;try{o=await Je(e,t)}catch(e){n.warn(`Could not read cached Datadog OAuth token; starting browser authorization. ${Ve(e)}`)}if(o){if(void 0===(r=o).expiresAt||r.expiresAt>Date.now()+3e5)return n.debug("Using cached Datadog OAuth access token."),(e=>({accessToken:e.accessToken,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(o);var r;if(o.refreshToken)try{n.debug("Refreshing cached Datadog OAuth access token.");const r=await(async(e,t,n)=>{const o=await Oe(),r=ze(t),s=Fe(t.clientId),i=await o.refreshTokenGrantRequest(r,s,o.None(),n),a=await o.processRefreshTokenResponse(r,s,i);return Be({...a,refresh_token:a.refresh_token||n},e)})(e,t,o.refreshToken);return await Ge(r,t,n),r}catch(o){return n.warn(`Cached Datadog OAuth token could not be refreshed; starting browser authorization. ${o instanceof Error?o.message:String(o)}`),void await Ye(e,t,n)}}},Ze=async(e,t,n)=>{const o=await Oe(),r=ze(t),s=Fe(t.clientId),i=Re(l(32)),a=await(async e=>(await Oe()).calculatePKCECodeChallenge(e))(i),u=Re(l(32)),c=(e=>{const t=new URL(e.authorizationUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("client_id",e.clientId),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("state",e.state),t})({authorizationUrl:t.authorizationUrl,clientId:t.clientId,codeChallenge:a,redirectUri:t.redirectUri,state:u}),p=(async e=>{const t=new URL(e.redirectUri),n=Number(t.port||80);if("http:"!==t.protocol)throw new Error("OAuth redirect URI must use http for the local OAuth callback.");if(!Number.isInteger(n)||n<=0)throw new Error("OAuth redirect URI must include a valid port.");let o,r=!1;const s=m.createServer();try{return await new Promise(((i,a)=>{const u=e=>{r||(r=!0,e())};s.on("request",((n,o)=>{const r=new URL(n.url||"/",t.origin);if(r.pathname!==t.pathname)return void Ue(o,404,"Not found.");let s;try{s=e.oauth.validateAuthResponse(e.authorizationServer,e.client,r,e.state)}catch(e){return Ue(o,400,"OAuth authorization failed. You may now close this tab."),void u((()=>a(e instanceof Error?e:new Error(String(e)))))}if(!s.get("code"))return Ue(o,400,"Missing OAuth authorization code. You may now close this tab."),void u((()=>a(new Error("Missing OAuth authorization code."))));Ue(o,200,"OAuth authorization complete. You may now close this tab."),u((()=>i({callbackParameters:s})))})),s.once("error",(e=>u((()=>a(e))))),o=setTimeout((()=>{u((()=>a(new Error(`Timed out waiting for OAuth callback after ${e.timeoutMs}ms.`))))}),e.timeoutMs);try{const e="localhost"===t.hostname?void 0:t.hostname;s.listen(n,e)}catch(e){u((()=>a(e instanceof Error?e:new Error(String(e)))))}}))}finally{o&&clearTimeout(o),s.listening&&(s.close(),s.closeAllConnections?.(),s.closeIdleConnections?.())}})({authorizationServer:r,client:s,oauth:o,redirectUri:t.redirectUri,state:u,timeoutMs:t.timeoutMs});n.info(`Authorize Datadog Apps upload:\n ${Ne(c.toString())}`),t.openBrowser&&((e,t)=>{const n="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};try{const e=d(n.command,n.args,{detached:!0,stdio:"ignore"});e.once("error",(e=>{t.warn(`Could not open browser automatically: ${Ve(e)}`)})),e.unref()}catch(e){t.warn(`Could not open browser automatically: ${Ve(e)}`)}})(c.toString(),n);return(async e=>{const t=await Oe(),n=ze(e),o=Fe(e.clientId),r=await t.authorizationCodeGrantRequest(n,o,t.None(),e.callbackParameters,e.redirectUri,e.codeVerifier),s=await t.processAuthorizationCodeResponse(n,o,r);return Be(s,e.site)})({callbackParameters:(await p).callbackParameters,clientId:t.clientId,codeVerifier:i,redirectUri:t.redirectUri,site:e,tokenUrl:t.tokenUrl,authorizationUrl:t.authorizationUrl})},Xe=new Map,et=async(e,t,n)=>{const o=_e(e,n),r=`${e}:${n??""}:${o.clientId}`;let s=Xe.get(r);return s||(s=(async(e,t,n)=>{const o=await Qe(e,t,n);return o?{persistAfterSuccessfulRequest:!1,token:o}:{persistAfterSuccessfulRequest:!0,token:await Ze(e,t,n)}})(e,o,t).catch((e=>{throw Xe.delete(r),e})),Xe.set(r,s)),s},tt='Set apps.authOverrides.method: "oauth" or DD_APPS_AUTH_METHOD=oauth to use OAuth, or set DD_API_KEY and DD_APP_KEY to use API/App key auth.';class nt extends Error{constructor(){super(`Missing authentication. ${tt}`),this.statusCode=400,this.name="MissingAuthenticationError"}}const ot=(e,t,n)=>{if("oauth"===e)return e=>(async({auth:e,log:t,...n})=>{const{site:o,siteSubdomain:r}=e,{persistAfterSuccessfulRequest:s,token:i}=await et(o,t,r);if(!i.accessToken)throw new Error("OAuth authentication did not return an access token.");const a=await Q({...n,auth:{accessToken:i.accessToken}});return s&&await Ge(i,_e(o,r),t,o),a})({...e,auth:t,log:n});if(t.apiKey&&t.appKey)return e=>Q({...e,auth:{apiKey:t.apiKey,appKey:t.appKey}});throw new nt};function rt(e,t){if(!function(e){return"Program"===e.type}(e))throw new Error(`Expected a Program node from this.parse() for ${t}, got ${e.type}`);return e}function st(e){return"object"==typeof e&&null!==e&&"Literal"===e.type&&"string"==typeof e.value}function it(e){return"type"===e.importKind||"type"===e.exportKind}function at(e,t){return function(e,t){const n=rt(e,t),o=function(e){const t=new Map;for(const n of e.body)if("FunctionDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"function"});else if("ClassDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"class"});else if("VariableDeclaration"===n.type)for(const e of n.declarations)"Identifier"===e.id.type&&t.set(e.id.name,{kind:"variable",init:e.init});else if("ImportDeclaration"===n.type)for(const e of n.specifiers)t.set(e.local.name,{kind:"import"});return t}(n),r=[];for(const e of n.body){if("ExportDefaultDeclaration"===e.type)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);if("ExportAllDeclaration"===e.type)throw new Error(`"export *" is not supported in .backend.ts files. Use explicit named exports instead: ${t}`);if("ExportNamedDeclaration"!==e.type)continue;e.declaration&&r.push(...dt(e.declaration,t).map((e=>({kind:"local",name:e,localName:e}))));const n="string"==typeof e.source?.value?e.source.value:null;for(const s of e.specifiers){if("Identifier"!==s.exported.type)continue;if("default"===s.exported.name)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);const e="Identifier"===s.local.type?s.local.name:"string"==typeof s.local.value?s.local.value:null;e&&(n?r.push({kind:"re-export",name:s.exported.name,localName:e,source:n}):("Identifier"===s.local.type&<(e,o,t),r.push({kind:"local",name:s.exported.name,localName:e})))}}return r}(e,t).map((e=>e.name))}const ut=new Set(["ArrayExpression","Literal","ObjectExpression","TemplateLiteral"]);function ct(e){return null==e||ut.has(e.type)}function dt(e,t){if("FunctionDeclaration"===e.type&&e.id)return[e.id.name];if("ClassDeclaration"===e.type)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${t}`);if("VariableDeclaration"===e.type)return e.declarations.flatMap((e=>{if("Identifier"!==e.id.type)throw new Error(`Destructured exports are not supported in backend files. Use individual named exports instead: ${t}`);if(ct(e.init))throw new Error(`Non-function export "${e.id.name}" in backend file ${t}. Only function exports are supported — use "export function ${e.id.name}(…) { }" instead.`);return[e.id.name]}));throw new Error(`Unsupported export declaration type "${e.type}" in backend file ${t}. Only function and variable exports are allowed.`)}function lt(e,t,n){const o=t.get(e);if(o){if("class"===o.kind)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${n}`);if("variable"===o.kind&&ct(o.init))throw new Error(`Non-function export "${e}" in backend file ${n}. Only function exports are supported — use "export function ${e}(…) { }" instead.`)}}function pt(e){const t=e.relativePath.split(u.sep).join("/");return`${p("sha256").update(t).digest("hex")}.${e.name}`}function ft(e){const t=[];for(const{exportName:n,queryName:o}of e)t.push(`export async function ${n}(...args) {`),t.push(` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(o)}, args);`),t.push("}"),t.push("");return t.join("\n")}function mt(e,t,n){const o=[];return o.push(`import { ${e} } from ${JSON.stringify(t)};`),function(e){try{return C.resolve("@datadog/action-catalog/action-execution",{paths:[e]}),!0}catch{return!1}}(n)&&o.push("import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';"),o.push(""),o.push('/** @param {import("./context.types").Context} $ */'),o.push("export async function main($) {"),o.push(" globalThis.$ = $;"),o.push(""),o.push(" // Register the $.Actions-based implementation for executeAction"),o.push(" if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\.datadoghq\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }"),o.push(""),o.push(" const args = $.backendFunctionArgs ?? [];"),o.push(` const result = await ${e}(...args);`),o.push(" return result;"),o.push("}"),o.join("\n")}function ht(e,t,n){const o={state:t},r=e=>{n._?.(e,o),function(e,t){return t[e.type]}(e,n)?.(e,o);for(const t of Object.keys(e))"type"!==t&&s(e[t])},s=e=>{if(Array.isArray(e))for(const t of e)gt(t)&&r(t);else gt(e)&&r(e)};r(e)}function gt(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function yt(e){ht(e,null,{_(e){const t=e;t.range||"number"!=typeof t.start||"number"!=typeof t.end||(t.range=[t.start,t.end])}});const t=y.analyze(e,{ecmaVersion:2022,ignoreEval:!0,sourceType:"module"}),n=new Map;for(const e of t.scopes)for(const t of e.references)n.set(t.identifier,t);return{scopeManager:t,referencesByIdentifier:n,moduleScope:$t(t)}}function bt(e,t){return t.referencesByIdentifier.get(e)?.resolved??void 0}function wt(e){return e.defs.some((e=>"ImportBinding"===e.type))}function vt(e,t){return t.moduleScope.set.get(e)}function $t(e){return e.scopes.find((e=>"module"===e.type))??e.globalScope}function kt(e,t,n){const o={scopeAnalysis:t,unsupportedAliases:xt(e,t)},r=[];return ht(e,o,{CallExpression(e,{state:t}){(function(e,t,n){const o=e.callee;if("Identifier"===o.type){if(Dt(o,t.unsupportedAliases,t.scopeAnalysis))throw Mt(n,"action-catalog call aliases");if(Dt(o,t.scopeAnalysis.actionFunctions,t.scopeAnalysis)){if(e.optional)throw Mt(n,"optional action-catalog calls");return!0}return!1}if("MemberExpression"!==o.type)return!1;if(!St(o,t.scopeAnalysis))return!1;if(e.optional||It(o))throw Mt(n,"optional or computed action-catalog namespace calls");return!0})(e,t,n)&&r.push(e)}}),r}function xt(e,t){const n=new Set;return ht(e,t,{VariableDeclarator(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.id.type&&"Identifier"===e.init?.type&&Dt(e.init,t.actionFunctions,t))return Pt(e,t,[e.id.name]);if("Identifier"===e.id.type&&"MemberExpression"===e.init?.type&&St(e.init,t))return Pt(e,t,[e.id.name]);if("ObjectPattern"!==e.id.type||"Identifier"!==e.init?.type||!Dt(e.init,t.actionNamespaces,t))return[];const n=e.id.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:jt(e.value))).map((e=>e.name));return Pt(e,t,n)}(e,t))n.add(o)},AssignmentExpression(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.left.type&&"Identifier"===e.right.type&&Dt(e.right,t.actionFunctions,t))return At([e.left],t);if("Identifier"===e.left.type&&"MemberExpression"===e.right.type&&St(e.right,t))return At([e.left],t);if("ObjectPattern"!==e.left.type||"Identifier"!==e.right.type||!Dt(e.right,t.actionNamespaces,t))return[];const n=e.left.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:jt(e.value)));return At(n,t)}(e,t))n.add(o)}}),n}function St(e,t){const n=Et(e);return!!n&&Dt(n,t.actionNamespaces,t)}function Et(e){return"Identifier"===e.object.type?e.object:"MemberExpression"===e.object.type?Et(e.object):void 0}function It(e){return!(!e.optional&&!e.computed)||"MemberExpression"===e.object.type&&It(e.object)}function Dt(e,t,n){return function(e,t,n){const o=bt(e,n);return!!o&&t.has(o)}(e,t,n.moduleScope)}function At(e,t){return e.flatMap((e=>{const n=bt(e,t.moduleScope);return n?[n]:[]}))}function Pt(e,t,n){const o=new Set(n);return t.moduleScope.scopeManager.getDeclaredVariables(e).filter((e=>o.has(e.name)))}function jt(e){switch(e.type){case"Identifier":return[e];case"ObjectPattern":return e.properties.flatMap((e=>"RestElement"===e.type?jt(e.argument):jt(e.value)));case"ArrayPattern":return e.elements.flatMap((e=>e?jt(e):[]));case"RestElement":return jt(e.argument);case"AssignmentPattern":return jt(e.left);case"MemberExpression":return[]}}function Mt(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Tt="@datadog/action-catalog";function Ct(e,t,n){const o=e.get(t);if(!o)return Lt(t,[],n.name);const r=bt(n,o.scopeAnalysis);return r?function(e,t){return t.defs.some((t=>t.name===e))}(n,r)?Ut(t,[],n.name):Rt({modules:e,visitedExports:new Set},t,r,[]):Ut(t,[],n.name)}function Ot(e,t,n,o){const r=e.modules.get(t);if(!r)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"export",exportName:n,message:`Module '${e}' was not collected while resolving export '${n}'.`,hops:t}}(t,o,n);if("default"===n)return Ft(t,o,n);const s=`${t}\0${n}`;if(e.visitedExports.has(s))return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"cycle",exportName:n,message:`Resolving export '${n}' from module '${e}' would cycle through the module graph.`,hops:t}}(t,o,n);e.visitedExports.add(s);try{const t=r.exportsByName.get(n);return t?function(e,t,n,o,r){if("unsupported"===o.kind)return function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-export",exportName:n,exportReason:o,message:`Export '${n}' from module '${e}' is unsupported: ${o}.`,hops:t}}(t.id,r,n,o.reason);if("re-export"===o.kind)return"default"===o.importedName?Ft(t.id,r,n):Ot(e,o.resolvedId,o.importedName,[...r,{kind:"re-export",moduleId:t.id,exportName:n,sourceModuleId:o.resolvedId,sourceExportName:o.importedName}]);return Rt(e,t.id,o.variable,[...r,{kind:"local-export",moduleId:t.id,exportName:n,localName:o.variable.name}])}(e,r,n,t,o):function(e,t,n,o){let r;for(const s of t.starExports){const i=Ot(e,s.resolvedId,n,[...o,{kind:"star-export",moduleId:t.id,exportName:n,sourceModuleId:s.resolvedId}]);if("unsupported"===i.kind){if("missing-export"===i.reason)continue;return i}if(!r||!Nt(r,i)){if(r)return _t(t.id,o,n);r=i}}return r??function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-export",exportName:n,message:`Module '${e}' does not expose export '${n}'.`,hops:t}}(t.id,o,n)}(e,r,n,o)}finally{e.visitedExports.delete(s)}}function Nt(e,t){return e.moduleId===t.moduleId&&e.variable===t.variable}function Rt(e,t,n,o){const r=e.modules.get(t);if(!r)return Lt(t,o,n.name);const s=r.importsByVariable.get(n);if(s)return function(e,t,n,o,r){if("default"===o.kind)return zt(t,r,n);if("namespace"===o.kind)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"namespace-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported namespace import.`,hops:t}}(t,r,n);if("default"===o.importedName)return zt(t,r,n);return Ot(e,o.resolvedId,o.importedName,[...r,{kind:"import",moduleId:t,localName:n,exportName:o.importedName,sourceModuleId:o.resolvedId}])}(e,r.id,n.name,s,o);const i=r.topLevelBindingsByVariable.get(n);return i?"const"===i.kind?{kind:"local",moduleId:r.id,variable:n,binding:i,hops:o}:"mutable"===i.kind?function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"mutable-binding",variableName:n,declarationKind:o,message:`Variable '${n}' in module '${e}' is declared with mutable '${o}'.`,hops:t}}(r.id,o,n.name,i.declarationKind):function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-binding",variableName:n,bindingReason:o,message:`Variable '${n}' in module '${e}' has unsupported binding: ${o}.`,hops:t}}(r.id,o,n.name,i.reason):function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-static-binding",variableName:n,message:`Variable '${n}' in module '${e}' does not have a recorded top-level static binding.`,hops:t}}(r.id,o,n.name)}function _t(e,t,n){return{kind:"unsupported",moduleId:e,reason:"ambiguous-star-export",exportName:n,message:`Module '${e}' exposes ambiguous star exports for '${n}'.`,hops:t}}function Ft(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-export",exportName:n,message:`Export '${n}' from module '${e}' resolves through an unsupported default export.`,hops:t}}function zt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported default import.`,hops:t}}function Lt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"variable",variableName:n,message:`Module '${e}' was not collected while resolving variable '${n}'.`,hops:t}}function Ut(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unresolved-identifier",variableName:n,message:`Identifier '${n}' in module '${e}' is not a resolvable reference.`,hops:t}}function Bt(e,t,n){const o=Xt(n);switch(o.type){case"Literal":return function(e,t){if("string"==typeof t.value)return{kind:"resolved",moduleId:e,value:t.value};return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-string-literal",valueType:t,message:`Literal value type '${t}' in module '${e}' is not a string.`}}(e,typeof t.value)}(t,o);case"TemplateLiteral":return function(e,t){if(t.expressions.length>0)return function(e){return{kind:"unsupported",moduleId:e,reason:"dynamic-template-literal",message:`Dynamic template literals in module '${e}' cannot be resolved to static strings.`}}(e);return{kind:"resolved",moduleId:e,value:t.quasis.map((e=>e.value.cooked??e.value.raw)).join("")}}(t,o);case"Identifier":return function(e,t,n){const o=Ct(e.modules,t,n);if("unsupported"===o.kind)return cn(o,n.name);if(!o.binding.expression)return dn(o.moduleId,o.variable.name);if(e.seenVariables.has(o.variable))return on(o.moduleId,o.variable.name);e.seenVariables.add(o.variable);try{return Bt(e,o.moduleId,o.binding.expression)}finally{e.seenVariables.delete(o.variable)}}(e,t,o);case"MemberExpression":return function(e,t,n){const o=qt(e,t,n);if("unsupported"===o.kind)return o;return Bt(e,o.moduleId,o.expression)}(e,t,o);default:return function(e,t){return{kind:"unsupported",moduleId:e,reason:"unsupported-expression",expressionType:t,message:`Expression type '${t}' in module '${e}' cannot be resolved to a static string.`}}(t,o.type)}}function qt(e,t,n){if(n.optional)return function(e){return{kind:"unsupported",moduleId:e,reason:"optional-member-expression",message:`Optional member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if(n.computed)return function(e){return{kind:"unsupported",moduleId:e,reason:"computed-member-expression",message:`Computed member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if("Identifier"!==n.property.type)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-static-member-property",propertyType:t,message:`Member property type '${t}' in module '${e}' is not statically named.`}}(t,n.property.type);const o=Vt(e,t,n.object);return"unsupported"===o.kind?o:function(e,t,n){let o;for(const r of t.properties){if("SpreadElement"===r.type)return un(e);if(r.computed)return nn(e);if(Zt(r)===n){if(o)return rn(e,n);if("init"!==r.kind)return tn(e,n);if(!Kt(r))return an(e,n,r.value.type);o=r}}if(!o)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"missing-object-property",propertyName:t,message:`Static object in module '${e}' does not have property '${t}'.`}}(e,n);return{kind:"resolved",moduleId:e,expression:o.value}}(o.moduleId,o.expression,n.property.name)}function Vt(e,t,n){if("Super"===n.type)return sn(t,n.type);const o=Xt(n);if("ObjectExpression"===o.type)return{kind:"resolved",moduleId:t,expression:o};if("MemberExpression"===o.type){const n=qt(e,t,o);return"unsupported"===n.kind?n:Vt(e,n.moduleId,n.expression)}if("Identifier"!==o.type)return sn(t,o.type);const r=Ct(e.modules,t,o);if("unsupported"===r.kind)return cn(r,o.name);if(!r.binding.expression)return dn(r.moduleId,r.variable.name);if(e.mutatedImportedObjectVariables.has(r.variable))return function(e,t){return{kind:"unsupported",moduleId:e,reason:"imported-object-mutation",variableName:t,message:`Imported object '${t}' from module '${e}' is mutated in the module graph.`}}(r.moduleId,r.variable.name);if(e.seenVariables.has(r.variable))return on(r.moduleId,r.variable.name);e.seenVariables.add(r.variable);try{return Vt(e,r.moduleId,r.binding.expression)}finally{e.seenVariables.delete(r.variable)}}function Kt(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function Ht(e){const t=new Set;for(const n of e.values())ht(n.ast,{modules:e,mutatedVariables:t,record:n},{AssignmentExpression(e,{state:t}){Jt(e.left,t)},UpdateExpression(e,{state:t}){Jt(e.argument,t)},UnaryExpression(e,{state:t}){"delete"===e.operator&&Jt(e.argument,t)},ForInStatement(e,{state:t}){Wt(e.left,t)},ForOfStatement(e,{state:t}){Wt(e.left,t)}});return t}function Wt(e,t){"VariableDeclaration"!==e.type&&Jt(e,t)}function Jt(e,t){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&Jt(e.left,t):Jt(e.argument,t);else for(const n of e.elements)n&&Jt(n,t);else for(const n of e.properties)Jt("RestElement"===n.type?n.argument:n.value,t);else{const n=Qt(e);n&&Gt(n,t)}else Gt(e,t)}function Gt(e,t){const n=Yt(t,e,new Set);n&&t.mutatedVariables.add(n)}function Yt(e,t,n){const o=bt(t,e.record.scopeAnalysis);if(!o||n.has(o))return;if(n.add(o),wt(o)){const n=Ct(e.modules,e.record.id,t);return"local"===n.kind?n.variable:void 0}const r=function(e){for(const t of e.defs){const e=t.node;if("VariableDeclarator"===e.type&&e.init)return e.init}return}(o);if(!r)return;const s=function(e){const t=Xt(e);if("Identifier"===t.type)return t;if("MemberExpression"===t.type)return Qt(t);return}(r);return s?Yt(e,s,n):void 0}function Qt(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?Qt(e.object):void 0}function Zt(e){return"Identifier"===e.key.type?e.key.name:"Literal"===e.key.type&&"string"==typeof e.key.value?e.key.value:void 0}function Xt(e){let t=e;for(;en(t);)t=t.expression;return t}function en(e){const t=e.type;return("TSAsExpression"===t||"TSSatisfiesExpression"===t||"TSNonNullExpression"===t||"TSTypeAssertion"===t)&&!!e.expression}function tn(e,t){return{kind:"unsupported",moduleId:e,reason:"accessor-object-property",propertyName:t,message:`Static object property '${t}' in module '${e}' is an accessor.`}}function nn(e){return{kind:"unsupported",moduleId:e,reason:"computed-object-property",message:`Computed object properties in module '${e}' cannot be resolved to static strings.`}}function on(e,t){return{kind:"unsupported",moduleId:e,reason:"cycle",variableName:t,message:`Resolving variable '${t}' in module '${e}' would cycle through static string values.`}}function rn(e,t){return{kind:"unsupported",moduleId:e,reason:"duplicate-object-property",propertyName:t,message:`Static object in module '${e}' has duplicate property '${t}'.`}}function sn(e,t){return{kind:"unsupported",moduleId:e,reason:"non-object-member-value",expressionType:t,message:`Expression type '${t}' in module '${e}' is not a static object value.`}}function an(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unsupported-object-property-value",propertyName:t,valueType:n,message:`Static object property '${t}' in module '${e}' has unsupported value type '${n}'.`}}function un(e){return{kind:"unsupported",moduleId:e,reason:"object-spread",message:`Object spreads in module '${e}' cannot be resolved to static strings.`}}function cn(e,t){return{kind:"unsupported",moduleId:e.moduleId,reason:"static-definition-unsupported",variableName:t,definition:e,message:`Variable '${t}' could not be resolved to a static definition: ${e.message}`}}function dn(e,t){return{kind:"unsupported",moduleId:e,reason:"uninitialized-const",variableName:t,message:`Const variable '${t}' in module '${e}' does not have an initializer.`}}const ln=new Set(["node_modules",".yarn"]);function pn(e,t,n,o=[]){if(!jn(e,t))return null;const r=rt(n,e),s=yt(r),i=function(e,t){const n=function(e){return e.body.flatMap((e=>("ImportDeclaration"===e.type||"ExportNamedDeclaration"===e.type||"ExportAllDeclaration"===e.type)&&e.source&&st(e.source)?[e.source.value]:[]))}(e);return t.map(((e,t)=>({source:n[t]??e,resolvedId:e})))}(r,o);return{id:e,ast:r,scopeAnalysis:s,staticDependencies:i,unsupportedDependencies:An(r),importsByVariable:fn(r,s,i),exportsByName:mn(r,s,i),starExports:yn(r,i),topLevelBindingsByVariable:bn(r,s)}}function fn(e,t,n){const o=new Map;for(const r of e.body){if("ImportDeclaration"!==r.type||!st(r.source))continue;const e=Dn(n,r.source.value);for(const n of r.specifiers){const[r]=t.scopeManager.getDeclaredVariables(n);r&&("ImportSpecifier"!==n.type?o.set(r,{kind:"ImportDefaultSpecifier"===n.type?"default":"namespace",resolvedId:e}):o.set(r,{kind:"named",importedName:En(n.imported),resolvedId:e}))}}return o}function mn(e,t,n){const o=new Map;for(const r of e.body)"ExportNamedDeclaration"!==r.type?"ExportDefaultDeclaration"!==r.type?"ExportAllDeclaration"===r.type&&gn(r,n,o):o.set("default",{kind:"unsupported",reason:"default export"}):hn(r,t,n,o);return o}function hn(e,t,n,o){if(e.declaration)!function(e,t,n){if(!e)return;if("VariableDeclaration"===e.type){for(const o of e.declarations){const e=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const t of e)n.set(t.name,{kind:"unsupported",reason:"binding pattern export"});continue}const[r]=e;r&&n.set(o.id.name,{kind:"local",variable:r})}return}if(("FunctionDeclaration"===e.type||"ClassDeclaration"===e.type)&&e.id){const[o]=t.scopeManager.getDeclaredVariables(e);o&&n.set(e.id.name,{kind:"local",variable:o})}}(e.declaration,t,o);else if(e.source&&st(e.source)){const t=Dn(n,e.source.value);for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);"default"!==e?o.set(e,{kind:"re-export",importedName:En(n.local),resolvedId:t}):o.set(e,{kind:"unsupported",reason:"default re-export",resolvedId:t})}}else for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=En(n.exported);if("default"===e){o.set(e,{kind:"unsupported",reason:"default export"});continue}const r=vt(En(n.local),t);o.set(e,r?{kind:"local",variable:r}:{kind:"unsupported",reason:"unresolved local export"})}}function gn(e,t,n){const o=In(e);o&&st(e.source)&&n.set(o,{kind:"unsupported",reason:"namespace re-export",resolvedId:Dn(t,e.source.value)})}function yn(e,t){return e.body.flatMap((e=>"ExportAllDeclaration"!==e.type||In(e)||!st(e.source)?[]:[{resolvedId:Dn(t,e.source.value)}]))}function bn(e,t){const n=new Map;for(const o of e.body)wn(o,t,n);return function(e,t,n){ht(e,{scopeAnalysis:t,bindings:n},{AssignmentExpression(e,{state:t}){kn(e.left,t.scopeAnalysis,t.bindings)},UpdateExpression(e,{state:t}){kn(e.argument,t.scopeAnalysis,t.bindings)},UnaryExpression(e,{state:t}){"delete"===e.operator&&kn(e.argument,t.scopeAnalysis,t.bindings)},ForInStatement(e,{state:t}){$n(e.left,t.scopeAnalysis,t.bindings)},ForOfStatement(e,{state:t}){$n(e.left,t.scopeAnalysis,t.bindings)}})}(e,t,n),n}function wn(e,t,n){if("VariableDeclaration"===e.type)return void vn(e,t,n);if("ExportNamedDeclaration"===e.type&&"VariableDeclaration"===e.declaration?.type)return void vn(e.declaration,t,n);const o="ExportNamedDeclaration"===e.type||"ExportDefaultDeclaration"===e.type?e.declaration:e;if(o&&("FunctionDeclaration"===o.type||"ClassDeclaration"===o.type)&&o.id){const[e]=t.scopeManager.getDeclaredVariables(o);e&&n.set(e,{kind:"unsupported",reason:`${o.type} binding`})}}function vn(e,t,n){for(const o of e.declarations){const r=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const e of r)n.set(e,{kind:"unsupported",reason:"binding pattern"});continue}const[s]=r;s&&("const"===e.kind?n.set(s,{kind:"const",expression:o.init??null}):n.set(s,{kind:"mutable",declarationKind:e.kind}))}}function $n(e,t,n){"VariableDeclaration"!==e.type&&kn(e,t,n)}function kn(e,t,n){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&kn(e.left,t,n):kn(e.argument,t,n);else for(const o of e.elements)o&&kn(o,t,n);else for(const o of e.properties)kn("RestElement"===o.type?o.argument:o.value,t,n);else{const o=Sn(e);o&&xn(o,t,n,"mutated object binding")}else xn(e,t,n,"reassigned binding")}function xn(e,t,n,o){const r=bt(e,t);if(!r||wt(r)||!n.has(r))return;const s=n.get(r);"mutable"!==s?.kind&&n.set(r,{kind:"unsupported",reason:o})}function Sn(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?Sn(e.object):void 0}function En(e){return"Identifier"===e.type?e.name:String(e.value)}function In(e){const t=e.exported;return t?En(t):void 0}function Dn(e,t){return e.find((e=>e.source===t))?.resolvedId??t}function An(e){const t=[];return ht(e,t,{ImportExpression(e,{state:t}){const n=function(e){return Tn(e.source,"non-literal dynamic import")}(e);Pn(n)&&t.push({specifier:n,kind:"dynamic-import"})},CallExpression(e,{state:t}){if(function(e){return"Import"===e.callee.type}(e)){const n=function(e){return Tn(e.arguments[0],"non-literal dynamic import")}(e);Pn(n)&&t.push({specifier:n,kind:"dynamic-import"})}else(function(e){if("Identifier"!==e.callee.type||"require"!==e.callee.name)return!1;const[t]=e.arguments;return!t||!st(t)||Cn(t.value)})(e)&&t.push({specifier:Mn(e),kind:"require"})}}),t}function Pn(e){return"non-literal dynamic import"===e||Cn(e)}function jn(e,t){if(!xe.some((t=>e.endsWith(t))))return!1;const n=u.relative(u.resolve(t),e);return!n.startsWith("..")&&!u.isAbsolute(n)&&!n.split(u.sep).some((e=>ln.has(e)))}function Mn(e){return Tn(e.arguments[0],"local require")}function Tn(e,t){return st(e)?e.value:t}function Cn(e){return e.startsWith(".")||e.startsWith("/")}function On(e,t){return new Error(`Unsupported local module graph for ${e}: ${t} could hide an action-catalog connectionId.`)}function Nn(e,t,n){const o=new Set;return function(e,t,n,o){const r=[e],s=new Set;for(;r.length>0;){const i=r.shift();if(s.has(i))continue;s.add(i);const a=t.get(i);if(!a)throw On(e,`missing module record for ${i}`);o({entryId:e,moduleId:i,record:a});for(const t of a.unsupportedDependencies)throw On(e,`${t.kind} ${t.specifier}`);for(const o of a.staticDependencies){const s=o.resolvedId;if(jn(s,n)){if(!t.has(s))throw On(e,`uncollected local import ${s} from ${a.id}`);r.push(s)}}}}(e,t,n,(({record:e})=>{const n=function(e){const t=new Set,n=new Set;for(const r of e.body)if("ImportDeclaration"===r.type&&"string"==typeof(o=r.source.value)&&(o===Tt||o.startsWith(`${Tt}/`))&&!it(r))for(const e of r.specifiers)it(e)||("ImportNamespaceSpecifier"===e.type?n.add(e.local.name):t.add(e.local.name));var o;return{functions:t,namespaces:n}}(e.ast),r=function(e,t){const n=new Set,o=new Set;for(const r of e.scopeManager.scopes)for(const e of r.variables)wt(e)&&(t.functions.has(e.name)&&n.add(e),t.namespaces.has(e.name)&&o.add(e));return{moduleScope:e,actionFunctions:n,actionNamespaces:o}}(e.scopeAnalysis,n);for(const n of kt(e.ast,r,e.id)){const r=Rn(n,t,e);r&&o.add(r)}})),[...o].sort()}function Rn(e,t,n){const[o]=e.arguments;if(!o||"ObjectExpression"!==o.type)throw zn(n.id,"non-object action-catalog call arguments");const r=function(e,t){let n;for(const o of e.properties){if("SpreadElement"===o.type)throw zn(t,"spread object arguments");if(o.computed)throw zn(t,"computed object property keys");if(Fn(o)){if(n)throw zn(t,"multiple connectionId properties");if("init"!==o.kind)throw zn(t,"accessor connectionId properties");if(!_n(o))throw zn(t,"destructuring pattern in connectionId value");n=o}}return n}(o,n.id);if(!r)return;const s=function(e,t,n){return Bt({modules:e,mutatedImportedObjectVariables:Ht(e),seenVariables:new Set},t,n)}(t,n.id,r.value);if("resolved"===s.kind)return s.value;throw i=n.id,a=`static string resolution ${function(e){return"static-definition-unsupported"===e.reason?`${e.reason}/${e.definition.reason}`:e.reason}(s)}: ${s.message}`,new Error(`Unsupported action-catalog connectionId in ${i}: ${a}.`);var i,a}function _n(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function Fn(e){return"connectionId"===function(e){if("Identifier"===e.key.type)return e.key.name;if("Literal"===e.key.type&&"string"==typeof e.key.value)return e.key.value;return}(e)}function zn(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Ln=/^(?:\0|virtual:)/;function Un(e){const t=new Map;return{plugin:{name:"dd-backend-module-graph-collector",moduleParsed(n){const o=Bn(n.id);if(r=o,Ln.test(r))return;var r;const s=pn(o,e,n.ast,function(e){return e.importedIdResolutions?.map((({id:e})=>e))??[...e.importedIds]}(n).map(Bn));s&&t.set(s.id,s)}},getModuleRecords:()=>t}}function Bn(e){return e.split("?")[0]}function qn(e,t){const n=Un(t);return{plugin:n.plugin,getAllowedConnectionIds:()=>Nn(e,n.getModuleRecords(),t)}}function Vn(e,t){return{name:e,enforce:"pre",resolveId:e=>t[e]?{id:e,moduleSideEffects:!0}:null,load:e=>t[e]?t[e]:null}}function Kn(e,t,n=[]){return{configFile:!1,root:e,logLevel:"silent",build:{minify:!1,target:"esnext",rollupOptions:{output:{format:"es",exports:"named",inlineDynamicImports:!0},preserveEntrySignatures:"exports-only",treeshake:!1,onwarn(e,t){"MODULE_LEVEL_DIRECTIVE"!==e.code&&t(e)}}},resolve:{extensions:[...xe,".json"]},plugins:[Vn("dd-backend-resolve",t),...n]}}function Hn(e){return`${e.relativePath}/${e.name}`}async function Wn(e,t,n,o){const r=Hn(t),s=`virtual:dd-backend-dev:${r}`,i=function(e,t,n){return mt(e,t,n??process.cwd())}(t.name,t.absolutePath,n),a=qn(t.absolutePath,n);o.debug(`Bundling backend function "${r}" from ${t.absolutePath}`);const u=Kn(n,{[s]:i},[a.plugin]),c=await e({...u,build:{...u.build,write:!1,rollupOptions:{...u.build.rollupOptions,input:s,output:u.build.rollupOptions.output}}}),d=Array.isArray(c)?c[0]:c;if(!("output"in d))throw new Error(`Unexpected vite.build result for "${r}"`);const l="chunk"===d.output[0].type?d.output[0].code:"",p={...t,allowedConnectionIds:a.getAllowedConnectionIds()};return o.debug(`Bundled "${r}" (${l.length} bytes)`),{func:p,code:l}}async function Jn(e,t,n,o,r,s){const i=`https://api.${o.site}/api/v2/app-builder/queries/preview-async`,a=Hn(t);s.debug(`Calling Datadog API: ${i}`);const u=JSON.stringify({data:{type:"queries",attributes:{query:{id:f(),name:a,type:"action",properties:{spec:{fqn:"com.datadoghq.datatransformation.jsFunctionWithActions",inputs:{script:e,allowedConnectionIds:t.allowedConnectionIds,context:{backendFunctionArgs:n}}},onlyTriggerManually:!0}},template_params:{}}}}),c=await r({url:i,method:"POST",type:"json",getData:()=>({data:u,headers:{"Content-Type":"application/json"}})}),d=c.data?.id;if(!d)throw new Error("No receipt ID returned from Datadog API");return s.debug(`Query execution started with receipt: ${d}`),async function(e,t,n,o){const r=`https://api.${t.site}/api/v2/app-builder/queries/execution-long-polling/${e}`,s=10;for(let e=0;e<s;e++){o.debug(`Long-poll attempt ${e+1}/${s}...`);const t=await n({url:r,type:"json"});if(t.errors?.length){const e=t.errors.map((e=>e.detail||e.title)).join("; ");throw new Error(`Query execution failed: ${e}`)}const i=t.data?.attributes;if(o.debug(`Long-poll response, done: ${i?.done}`),i?.done){if(!i.outputs)throw new Error("Query execution completed without outputs");return i.outputs}}throw new Error("Query execution timed out")}(d,o,r,s)}function Gn(e,t,n){e.statusCode=t,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({success:!1,error:n}))}class Yn extends Error{constructor(e,t){super(t),this.statusCode=e}}async function Qn(e,t,n){const{functionName:o,args:r=[]}=await function(e){return new Promise(((t,n)=>{let o="";e.on("data",(e=>{o+=e.toString()})),e.on("end",(()=>{try{t(JSON.parse(o))}catch{n(new Error("Invalid JSON body"))}})),e.on("error",n)}))}(e);if(!o||"string"!=typeof o)throw new Yn(400,"Missing or invalid functionName");const s=t.get(o);if(!s)throw new Yn(404,`Backend function "${o}" not found`);return{...await n(s),args:r}}function Zn(e,t,n,o,r,s){const i=t=>Wn(e,t,r,s),a=t();return a.length>0&&s.info(`Dev server middleware active for ${a.length} backend function(s): ${a.map((e=>e.name)).join(", ")}`),o||s.warn(`Auth credentials not configured. The /__dd/executeAction endpoint will be unavailable. ${tt}`),(e,r,a)=>{if("POST"!==e.method)return void a();const u=(c=t(),new Map(c.map((e=>[pt(e),e]))));var c;if("/__dd/debugBundle"===e.url)(async function(e,t,n,o){try{const{code:r}=await Qn(e,n,o);t.statusCode=200,t.setHeader("Content-Type","text/plain"),t.end(r)}catch(e){Gn(t,e instanceof Yn?e.statusCode:500,e instanceof Error?e.message:"Internal server error")}})(e,r,u,i).catch((()=>{Gn(r,500,"Unexpected error")}));else if("/__dd/executeAction"===e.url){if(!o)return void Gn(r,400,`Auth credentials not configured. ${tt}`);(async function(e,t,n,o,r,s,i){try{const{func:a,code:u,args:c}=await Qn(e,n,o),d=Hn(a);i.debug(`Executing action: ${d} with args`);const l=await Jn(u,a,c,r,s,i);t.statusCode=200,t.setHeader("Content-Type","application/json"),t.end(JSON.stringify({success:!0,result:l}))}catch(e){const n=e instanceof Yn?e.statusCode:500,o=e instanceof Error?e.message:"Internal server error";i.debug(`Error handling executeAction: ${o}`),Gn(t,n,o)}})(e,r,u,i,n,o,s).catch((()=>{Gn(r,500,"Unexpected error")}))}else a()}}const Xn=async(e,t)=>{const n=(await Promise.all(e.map((e=>w(e,{absolute:!0,cwd:t,nodir:!0}))))).flat(),o=Array.from(new Set(n)).map((e=>u.relative(t,e))),r=(e=>{if(0===e.length)return"";const t=e[0].split(u.sep);let n="";for(let o=0;o<t.length-1;o++){const r=t.slice(0,o+1).join(u.sep);if(!e.every((e=>e.startsWith(`${r}${u.sep}`))))break;n=r}return n})(o);return o.map(((e,t)=>{const o=r?e.slice(r.length+1):e;return{absolutePath:n[t],relativePath:o.split(u.sep).join("/")}}))},eo=(e,t)=>ee(t)?O:t.startsWith(e)||u.isAbsolute(t)?t:u.resolve(e,t),to=(e,t)=>{let n,o=eo(process.cwd(),e);for(;!n;){const e=u.resolve(o,t);if(je(e)&&(n=e),o=o.split(u.sep).slice(0,-1).join(u.sep),[u.sep,""].includes(o))break}return n},no=(e,t)=>{const n=[...e].map((e=>eo(t||process.cwd(),e).split(u.sep))),o=n.length?Math.min(...n.map((e=>e.length))):0,r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0&&r.join(u.sep)||u.sep},oo=t.bold.red,ro=t.bold.yellow,so=e=>{const t=to(e,"package.json");if(t)try{const e=Pe(t);return JSON.parse(e)}catch(e){return}},io=(e,t,n)=>{if(n?.name&&n?.identifier)return{identifier:n?.identifier,name:n.name};const o=so(e);o||t.warn(ro("No package.json found to infer the app name."));const r=n?.name||o?.name?.trim();r||t.error(oo("Unable to determine the app name to compute the app identifier."));const s=((e,t)=>{const n=e||(e=>{if(e&&e.repository)return"string"==typeof e.repository?e.repository:"url"in e.repository?e.repository.url:void 0})(t);if(!n)return;const o=se(n.trim());return o?o.replace(/\.git$/,""):void 0})(n?.url,o);s||t.error(oo("Unable to determine the git remote to compute the app identifier."));const i=n?.identifier||((e,t)=>{if(!e||!t)return;const n=`${e}:${t}`;return p("sha256").update(n).digest("hex").slice(0,32)})(s,r);return i&&r||t.error(oo("Unable to compute the app identifier.")),{identifier:i,name:r}},ao=t.green.bold,uo=t.yellow.bold,co=t.cyan.bold,lo=t.bold,po=(e,t,n,o,r)=>{if(o)return o;if(!r)return;return`https://${n??"app"}.${t}${"upload"===e?`/app-builder/apps/edit/${r}?viewMode=preview`:`/app-builder/apps/${r}`}`},fo=(e,t)=>`Could not resolve the App Builder URL for this ${e} — find "${t}" in your App Builder apps list to view it.`,mo=(e,t={},n)=>async()=>{const o=await Me(e,{contentType:"application/zip",filename:$e});return G({getForm:()=>{const e=new FormData;e.append("name",n),e.append("bundle",o,$e);const t=q("APPS_VERSION_NAME")?.trim();return t&&e.append("version",t),e},defaultHeaders:t,zip:!1})},ho=async(e,t,n)=>{const o=[],r=[],s=t.doAuthenticatedRequest;if(!t.identifier)return o.push(new Error("No app identifier provided")),{errors:o,warnings:r};const i=(a=t.site,u=t.identifier,q("APPS_INTAKE_URL")||`https://api.${a}/${ve}/${u}/upload`);var a,u;const d=J({bundler:t.bundlerName,plugin:"apps",version:t.version}),l=ae({identifier:t.identifier,intakeUrl:i,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),p=`an archive of:\n - ${ao(e.assets.length.toString())} files\n - ${ao(v(e.size))}\n\nWith the configuration:\n${l}`;if(t.dryRun)return n.error(`\n${co("Dry run enabled")}\n\nSkipping assets upload.\nWould have uploaded ${p}`),{errors:o,warnings:r};try{const o=await s({url:i,method:"POST",type:"json",getData:mo(e.archivePath,d,t.name),onRetry:(e,t)=>{const o=`Failed to upload archive (attempt ${uo(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}});n.debug(`Uploaded ${p}\n`);const a=po("upload",t.site,t.siteSubdomain,o.app_builder_url,o.app_builder_id);if(a)n.info(`Your application is available at:\n ${co(a)}`);else{const e=fo("upload",t.name);r.push(e),n.warn(e)}const u=V(q("APPS_PUBLISH"),!0);if(o.version_id&&u){const e=((e,t)=>`https://api.${e}/${ve}/${t}/release/live`)(t.site,t.identifier),i=await s({url:e,method:"PUT",type:"json",getData:async()=>({data:c.from(JSON.stringify({version_id:o.version_id})),headers:{"Content-Type":"application/json",...d}}),onRetry:(e,t)=>{const o=`Failed to release version (attempt ${uo(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}}),a=po("release",t.site,t.siteSubdomain,i.app_builder_url,i.app_builder_id??o.app_builder_id);if(a)n.info(`Published uploaded version ${lo(o.version_id)} to live.\n ${co(a)}`);else{n.info(`Published uploaded version ${lo(o.version_id)} to live.`);const e=fo("release",t.name);r.push(e),n.warn(e)}}else o.version_id&&!u&&n.info(`Uploaded version ${lo(o.version_id)} as a draft (publish skipped).`)}catch(e){const t=e instanceof Error?e:new Error(String(e));o.push(t)}return{errors:o,warnings:r}},go=t.yellow.bold,yo=t.red.bold,bo="manifest.json";async function wo(e,t){const n=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-manifest-")),o=u.join(n,bo);try{await r.writeFile(o,JSON.stringify(function(e,t){const n={};for(const t of e)n[pt(t)]={allowedConnectionIds:[...t.allowedConnectionIds]};const o={backend:{functions:n}};null!=t.description&&(o.description=t.description),null!=t.selfService&&(o.selfService=t.selfService);const r=t.permissions?.protectionLevel??null,s=t.permissions?.runAs??null;return null==r&&null==s||(o.permissions={...null!=r&&{protectionLevel:r},...null!=s&&{runAs:s}}),o}(e,t),null,2))}catch(e){throw await Ie(n),e}return{manifestAsset:{absolutePath:o,relativePath:bo},cleanup:()=>Ie(n)}}const vo=async({backendOutputs:e,backendFunctions:t,context:n,doAuthenticatedRequest:o,options:s})=>{const a=n.getLogger(we),{auth:c,buildRoot:d,bundler:{name:l,outDir:p},git:f,version:m}=n,g=a.time("handle assets");let y,w,v;try{const n=a.time("resolve identifier"),{name:g,identifier:v}=io(d,a,{url:f?.remote,name:s.name,identifier:s.identifier});if(!v||!g)throw new Error("Missing apps identification.\nEither:\n - pass an 'options.apps.identifier' and 'options.apps.name' to your plugin's configuration.\n - have a 'name' and a 'repository' in your 'package.json'.\n - have a valid remote url on your git project.\n");n.end();const $=u.relative(d,p),k=[...s.include,`${$}/**/*`],x=await Xn(k,d);if(!x.length)return void a.debug("No assets to upload.");const S=new Set(e.values()),E=x.filter((e=>!S.has(e.absolutePath))).map((e=>({...e,relativePath:`frontend/${e.relativePath}`})));for(const[t,n]of e)E.push({absolutePath:n,relativePath:`backend/${t}.js`});const{manifestAsset:I,cleanup:D}=await wo(t,s);w=D,E.push(I);const A=a.time("archive assets"),P=await(async e=>{const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-")),n=u.join(t,$e),o=new b;for(const t of e)o.file(t.relativePath,i.createReadStream(t.absolutePath),{binary:!0,compression:"DEFLATE",compressionOptions:{level:9}});await new Promise(((e,t)=>{const r=i.createWriteStream(n),s=o.generateNodeStream({type:"nodebuffer",streamFiles:!0,compression:"DEFLATE",compressionOptions:{level:9}});s.on("error",t),r.on("error",t),r.on("close",e),s.pipe(r)}));const{size:s}=await r.stat(n);return{archivePath:n,size:s,assets:e}})(E);A.end(),y=u.dirname(P.archivePath);const j=a.time("upload assets"),{errors:M,warnings:T}=await ho(P,{bundlerName:l,doAuthenticatedRequest:o,dryRun:s.dryRun,identifier:v,name:g,site:c.site,siteSubdomain:c.siteSubdomain,version:m},a);if(j.end(),T.length>0&&a.warn(`${go("Warnings while uploading assets:")}\n - ${T.join("\n - ")}`),M.length>0){const e=M.map((e=>{const t=e.cause instanceof Error?e.cause.message:e.cause,n=e.message||e.stack||String(e);return t?`${t}\n${n}`:n})).join("\n - ");throw new Error(` - ${e}`)}}catch(e){v=e,a.error(`${yo("Failed to upload assets:")}\n${e?.message||e}`)}if(y&&await Ie(y),w&&await w(),g.end(),v)throw v};const $o=u.join(T,"./apps-runtime.mjs"),ko=async()=>{throw new Error("Dry run should not perform authenticated requests.")},xo=({bundler:e,context:t,options:n})=>{const o=t.getLogger(we),{auth:r,buildRoot:i}=t;t.inject({type:"file",position:Ce.MIDDLE,value:$o});const{setBackendFunctions:a,getBackendFunctions:c}=function(){const e=new Map;return{setBackendFunctions(t,n){e.set(t,n)},getBackendFunctions:()=>Array.from(e.values()).flat()}}();return{transform:{filter:{id:{include:[ke],exclude:[/node_modules/,/[/\\]dist[/\\]/]}},handler(e,t){const n=at(this.parse(e),t);if(0===n.length)return o.warn(`Backend file ${t} has no exported functions. Did you forget to add a named export?`),a(t,[]),{code:"",map:null};const{functions:r,proxyCode:s}=function(e,t,n){const o=u.relative(n,t).replace(ke,""),r=[],s=[];for(const n of e){const e={relativePath:o,name:n,absolutePath:t,allowedConnectionIds:[]};r.push(e),s.push({exportName:n,queryName:pt(e)})}return{functions:r,proxyCode:ft(s)}}(n,t,i);return a(t,r),o.debug(`Generated proxy for ${t} with ${r.length} export(s)`),{code:s,map:null}}},async closeBundle(){let a,d=new Map,l=c();if(l.length>0){const t=await async function(e,t,n,o){const r=await s(u.join(g(),"dd-apps-backend-")),i=new Map,a=new Map;o.debug(`Building ${t.length} backend function(s) via vite.build()`);for(const s of t){const t=pt(s),c=`\0dd-backend:${t}`,d=mt(s.name,s.absolutePath,n),l=qn(s.absolutePath,n),p=Kn(n,{[c]:d},[l.plugin]),f=await e({...p,build:{...p.build,write:!0,outDir:r,emptyOutDir:!1,rollupOptions:{...p.build.rollupOptions,input:{[t]:c},output:{...p.build.rollupOptions.output,entryFileNames:"[name].js"}}}}),m=Array.isArray(f)?f[0]:f;if("output"in m)for(const e of m.output){if("chunk"!==e.type||!e.isEntry)continue;const n=u.resolve(r,e.fileName);i.set(t,n),o.debug(`Backend function "${t}" output: ${n}`)}a.set(s.absolutePath,l.getAllowedConnectionIds())}return{outDir:r,outputs:i,functions:t.map((e=>({...e,allowedConnectionIds:a.get(e.absolutePath)})))}}(e.build,l,i,o);a=t.outDir,d=t.outputs,l=t.functions}try{const e=n.dryRun?ko:ot(n.authOverrides.method,r,o);await vo({backendOutputs:d,backendFunctions:l,context:t,doAuthenticatedRequest:e,options:n})}finally{a&&await Ie(a)}},configureServer(t){let s;try{s=ot(n.authOverrides.method,r,o)}catch(e){if(!(e instanceof nt))throw e}t.middlewares.use(Zn(e.build,c,r,s,i,o))}}},So=({options:e,context:t,bundler:n})=>{const o=t.getLogger(we),r=Ee(e);return"vite"!==t.bundler.name?(o.warn(`The apps plugin only supports Vite; skipping under '${t.bundler.name}'.`),[]):[{name:we,enforce:"post",vite:xo({bundler:n,context:t,options:r})}]},Eo="errorTracking",Io="datadog-error-tracking-plugin",Do=(e,n,o)=>{if(".map"!==u.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),s=u.relative(n,r),i=((e,t)=>{if(e.startsWith("/"))return u.join(e,t);try{const n=e.replace(/\/*$/,"/"),o=new URL(n),r=t.replace(/^[\\/]*/,"");return new URL(r,o).href}catch{return`${e}${t}`}})(e,s);return{minifiedFilePath:r,minifiedUrl:i,relativePath:s}},Ao=/[/]+|[\\]+/g,Po=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,jo=(e,t)=>{const n=e.replace(Po,"").split(Ao),o=t.replace(Po,"").split(Ao),r=n.join("/");let s="";for(let e=0;e<o.length;e+=1){const t=o.slice(-e).join("/");r.startsWith(t)&&(s=t)}return s},Mo=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,o]=await Promise.all([Te(e.minifiedFilePath),Te(e.sourcemapFilePath)]);return{file:n,sourcemap:o,repeatedPrefix:jo(e.relativePath,t)}})(e,n),s=[],i=[],a=new Map([["event",{type:"string",options:{contentType:"application/json",filename:"event"},value:JSON.stringify({...t,minified_url:e.minifiedUrl})}],["source_map",{type:"file",path:e.sourcemapFilePath,options:{filename:"source_map",contentType:"application/json"}}],["minified_file",{type:"file",path:e.minifiedFilePath,options:{filename:"minified_file",contentType:"application/javascript"}}]]);if(o)try{a.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{i.push(`${u.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){i.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&s.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||s.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&s.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||s.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&i.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:a,errors:s,warnings:i}},To=e=>{const t=e.message.match(/HTTP (\d{3})/);return t?`status_code:${t[1]}`:"status_code:unknown"},Co=e=>{const t=To(e);return"status_code:unknown"!==t?`error_type:http_${t.replace("status_code:","")}`:`error_type:${ie(e.name||"unknown")}`},Oo=(e,t,n)=>{const o=((e,t)=>`${e}|${t.join("|")}`)(t,n),r=e.metrics.get(o);r?r.value++:e.metrics.set(o,{name:t,value:1,tags:n})},No=(e,t,n)=>{Oo(e,"retry",[...e.baseTags,`attempt:${n}`,To(t),Co(t)])},Ro=(e,t)=>{Oo(e,"failure",[...e.baseTags,To(t),Co(t)])},_o=(e,t)=>{if(!t.sendMetrics)return;if(!e.metrics.size)return;const n=(e=>{const t=Math.floor(Date.now()/1e3);return Array.from(e.metrics.values()).map((e=>({metric:`sourcemaps.upload.${e.name}`,type:"count",points:[[t,e.value]],tags:e.tags})))})(e);for(const e of n)t.addMetric(e)},Fo=t.green.bold,zo=t.yellow.bold,Lo=t.red.bold,Uo=(e,t={})=>async()=>G({getForm:async()=>{const t=new FormData;for(const[n,o]of e.content){const e="file"===o.type?await Me(o.path,o.options):new Blob([o.value],{type:o.options.contentType});t.append(n,e,o.options.filename)}return t},defaultHeaders:t,zip:!0}),Bo=async(e,t,n,o)=>{const r=[],s=[];if(!n.apiKey)return r.push({error:new Error("No authentication token provided")}),{errors:r,warnings:s};if(0===e.length)return s.push("No sourcemaps to upload"),{errors:r,warnings:s};const i=o.time("Queue uploads"),a=new($.default?$.default:$)({concurrency:t.maxConcurrency}),u=(c=n.site,q("SOURCEMAP_INTAKE_URL")||`https://sourcemap-intake.${c}/api/v2/srcmap`);var c;const d=J({bundler:n.bundlerName,plugin:"sourcemaps",version:n.version}),l=(e=>({metrics:new Map,baseTags:[`service:${e.service}`]}))(t),p=ae({...t,intakeUrl:u,outDir:n.outDir,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),f=`\nUploading ${Fo(e.length.toString())} sourcemaps with configuration:\n${p}`;o.debug(f);const m=[];for(const i of e){const e={sourcemap:i.content.get("source_map")?.path.replace(n.outDir,"."),file:i.content.get("minified_file")?.path.replace(n.outDir,".")};m.push(a.add((async()=>{try{await Q({auth:{apiKey:n.apiKey},url:u,method:"POST",getData:Uo(i,d),onRetry:(t,n)=>{No(l,t,n);const r=`Failed to upload ${zo(e.sourcemap)} | ${zo(e.file)}:\n ${t.message}\nRetrying ${n}/5`;s.push(r),o.debug(r)}})}catch(n){if(Ro(l,n),r.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}i.end(),o.debug(`Queued ${Fo(e.length.toString())} uploads.`);try{await Promise.all(m),await a.onIdle()}finally{_o(l,n)}return{warnings:s,errors:r}},qo=async(e,t,n)=>{const o=n.time("get sourcemaps files"),r=((e,t)=>{if(!t.outputs||0===t.outputs.length)throw new Error("No output files found.");return t.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...Do(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:t.outDir,outputs:t.outputs});o.end();const s=n.time("send sourcemaps");await(async(e,t,n,o)=>{const r=Date.now(),s=t.minifiedPathPrefix,i={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=o.time("Compute payloads"),u=await Promise.all(e.map((e=>Mo(e,i,s,n.git))));a.end();const c=u.map((e=>e.errors)).flat(),d=u.map((e=>e.warnings)).flat();if(d.length>0&&o.warn(`Warnings while preparing payloads:\n - ${d.join("\n - ")}`),c.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${c.join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e);return}const l=o.time("Upload sourcemaps"),{errors:p,warnings:f}=await Bo(u,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir,site:n.site,sendMetrics:n.sendMetrics,addMetric:n.addMetric},o);if(l.end(),o.debug(`Done uploading ${Fo(`${e.length-p.length}/${e.length}`)} sourcemaps in ${Fo(oe(Date.now()-r))}.`),p.length>0){const e=`Failed to upload some sourcemaps:\n - ${p.map((({metadata:e,error:t})=>{const n=t.cause||t.stack||t.message;return e?`${Lo(e.file)} | ${Lo(e.sourcemap)} :\n${n}`:n})).join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e)}f.length>0&&o.warn(`Warnings while uploading sourcemaps:\n - ${f.join("\n - ")}`)})(r,e.sourcemaps,{addMetric:t.addMetric,apiKey:t.apiKey,bundlerName:t.bundlerName,git:t.git,outDir:t.outDir,sendMetrics:t.sendMetrics,site:t.site,version:t.version},n),s.end()},Vo=e=>{const n=t.bold.red,o=e[Eo]||{},r={errors:[]};if(o.sourcemaps){const t=o.sourcemaps,s=t.releaseVersion||e.metadata?.version;s||r.errors.push(`${n("sourcemaps.releaseVersion")} is required (set it directly or via ${n("metadata.version")}).`),t.releaseVersion&&e.metadata?.version&&t.releaseVersion!==e.metadata.version&&r.errors.push(`${n("sourcemaps.releaseVersion")} must match ${n("metadata.version")} when both are configured.`),t.service||r.errors.push(`${n("sourcemaps.service")} is required.`),t.minifiedPathPrefix||r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),t.minifiedPathPrefix&&!(e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(t.minifiedPathPrefix)&&r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`),s&&(r.config={bailOnError:!1,dryRun:!1,maxConcurrency:20,...t,releaseVersion:s})}return r},Ko=({options:e,context:t})=>{const n=t.getLogger(Io),o=n.time("validate options"),r=((e,t)=>{const n=[],o=Vo(e);if(n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${Io}.`);return{...e[Eo],sourcemaps:o.config}})(e,n);o.end();const s=ye(e,"metrics",n);let i,a,u=!1;const c=async()=>{if(!r.sourcemaps||u)return;u=!0;const e=n.time("sourcemaps process");await qo(r,{apiKey:t.auth.apiKey,bundlerName:t.bundler.name,git:i,addMetric:t.addMetric,outDir:t.bundler.outDir,outputs:a?.outputs||[],sendMetrics:s,site:t.auth.site,version:t.version},n),e.end()};return[{name:Io,enforce:"post",async git(e){i=e,a&&await c()},async buildReport(t){a=t,!i&&ne(e)||await c()},async asyncTrueEnd(){u||await c()}}]},Ho="liveDebugger",Wo="datadog-live-debugger-plugin",Jo="if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}",Go="__DD_LIVE_DEBUGGER_BUILD__",Yo=e=>void 0===e?Jo:`${Jo};if(typeof globalThis.${Go}==='undefined'){globalThis.${Go}={version:${JSON.stringify(e)}}}`;function Qo(e){return"function"==typeof e?e:e.default}function Zo(e,t,n,o,r){const s=u.relative(t,e).replace(/\\/g,"/"),i=Xo(n,r);if(i)return`${s};${i}`;const a=function(e){const t=e.node.loc?.start.line??0,n=e.node.loc?.start.column??0;return`${t}:${n}`}(n);return`${s};<anonymous>@${a}:${o}`}function Xo(e,t){const n=e.node,o=e.parent;return"id"in n&&t.isIdentifier(n.id)?n.id.name:t.isObjectMethod(n)||t.isClassMethod(n)||t.isClassPrivateMethod(n)?nr(n.key,t):t.isVariableDeclarator(o)&&t.isIdentifier(o.id)?o.id.name:t.isAssignmentExpression(o)?function(e,t){if(t.isIdentifier(e))return e.name;if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=er(e.object,t),o=tr(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}(o.left,t):t.isObjectProperty(o)||t.isClassProperty(o)||t.isClassPrivateProperty(o)?nr(o.key,t):null}function er(e,t){if(t.isIdentifier(e))return e.name;if(t.isThisExpression(e))return"this";if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=er(e.object,t),o=tr(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}function tr(e,t,n){return n.isPrivateName(e)&&n.isIdentifier(e.id)?`#${e.id.name}`:t?null:n.isIdentifier(e)?e.name:null}function nr(e,t){return t.isIdentifier(e)?e.name:t.isStringLiteral(e)||t.isNumericLiteral(e)||t.isBigIntLiteral(e)?String(e.value):t.isPrivateName(e)&&t.isIdentifier(e.id)?`#${e.id.name}`:null}function or(e,t){if(e.node.leadingComments)for(const n of e.node.leadingComments)if(n.value.includes(t))return!0;return!1}function rr(e,t){const n=[];if(t.isBlockStatement(e.body)){const o=e.params.flatMap((e=>dr(e,t))),r=new Set(o),s="id"in e&&t.isIdentifier(e.id)?e.id.name:"";for(const o of e.body.body)if(t.isVariableDeclaration(o)){const e=o.end;if(null==e)continue;for(const i of o.declarations)for(const o of dr(i.id,t))r.has(o)||o===s||n.push({name:o,declarationEnd:e,temporalDeadZones:[]})}}const o=n.length>25?n.slice(0,25):n;if(t.isBlockStatement(e.body)){const n=o.map((({name:e})=>e)),r=new Set(n),s=function(e,t,n){const o=new Map;for(const r of e.body)sr(r,t,o,n);return o}(e.body,r,t);for(const e of o)e.temporalDeadZones=s.get(e.name)??[]}return o}function sr(e,t,n,o){o.isFunctionDeclaration(e)||o.isClassDeclaration(e)||(o.isBlockStatement(e)?ir(e,t,n,o):o.isIfStatement(e)?(sr(e.consequent,t,n,o),e.alternate&&sr(e.alternate,t,n,o)):o.isForStatement(e)||o.isForInStatement(e)||o.isForOfStatement(e)||o.isWhileStatement(e)||o.isDoWhileStatement(e)?sr(e.body,t,n,o):o.isSwitchStatement(e)?function(e,t,n,o){for(const r of e.cases){ar(r.consequent,e.start,t,n,o);for(const e of r.consequent)sr(e,t,n,o)}}(e,t,n,o):o.isTryStatement(e)?(ir(e.block,t,n,o),e.handler&&ir(e.handler.body,t,n,o),e.finalizer&&ir(e.finalizer,t,n,o)):(o.isLabeledStatement(e)||o.isWithStatement(e))&&sr(e.body,t,n,o))}function ir(e,t,n,o){ar(e.body,e.start,t,n,o);for(const r of e.body)sr(r,t,n,o)}function ar(e,t,n,o,r){if(null!=t)for(const s of e)r.isVariableDeclaration(s)&&"var"!==s.kind?ur(s,t,n,o,r):r.isClassDeclaration(s)&&s.id&&cr(s.id.name,t,s.end,n,o)}function ur(e,t,n,o,r){for(const s of e.declarations)for(const i of dr(s.id,r))cr(i,t,e.end,n,o)}function cr(e,t,n,o,r){if(null==n||!o.has(e))return;const s=r.get(e)??[];s.push({start:t,end:n}),r.set(e,s)}function dr(e,t){return t.isIdentifier(e)?[e.name]:t.isRestElement(e)?t.isIdentifier(e.argument)?[e.argument.name]:dr(e.argument,t):t.isAssignmentPattern(e)?dr(e.left,t):t.isObjectPattern(e)?e.properties.flatMap((e=>t.isRestElement(e)?dr(e.argument,t):dr(e.value,t))):t.isArrayPattern(e)?e.elements.flatMap((e=>e?dr(e,t):[])):t.isTSParameterProperty(e)&&t.isIdentifier(e.parameter)?[e.parameter.name]:[]}const lr=["@babel/parser","@babel/traverse","@babel/types","magic-string"];let pr,fr,mr,hr,gr=!1;function yr(e){try{return function(e){switch(e){case"@babel/parser":return C("@babel/parser");case"@babel/traverse":return C("@babel/traverse");case"@babel/types":return C("@babel/types");case"magic-string":return C("magic-string");default:throw new Error(`Unknown peer dependency: ${e}`)}}(e)}catch(e){throw function(e){if(!function(e){if(!(e instanceof Error))return!1;const t=e.code;if("MODULE_NOT_FOUND"!==t&&"ERR_MODULE_NOT_FOUND"!==t)return!1;return lr.some((t=>e.message.includes(t)))}(e))return e instanceof Error?e:new Error(String(e));const t=lr.find((t=>e.message.includes(t))),n=t??lr.join(", ");return new Error(`Datadog Live Debugger could not load "${n}". It is an optional peer dependency that must be installed in your project when the \`liveDebugger\` plugin is enabled. Install the peer dependencies with: \`npm install --save-dev ${lr.join(" ")}\` (or the yarn/pnpm/bun equivalent). Underlying error: ${e.message}`)}(e)}}const br=/\bfunction\b|=>|\bclass\b|\)\s*\{/;function wr(e){const{code:t,filePath:n,buildRoot:o,honorSkipComments:r,functionTypes:s,namedOnly:i}=e;let a=0,u=0,c=0,d=0,l=0;if(function(e){return/['"][^'"]*(?:@css-module:|\?worker\b|\?sprite\b|dynamic!)[^'"]*['"]/.test(e)}(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:1,skippedUnsupportedCount:d,totalFunctions:l};if(!br.test(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};gr||(pr=yr("@babel/parser").parse,fr=Qo(yr("@babel/traverse")),mr=yr("@babel/types"),hr=Qo(yr("magic-string")),gr=!0);const p=pr(t,{sourceType:"unambiguous",plugins:["jsx","typescript"],sourceFilename:n}),f=[],m=new Map,h=new Set,g=new Map,y=new Map;let b=0;if(fr(p,{Function(e){l++;const t=function(e,t){if(t.isClassMethod(e.node)&&"constructor"===e.node.kind&&Ir(e,t))return e.node;return}(e,mr);if(t&&(m.set(t,t.body.start),g.set(t,function(e,t){const n=[];for(const o of e)kr(o,n,t);return n}(t.body.body,mr))),!function(e,t){const n=e.node;return!(n.generator||t.isClassMethod(n)&&"constructor"===n.kind)}(e,mr))return void d++;if(r&&function(e,t,n){let o=e;for(;o;){if(or(o,t))return!0;if(n.isStatement(o.node)||n.isExportDeclaration(o.node)){if(o.parentPath&&n.isExportDeclaration(o.parentPath.node))return or(o.parentPath,t);break}o=o.parentPath}return!1}(e,"@dd-no-instrumentation",mr))return void c++;if(s&&!s.includes(function(e,t){if(t.isFunctionDeclaration(e))return"functionDeclaration";if(t.isArrowFunctionExpression(e))return"arrowFunction";if(t.isObjectMethod(e))return"objectMethod";if(t.isClassPrivateMethod(e))return"classPrivateMethod";if(t.isClassMethod(e))return"classMethod";return"functionExpression"}(e.node,mr)))return void d++;if(i&&!Xo(e,mr))return void d++;let p=0;if(!Xo(e,mr)){const t=e.parentPath?.node;t&&(p=y.get(t)||0,y.set(t,p+1))}const w=Zo(n,o,e,p,mr);try{const t=e.node,n=b++,o=`$dd_p${n}`,r=function(e,t){const n=[];for(const o of e.params)for(const e of dr(o,t))"this"!==e&&n.push(e);return n.length>25?n.slice(0,25):n}(t,mr),s=rr(t,mr),i=mr.isArrowFunctionExpression(t)&&!mr.isBlockStatement(t.body),a=i&&mr.isSequenceExpression(t.body),c=function(e,t){if(t.isFunction(e.node)&&!t.isArrowFunctionExpression(e.node))return;let n=e.parentPath;for(;n;){const e=n.node;if(t.isClassMethod(e)&&"constructor"===e.kind){if(!Ir(n,t))return;return{node:e,parent:n.parent,parentPath:n.parentPath}}if(t.isFunction(e)){if(t.isArrowFunctionExpression(e)){n=n.parentPath;continue}return}n=n.parentPath}return}(e,mr),d=null!=c;c&&(h.add(c.node),m.set(c.node,c.node.body.start));const l=[],p=i||!mr.isBlockStatement(t.body)||!Pr(t.body.body,mr);let g;if(!i&&mr.isBlockStatement(t.body)&&Ar(t.body.body,l,mr),!i&&mr.isBlockStatement(t.body)&&t.body.directives.length>0){g=t.body.directives[t.body.directives.length-1].end}f.push({bodyStart:t.body.start,bodyEnd:t.body.end,functionEnd:t.end,isExpressionBody:i,hasSequenceExpressionBody:a,aliasesExpressionBodySuperCall:d&&i&&Er(t.body,mr),needsTrailingReturn:p,useThisAlias:d,bodyParenStart:i&&"number"==typeof t.body.extra?.parenStart?t.body.extra.parenStart:void 0,directivesEnd:g,functionId:w,probeVarName:o,probeIdx:String(n),entryVars:r,localVars:s,returns:l}),u++}catch(e){a++}}}),0===u)return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};const w=new hr(t),v=function(e){const t=new Set;for(const n of e)n.aliasesExpressionBodySuperCall&&t.add(Sr({start:n.bodyStart,end:n.bodyEnd}));return t}(f),$=function(e,t,n,o){const r=[];for(const s of e){const e=t.get(s);null!=e&&r.push({bodyStart:e,superCalls:(n.get(s)??[]).filter((e=>!o.has(Sr(e))))})}return r}(h,m,g,v);for(let e=f.length-1;e>=0;e--)vr(w,t,f[e]);for(const e of $)$r(w,t,e);return{code:w.toString(),map:w.generateMap({source:n,hires:!0}),failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l}}function vr(e,t,n){const{probeVarName:o,probeIdx:r,functionId:s,entryVars:i,localVars:a,returns:u,bodyStart:c,bodyEnd:d,functionEnd:l,isExpressionBody:p,hasSequenceExpressionBody:f,aliasesExpressionBodySuperCall:m,useThisAlias:h,bodyParenStart:g,directivesEnd:y}=n,b=`$dd_e${r}`,w=`$dd_rv${r}`,v=h?"$dd_t":"this",$=i.join(", "),k=""!==$,x=k?`, ${b}()`:"";const S=`const ${o} = $dd_probes('${s.replace(/['\\\n\r\u2028\u2029]/g,(e=>{switch(e){case"'":return"\\'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}}))}');`,E=k?`const ${b} = () => ({${$}});`:"",I=`if (${o}) $dd_entry(${o}, ${v}${x});`,D=`catch(e) { if (${o}) $dd_throw(${o}, e, ${v}${x}); throw e; }`;if(p){if(null!=g){const n=function(e,t,n){const o=[];for(let r=t;r<n;r++)"("===e[r]&&o.push(r);return o}(t,g,c),o=function(e,t,n){const o=[];for(let r=n-1;r>=t;r--)")"===e[r]&&o.push(r);return o}(t,d,l),r=Math.min(n.length,o.length);for(let t=0;t<r;t++){const r=n[t],s=o[t];e.remove(r,r+1),e.remove(s,s+1)}}const n=["{",S,E,"try {",I,m?`const ${w} = ($dd_t = `:`const ${w} = `].filter(Boolean).join("\n");let r=f?");":";";m&&(r=f?"));":");");const s=[r,`if (${o}) $dd_return(${o}, ${w}, ${v}${Dr(b,k,a,d)});`,`return ${w};`,`} ${D}`,"}"].join("\n");if(d-c>=2){const o=f?`${n}(${t[c]}`:n+t[c];e.update(c,c+1,o),e.update(d-1,d,t[d-1]+s)}else e.update(c,d,n+t.slice(c,d)+s)}else{const r=[S,E,"try {",`let ${w};`,I].filter(Boolean).join("\n");for(const t of u){const n=Dr(b,k,a,t.start);if(null!=t.argStart&&null!=t.argEnd){const r=t.hasSequenceExpressionArgument?`(${w} = (`:`(${w} = `,s=t.hasSequenceExpressionArgument?")":"";e.appendLeft(t.argStart,r),e.appendLeft(t.argEnd,`${s}, ${o} ? $dd_return(${o}, ${w}, ${v}${n}) : ${w})`)}else e.appendLeft(t.start,`if (${o}) $dd_return(${o}, undefined, ${v}${n}); `)}if(null!=y){const n=y-1;e.update(n,y,`${t[n]}\n${r}`)}else e.update(c,c+1,`${t[c]}${r}`);const s=Dr(b,k,a,d),i=`\n${n.needsTrailingReturn?`if (${o}) $dd_return(${o}, undefined, ${v}${s});\n`:""}} ${D}\n`;e.update(d-1,d,`${i}${t[d-1]}`)}}function $r(e,t,n){e.update(n.bodyStart,n.bodyStart+1,`${t[n.bodyStart]}let $dd_t;`);for(const t of n.superCalls)e.appendLeft(t.start,"($dd_t = "),e.appendLeft(t.end,")")}function kr(e,t,n){Er(e,n)&&t.push({start:e.start,end:e.end});const o=Object.values(e);for(const e of o)if(Array.isArray(e))for(const o of e)xr(o,t,n);else xr(e,t,n)}function xr(e,t,n){n.isNode(e)&&(n.isFunction(e)&&!n.isArrowFunctionExpression(e)||kr(e,t,n))}function Sr(e){return`${e.start}:${e.end}`}function Er(e,t){return t.isCallExpression(e)&&t.isSuper(e.callee)}function Ir(e,t){const n=e.parentPath?.parentPath;if(!n)return!1;const o=n.node;return(t.isClassDeclaration(o)||t.isClassExpression(o))&&null!=o.superClass}function Dr(e,t,n,o){const r=function(e,t){const n=e.filter((({declarationEnd:e,temporalDeadZones:n})=>e<=t&&!function(e,t){return e.some((({start:e,end:n})=>e<=t&&t<n))}(n,t))).map((({name:e})=>e));if(0===n.length)return;return`{${n.join(", ")}}`}(n,o);return t&&r?`, ${e}(), ${r}`:t?`, ${e}()`:r?`, undefined, ${r}`:""}function Ar(e,t,n){for(const o of e)if(n.isReturnStatement(o))t.push({start:o.start,end:o.end,argStart:o.argument?.start??void 0,argEnd:o.argument?.end??void 0,hasSequenceExpressionArgument:n.isSequenceExpression(o.argument)});else if(!n.isFunctionDeclaration(o)&&!n.isClassDeclaration(o))if(n.isBlockStatement(o))Ar(o.body,t,n);else if(n.isIfStatement(o))Ar([o.consequent],t,n),o.alternate&&Ar([o.alternate],t,n);else if(n.isForStatement(o)||n.isForInStatement(o)||n.isForOfStatement(o)||n.isWhileStatement(o)||n.isDoWhileStatement(o))Ar([o.body],t,n);else if(n.isSwitchStatement(o))for(const e of o.cases)Ar(e.consequent,t,n);else n.isTryStatement(o)?(Ar(o.block.body,t,n),o.handler&&Ar(o.handler.body.body,t,n),o.finalizer&&Ar(o.finalizer.body,t,n)):(n.isLabeledStatement(o)||n.isWithStatement(o))&&Ar([o.body],t,n)}function Pr(e,t){if(0===e.length)return!1;const n=e[e.length-1];if(t.isReturnStatement(n))return!0;if(t.isIfStatement(n)&&n.alternate){const e=t.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent],o=t.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];return Pr(e,t)&&Pr(o,t)}return!1}const jr=["functionDeclaration","functionExpression","arrowFunction","objectMethod","classMethod","classPrivateMethod"],Mr=t.bold.red,Tr=Number(process.env.DD_LD_LIMIT)||1/0,Cr=(e,t)=>{const n=t.getLogger(Wo);let o=0,r=0,s=0,i=0,a=0,u=0,c=0,d=0;return{name:Wo,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(l,p){if(e.include.length>0){if(!e.include.some((e=>"string"==typeof e?p.includes(e):e.test(p))))return{code:l}}for(const t of e.exclude){if("string"==typeof t?p.includes(t):t.test(p))return{code:l}}if(d>=Tr)return{code:l};try{const f=wr({code:l,filePath:p,buildRoot:t.buildRoot,honorSkipComments:e.honorSkipComments,functionTypes:e.functionTypes,namedOnly:e.namedOnly});if(o+=f.instrumentedCount,c+=f.totalFunctions,r+=f.failedCount,s+=f.skippedByCommentCount,i+=f.skippedFileCount,a+=f.skippedUnsupportedCount,f.totalFunctions>0&&d++,0===f.instrumentedCount)return{code:l};u++;const m=function(e){const t=e.getNativeBuildContext?.();return t?.inputSourceMap}(this),h=f.map&&m?function(e,t,n,o){try{return k(e,((e,n)=>1===n.depth?t:null))}catch(t){return o.error(`Failed to compose source map for ${n}: ${t}`,{forward:!0}),e}}(f.map,m,p,n):f.map;return{code:f.code,map:h}}catch(e){return n.error(`Instrumentation Error in ${p}: ${e}`,{forward:!0}),{code:l}}}},buildEnd:()=>{c>0&&n.info(`Live Debugger: ${o}/${c} functions instrumented across ${u}/${d} files`,{forward:!0,context:{failedCount:r,skippedByCommentCount:s,skippedFileCount:i,skippedUnsupportedCount:a,totalFilesWithFunctions:d,instrumentedCount:o,totalFunctions:c,transformedFileCount:u}})}}},Or=({options:e,context:t})=>{const n=((e,t)=>{const n=e[Ho]||{},o=e.metadata?.version,r=[];if(void 0!==n.include)if(Array.isArray(n.include)){for(const e of n.include)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Mr("include")} patterns must be strings or RegExp`);break}}else r.push(`${Mr("include")} must be an array of strings or RegExp`);if(void 0!==n.exclude)if(Array.isArray(n.exclude)){for(const e of n.exclude)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Mr("exclude")} patterns must be strings or RegExp`);break}}else r.push(`${Mr("exclude")} must be an array of strings or RegExp`);if(void 0!==n.honorSkipComments&&"boolean"!=typeof n.honorSkipComments&&r.push(`${Mr("honorSkipComments")} must be a boolean`),void 0!==n.functionTypes)if(Array.isArray(n.functionTypes)){for(const e of n.functionTypes)if(!jr.includes(e)){r.push(`${Mr("functionTypes")} contains invalid value "${e}". Valid values: ${jr.join(", ")}`);break}}else r.push(`${Mr("functionTypes")} must be an array of FunctionKind values`);if(void 0!==n.namedOnly&&"boolean"!=typeof n.namedOnly&&r.push(`${Mr("namedOnly")} must be a boolean`),r.length)throw t.error(`\n - ${r.join("\n - ")}`),new Error(`Invalid configuration for ${Wo}.`);return{version:o,include:n.include||[/\.[jt]sx?$/],exclude:n.exclude||[/\/node_modules\//,/\.min\.js$/,/\/pyodide-lib\//,/^vite\//,/\0/,/commonjsHelpers\.js$/,/__vite-browser-external/,/@datadog\/browser-/,/browser-sdk\/packages\//],honorSkipComments:n.honorSkipComments??!0,functionTypes:n.functionTypes,namedOnly:n.namedOnly??!1}})(e,t.getLogger(Wo));return t.inject({type:"code",position:Ce.BEFORE,injectIntoAllChunks:!0,value:Yo(n.version)}),[Cr(n,t)]};const Nr=[e=>/modules\.tree\.(count|size)$/.test(e.metric)?null:e,e=>e.tags.some((e=>/^assetName:.*\.map$/.test(e)||/^moduleName:\/node_modules/.test(e)))?null:e,e=>{const t={size:1e5,count:10,duration:1e3};/^sourcemaps\.upload\.(failure|retry)$/.test(e.metric)&&(t.count=0),/(entries|loaders|warnings|errors)\.count$/.test(e.metric)&&(t.count=0),/(modules\.(dependencies|dependents)$)/.test(e.metric)&&(t.count=30),/modules\.tree\.count$/.test(e.metric)&&(t.count=150),/modules\.tree\.size$/.test(e.metric)&&(t.size=15e5),/entries\.size$/.test(e.metric)&&(t.size=0),/entries\.modules\.count$/.test(e.metric)&&(t.count=0);return(e.points.length?e.points.reduce(((e,t)=>e+t[1]),0)/e.points.length:0)>t[e.type]?e:null}],Rr="metrics",_r="datadog-metrics-plugin",Fr=e=>Math.floor((e||Date.now())/1e3),zr=(e,t)=>{const n=[`bundler:${ie(e.bundler.name)}`,`plugin_version:${ie(e.version)}`,`site:${ie(e.auth.site)}`];return e.build.metadata.name&&n.push(`build_name:${ie(e.build.metadata.name)}`),e.build.metadata.version&&n.push(`build_version:${ie(e.build.metadata.version)}`),[...n,...t]},Lr=(e,t,n)=>({...e,tags:[...e.tags,...t],metric:n?`${n}.${e.metric}`:e.metric}),Ur=(e,t,n,o,r)=>{const s=new Set;for(const t of e){let e={...t,toSend:!0};if(n?.length)for(const t of n){const n=t({metric:e.metric,type:e.type,points:e.points,tags:e.tags});n?e={...n,toSend:e.toSend}:e.toSend=!1}s.add(Lr(e,o,r))}const i=Array.from(s).filter((e=>e.toSend)).length;return s.add(Lr({metric:"metrics.count",type:"count",points:[[t,i+1]],tags:[],toSend:!0},o,r)),s},Br=(e="")=>e.endsWith("/")?e:`${e}/`,qr=(e,t)=>{let n=e;return e.split(Br(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},Vr=(e,t)=>e.split("!").pop().replace(Br(t),"./"),Kr=(e,t,n)=>{let o=e.name||e.userRequest;return o||(o=((e,t)=>{let n=e.userRequest;if(!n){let o;o=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=o?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),Vr(o||"no-name",n)},Hr=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Wr=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Jr=t.bold.red,Gr=t.bold.cyan,Yr=e=>(t,n)=>{let o,r;return"function"==typeof e?(o=e(t),r=e(n)):(o=t[e],r=n[e]),o>r?-1:o<r?1:0},Qr=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Yr("duration"));const o={name:`${e} duration`,values:n.map((e=>({name:e.name,value:oe(e.duration)}))),top:!0};n.sort(Yr("increment"));return[o,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Zr=(e,t,n)=>{const o=[];var r;n&&(o.push(...Qr("Loader",n.loaders)),o.push(...Qr("Tapable",n.tapables)),o.push(...Qr("Module",n.modules))),o.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},o={name:"Module size",values:[],top:!0},r={name:"Module aggregated size",values:[],top:!0},s=new Set,i=te(e.build),a=new Map,u=new Map,c=new Map;for(const e of i.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)c.has(n)||c.set(n,new Set),c.get(n).add(e.filepath);for(const t of n)u.has(t)||u.set(t,new Set),u.get(t).add(e.filepath);if(u.has(e.filepath)){const n=u.get(e.filepath);for(const e of n)t.add(e)}if(c.has(e.filepath)){const t=c.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),c.set(e.filepath,n),a.set(e.filepath,{name:e.name,size:e.size,dependencies:t,dependents:n})}for(const[e,t]of a){const n=u.get(e)||new Set,o=c.get(e)||new Set;let r=t.size;for(const e of n)r+=a.get(e)?.size||0;s.add({name:t.name,size:t.size,aggregatedSize:r,dependents:o,dependencies:n})}if(!s.size)return[t,n,o];const d=Array.from(s);return d.sort(Yr((e=>e.dependents.size))),t.values=d.map((e=>({name:e.name,value:e.dependents.size.toString()}))),d.sort(Yr((e=>e.dependencies.size))),n.values=d.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),d.sort(Yr("size")),o.values=d.map((e=>({name:e.name,value:v(e.size)}))),d.sort(Yr("aggregatedSize")),r.values=d.map((e=>({name:e.name,value:v(e.aggregatedSize||e.size)}))),[t,n,o,r]})(e)),o.push(...(r=e,[{name:"Asset size",values:(r.build.outputs||[]).filter((e=>"map"!==e.type)).sort(Yr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry aggregated size",values:(r.build.entries||[]).sort(Yr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry number of modules",values:(r.build.entries||[]).sort(Yr((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),o.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,o=e.build.outputs?e.build.outputs.length:0,r=e.build.warnings.length,s=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:oe(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:oe(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:oe(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:o.toString()},{name:"Number of entries",value:i.toString()},{name:"Number of warnings",value:r.toString()},{name:"Number of errors",value:s.toString()}),[t]})(e));const s=(e=>{let t="";for(const t of e){t.top&&t.values.length>=5&&(t.values=t.values.slice(0,5),t.name=`Top 5 ${t.name}`);for(const e of t.values)e.name=re(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),r=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),s=Math.max(n+4,o+r+4);for(const n of e){if(0===n.values.length)continue;const e=s-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=r-e.value.length;t+=` [${Jr(e.value)}] ${" ".repeat(n)}${Gr(e.name)}\n`}}return t})(o);t.info(s)},Xr="api/v1/series",es=t.bold.green,ts=(e,t,n)=>{if(!t.apiKey)return void n.info("Won't send metrics to Datadog: missing API Key.");if(!e.size)return void n.debug("No metrics to send.");const o=Array.from(e).filter((e=>e.toSend)).map((e=>({...e,toSend:void 0}))),r=new Map;for(const e of o)r.has(e.metric)||r.set(e.metric,0),r.set(e.metric,r.get(e.metric)+1);const s=Array.from(r.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${o.length} metrics with configuration:\n - intake: ${es(`https://api.${t.site}/${Xr}`)}\n\nMetrics:\n - ${s.join("\n - ")}`),Q({method:"POST",url:`https://api.${t.site}/${Xr}?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:o})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))},ns=["onStart","onLoad","onResolve","onEnd"],os=new Map,rs=new Map,ss=new Map,is=(e,t,n)=>{const o=Object.assign({},e);for(const r of ns)o[r]=async(o,s)=>{const i=rs.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[r]=i.events[r]||{name:r,values:[]};const a="onLoad"===r;return(0,e[r])(o,(async(...e)=>{const o=Vr(e[0].path,n),u=ss.get(o)||{name:o,increment:0,duration:0,events:{}};u.events[r]=u.events[r]||{name:r,values:[]};const c=x.now();try{return await s(...e)}finally{const n=x.now(),s=n-c,d={start:c,end:n,duration:s,context:Wr(e)};if(i.events[r].values.push(d),i.duration+=s,i.increment+=1,rs.set(t,i),u.events[r].values.push(d),u.duration+=s,u.increment+=1,ss.set(o,u),a){const e=os.get(t)||{name:t,increment:0,duration:0,events:{}};e.events[r]=e.events[r]||{name:r,values:[]},e.events[r].values.push(d),e.duration+=s,e.increment+=1,os.set(t,e)}}}))};return o},as=(e,t)=>({setup:n=>{n.initialOptions.metafile=!0;const o=t.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const o of n){const n=o.setup;o.setup=async r=>{const s=is(r,o.name,t);await n({...s,initialOptions:{...s.initialOptions,plugins:e}})}}}})(n,e.buildRoot),o.end(),n.onEnd((async n=>{if(!n.metafile)return void t.warn("Missing metafile, can't proceed with modules data.");const o=t.time("getting plugins results"),{plugins:r,loaders:s,modules:i}={plugins:rs,modules:ss,loaders:os};o.end(),await e.asyncHook("timings",{tapables:r,loaders:s,modules:i})}))}});class us{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Kr(e,t,this.cwd),o=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(Hr))(e);o.length||o.push("no-loader"),this.started[n]={module:qr(n),timings:{start:x.now(),duration:0,end:0},loaders:o}}doneModule(e,t){const n=Kr(e,t,this.cwd),o=this.started[n];o&&(o.timings.end=x.now(),o.timings.duration=o.timings.end-o.timings.start,this.finished.push(o),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const o=n.timings.end-n.timings.start,r=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},s=n.loaders.join(",");r.events[s]=r.events[s]||{name:s,values:[]},r.events[s].values.push(n.timings),r.increment+=1,r.duration+=o,t.set(n.module,r);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=o,e.set(t,n)}}return{loaders:e,modules:t}}}class cs{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,o,r,s){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:r,end:s,duration:s-r,context:o,type:e}),i.duration+=s-r,i.increment+=1,this.timings.set(t,i)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const o=n;o.duration=Object.values(n.events).map((e=>e.values.reduce(((e,t)=>e+t.end-t.start),0))).reduce(((e,t)=>e+t),0),e.set(t,o)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const s=x.now(),i=t.apply(this,r),a=()=>{this.saveResult(e,n,o,Wr(r),s,x.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const s=x.now(),i=r.pop();return t.apply(this,[...r,(...t)=>(this.saveResult(e,n,o,Wr(r),s,x.now()),i(...t))])}}getDefaultTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const s=x.now(),i=t.apply(this,r);return this.saveResult(e,n,o,Wr(r),s,x.now()),i}}getTapPatch(e,t,n,o){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,o);case"async":return this.getAsyncTapPatch(e,t,n,o);default:return this.getDefaultTapPatch(e,t,n,o)}}newTap(e,t,n,o){return(r,s)=>{const i="string"==typeof(a=r)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(o,r,s);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,s,i,t);return n.call(o,r,c)}}replaceTaps(e,t){t.tap=this.newTap("default",e,t.tap,t),t.tapAsync=this.newTap("async",e,t.tapAsync,t),t.tapPromise=this.newTap("promise",e,t.tapPromise,t)}patchHook(e,t,n){n._fakeHook||e.includes(_r)||(this.hooks[e]||(this.hooks[e]=[]),this.hooks[e].includes(t)||(this.hooks[e].push(t),this.replaceTaps(t,n)))}patchHooks(e){const t=e.constructor.name,n=Object.keys(e.hooks).filter((e=>!this.ignoredHooks.includes(e)&&!this.hooks[t]?.includes(e)));for(const o of n)this.patchHook(t,o,e.hooks[o])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const ds=e=>async t=>{const n=e.getLogger(_r),o={name:_r},r=new cs(e.buildRoot),s=new us(e.buildRoot),i=n.time("parse compiler hooks");r.throughHooks(t),i.end(),t.hooks.thisCompilation.tap(o,(e=>{const t=n.time("parse compilation hooks");r.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{s.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{s.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{s.doneModule(t,e)}))})),t.hooks.afterEmit.tapPromise(o,(async()=>{const{timings:t}=r.getResults(),{loaders:n,modules:o}=s.getResults();await e.asyncHook("timings",{tapables:t,loaders:n,modules:o})}))},ls={filters:Nr},ps=({options:e,context:t,stores:n})=>{const o=t.getLogger(_r);let r=0;((e,t)=>{e.addMetric=e=>{t.metrics.add(e)}})(t,n);const s=((e,t)=>{const n=e[Rr],o=Fr(n?.timestamp);let r=!1===n?.enableDefaultPrefix?"":`build.${t}`;return n?.prefix&&(r+=r?`.${n.prefix}`:n.prefix),{enableDefaultPrefix:!0,enableTracing:!1,filters:Nr,tags:[],...e[Rr],timestamp:o,prefix:r.toLowerCase().replace(/(^\.*|\.*$)/g,"")}})(e,t.bundler.name),i=[],a={name:_r,enforce:"pre",esbuild:as(t,o),webpack:ds(t),rspack:ds(t)},u=o.time("build",{start:!1}),c=s.enableTracing&&["esbuild","webpack","rspack"].includes(t.bundler.name);let d,l;const p=async()=>{if(!n.metrics.size)return;const e=o.time("aggregating collected metrics"),r=(()=>{const e=new Set(n.metrics);n.metrics.clear();const o=zr(t,s.tags);return Ur(e,s.timestamp,s.filters,o,s.prefix)})();await t.asyncHook("metrics",r),e.end();const i=o.time("sending collected metrics to Datadog");await ts(r,{apiKey:t.auth.apiKey,site:t.auth.site},o),i.end()},f=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-r;const e=o.time("aggregating metrics"),n=s.timestamp,i=o.time("aggregate universal metrics"),a=((e,t)=>{const n=new Set,o=e.inputs||[],r=e.outputs||[],s=e.entries||[],i=e.warnings.length,a=e.errors.length,u=e.duration,c=new Map,d=new Map,l=new Map;for(const e of s){for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");l.has(n)||l.set(n,[]),l.get(n).push(e.name)}}for(const e of r)for(const t of e.inputs)d.has(t.filepath)||d.set(t.filepath,[]),d.get(t.filepath).push(e.name);n.add({metric:"assets.count",type:"count",points:[[t,r.length]],tags:[]}).add({metric:"entries.count",type:"count",points:[[t,s.length]],tags:[]}).add({metric:"errors.count",type:"count",points:[[t,a]],tags:[]}).add({metric:"modules.count",type:"count",points:[[t,o.length]],tags:[]}).add({metric:"warnings.count",type:"count",points:[[t,i]],tags:[]}),u&&n.add({metric:"compilation.duration",type:"duration",points:[[t,u]],tags:[]});for(const e of o){const o=[`moduleName:${e.name}`,`moduleType:${e.type}`];c.has(e.filepath)&&o.push(...c.get(e.filepath).map((e=>`entryName:${e}`))),d.has(e.filepath)&&o.push(...d.get(e.filepath).map((e=>`assetName:${e}`))),n.add({metric:"modules.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"modules.dependencies",type:"count",points:[[t,e.dependencies.size]],tags:o}).add({metric:"modules.dependents",type:"count",points:[[t,e.dependents.size]],tags:o})}for(const e of r){const o=[`assetName:${e.name}`,`assetType:${e.type}`],r=e.filepath.replace(/\.map$/,"");l.has(r)&&o.push(...l.get(r).map((e=>`entryName:${e}`))),n.add({metric:"assets.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"assets.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o})}for(const e of s){const o=[`entryName:${e.name}`];n.add({metric:"entries.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"entries.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o}).add({metric:"entries.assets.count",type:"count",points:[[t,e.outputs.length]],tags:o})}return n})(l,n);i.end();const u=o.time("aggregate plugins metrics"),c=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"plugins.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values()){let e=0,r=0;for(const s of Object.values(o.events)){let i=0;r+=s.values.length;for(const t of s.values){const n=t.end-t.start;i+=n,e+=n}n.add({metric:"plugins.hooks.duration",type:"duration",points:[[t,i]],tags:[`pluginName:${o.name}`,`hookName:${s.name}`]}).add({metric:"plugins.hooks.increment",type:"count",points:[[t,s.values.length]],tags:[`pluginName:${o.name}`,`hookName:${s.name}`]})}n.add({metric:"plugins.duration",type:"duration",points:[[t,e]],tags:[`pluginName:${o.name}`]}).add({metric:"plugins.increment",type:"count",points:[[t,r]],tags:[`pluginName:${o.name}`]})}return n})(d?.tapables,n);u.end();const p=o.time("aggregate loaders metrics"),f=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"loaders.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values())n.add({metric:"loaders.duration",type:"duration",points:[[t,o.duration]],tags:[`loaderName:${o.name}`]}).add({metric:"loaders.increment",type:"count",points:[[t,o.increment]],tags:[`loaderName:${o.name}`]});return n})(d?.loaders,n);p.end();const m=new Set([...a,...c,...f]),h=zr(t,s.tags),g=Ur(m,n,s.filters,h,s.prefix);await t.asyncHook("metrics",g),e.end();const y=o.time("outputing report");Zr(t,o,d),y.end();const b=o.time("sending metrics to Datadog");await ts(g,{apiKey:t.auth.apiKey,site:t.auth.site},o),b.end()},m={name:"datadog-universal-metrics-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now(),e[Rr]?.timestamp||(s.timestamp=Fr(t.build.start))},buildEnd(){u.end(),r=Date.now()},async timings(e){d=e,l&&await f()},async buildReport(e){l=e,!d&&c||await f()},async flush(){await p()}};return s.enableTracing&&i.push(a),i.push(m),i},fs="output",ms="datadog-output-plugin",hs=(e,t)=>"string"==typeof t?t.replace(/(\.json)?$/,".json"):!0===t?`${e}.json`:t,gs=e=>{const t=void 0===e;return{build:hs("build",e?.build??t),bundler:hs("bundler",e?.bundler??t),dependencies:hs("dependencies",e?.dependencies??t),errors:hs("errors",e?.errors??t),logs:hs("logs",e?.logs??t),metrics:hs("metrics",e?.metrics??t),timings:hs("timings",e?.timings??t),warnings:hs("warnings",e?.warnings??t)}},ys=(e,t)=>n=>{n.hooks.done.tap("bundler-outputs",(n=>{t((()=>{const t=e.time("stats serialization"),o=n.toJson({all:!1,assets:!0,children:!0,chunks:!0,chunkGroupAuxiliary:!0,chunkGroupChildren:!0,chunkGroups:!0,chunkRelations:!0,entrypoints:!0,errors:!0,ids:!0,modules:!0,nestedModules:!0,relatedAssets:!0,warnings:!0,reasons:!1,chunkModules:!1});return t.end(),o}))}))},bs=e=>{const t=new Set;return{buildStart(){t.clear()},writeBundle(e,n){t.add(n)},closeBundle(){e((()=>Array.from(t)))}}},ws=({options:e,context:t})=>{const n=t.getLogger(ms),o=(e=>({path:"./",...e[fs],files:gs(e[fs]?.files)}))(e),r=(e,r)=>{const s=o.files[e];if(!r||!1===s)return;t.queue((async()=>{const e=n.time(`output ${s}`),c=((e,t,n)=>{const o=u.isAbsolute(t)?t:u.resolve(e,t);return u.resolve(o,n)})(t.bundler.outDir,o.path,s);let d;try{const e="function"==typeof r?await r():r;await(async(e,t)=>{await De(u.dirname(e));const n=i.createWriteStream(e),o=new a(t,void 0,2),r=new Promise(((e,t)=>{o.on("end",(()=>{e()})),o.on("error",(e=>{t(e)}))}));return o.pipe(n),r})(c,e)}catch(e){d=e}d?n.error(`Failed writing ${s}: ${d}`):n.debug(`Wrote "./${u.relative(t.buildRoot,c)}"`),e.end()})())};return[{name:ms,buildReport(e){const t=n.time("serialize report"),o=te(e);t.end(),r("build",{bundler:o.bundler,metadata:o.metadata,start:o.start,end:o.end,duration:o.duration,writeDuration:o.writeDuration,entries:o.entries,outputs:o.outputs}),r("logs",o.logs),r("timings",o.timings),r("dependencies",o.inputs),r("errors",o.errors),r("warnings",o.warnings)},metrics(e){r("metrics",(()=>Array.from(e)))},esbuild:{setup(e){e.onEnd((e=>{r("bundler",e.metafile)}))}},rspack:ys(n,(e=>{r("bundler",e)})),rollup:bs((e=>{r("bundler",e)})),vite:bs((e=>{r("bundler",e)})),webpack:ys(n,(e=>{r("bundler",e)}))}]},vs="rum",$s="datadog-rum-plugin",ks=["8","9","a","b"],xs=(e,t)=>{const n={service:e.service,version:e.version};return e.debugId&&(n.ddDebugId=t?(e=>{const t=p("sha256").update(e).digest("hex").slice(0,32),n=`${t.slice(0,12)}4${t.slice(13)}`,o=n.charCodeAt(16)%4,r=`${n.slice(0,16)}${ks[o]}${n.slice(17)}`;return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")})(t):f()),`(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(n)},${JSON.stringify("DD_SOURCE_CODE_CONTEXT")});`},Ss="datadog-rum-privacy-plugin";const Es=(e,t)=>{const n=t.getLogger(Ss),o=function(e,t){const n={privacy:{addToDictionaryHelper:{expression:{code:e}}}};return["esbuild","webpack","rspack"].includes(t)&&(n.output={...n.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),n}(e.helperCodeExpression,t.bundler.name);let r=0,s=0;return{name:Ss,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(e,t){try{const n=function(e){if("rspack"===e?.framework||"webpack"===e?.framework)switch(typeof e.inputSourceMap){case"undefined":return;case"string":return e.inputSourceMap;default:return JSON.stringify(e.inputSourceMap)}}(this.getNativeBuildContext?.()),i=S({id:t,code:e,map:n},o);return 0===i.privacyDictionarySize?{code:e}:(r+=i.privacyDictionarySize,s++,i)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}},buildEnd:()=>{n.debug(`Privacy dictionary will include ${r} entries across ${s} files`,{forward:!0,context:{dictionaryEntryCount:r,fileCount:s}})}}},Is=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,Ds=(e,t)=>{const n=e.sdk;if(n.clientToken)return Is(e);if(!t.auth.apiKey||!t.auth.appKey)throw new Error('Missing "auth.apiKey" and/or "auth.appKey" to fetch "rum.sdk.clientToken".');return async()=>{let o;try{const e=await Q({url:`https://api.${t.auth.site}/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});o=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!o)throw new Error("Missing clientToken in the API response.");return Is({...e,sdk:{clientToken:o,...n}})}},As=e=>{const n=t.bold.red,o=e[vs]||{},r={errors:[]};if(!o.sdk)return r;o.sdk.applicationId||r.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth.apiKey&&e.auth.appKey||o.sdk.clientToken||r.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const s={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:e.auth.site||"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};return r.config={...s,...o.sdk},r},Ps=e=>{const t=e[vs]||{},n={errors:[]};if(t.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`-]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helperCodeExpression:"/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()"};n.config={...e,...t.privacy}}return n},js=e=>{const n=t.bold.red,o=e[vs]||{},r={errors:[]};if(!o.sourceCodeContext)return r;const s=o.sourceCodeContext;return s?.debugId||s?.service&&"string"==typeof s.service||r.errors.push(`Missing ${n('"rum.sourceCodeContext.service"')}.`),r.config={...s,version:s.version||e.metadata?.version},r},Ms=({options:e,context:t})=>{const n=((e,t)=>{const n=[],o=As(e),r=Ps(e),s=js(e);if(n.push(...o.errors),n.push(...r.errors),n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${$s}.`);const i={...e[vs],sdk:void 0,privacy:void 0,sourceCodeContext:void 0};return o.config&&(i.sdk=o.config),r.config&&(i.privacy=r.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(i.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),s.config&&(i.sourceCodeContext=s.config),i})(e,t.getLogger($s)),o=[],r=n.sourceCodeContext;if(r&&t.inject({type:"code",position:Ce.BEFORE,injectIntoAllChunks:!0,value:e=>xs(r,e)}),n.sdk&&(t.inject({type:"file",position:Ce.MIDDLE,value:u.join(T,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Ce.MIDDLE,value:Ds(n,t)})),n.privacy){t.inject({type:"file",position:Ce.BEFORE,value:u.join(T,"./privacy-helpers.js")});const e=Es(n.privacy,t);o.push(e)}return o},Ts="datadog-analytics-plugin",Cs=({context:e})=>{const t=e.getLogger(Ts);return[{name:Ts,async buildStart(){"production"===e.env&&e.queue((async()=>{try{await e.sendLog({message:"Build started",context:{plugins:e.pluginNames}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}})())}}]},Os="datadog-async-queue-plugin",Ns=e=>{const{context:t,stores:n}=e,o=t.getLogger(Os),r=[];return t.queue=e=>{const t=e.catch((e=>{r.push(e.message||e.toString())}));n.queue.push(t)},[{name:Os,asyncTrueEnd:async()=>{await Promise.all(n.queue),r.length>0&&o.error(`Error occurred while processing async queue:\n ${r.join("\n ")}`)}}]},Rs=async(e,t,n)=>{const o=[],r=e.initialOptions.entryPoints,s=[],i=[];if(Array.isArray(r))for(const e of r){const t=e&&"object"==typeof e?e.in:e;s.push({path:t})}else r&&"object"==typeof r&&s.push(...Object.entries(r).map((([e,t])=>({name:e,path:t}))));const a=s.flatMap((e=>{return(t=e.path,t.includes("*")?w.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,r])=>{const s=await e.resolve(r,{kind:"entry-point",resolveDir:t.buildRoot});s.errors.length&&i.push(...s.errors.map((e=>e.text))),s.path&&o.push({name:n.name,resolved:s.path,original:n.path})}));for(const e of i)n.error(e);return await Promise.all(a),o},_s=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Fs=/(\?|%3F|\|)+/gi,zs=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=Bs(e),_s.lastIndex=0,_s.exec(t)?.[1]||"unknown");var t},Ls=["unknown","commonjsHelpers.js",`vite${u.sep}preload-helper.js`],Us=(e,t,n)=>{const o=new Set;for(const n of e){const e=Bs(n);ee(n)||e===t||Ls.includes(e)||o.add(e)}return o},Bs=e=>e.split("!").pop().split(Fs).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),qs=(e,t)=>ee(t)?O:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(u.sep),o=e.split(u.sep).filter(((e,t)=>e===n[t])).join(u.sep);return e.replace(o,"")})(t.split("!").pop(),e).split("node_modules").pop().split(Fs).shift().replace(/^((\.\.?)?[/\\])+/g,""),Vs=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[eo(t,e),n]))),Ks=(e,t)=>({setup(n){const o=new Map;let r=[];const s=t.time("build report",{start:!1});n.onStart((async()=>{o.clear(),r=[],s.resume();const i=t.time("process entries");r.push(...await Rs(n,e,t));for(const t of r){const n=qs(e.bundler.outDir,t.resolved);t.name?o.set(n,t.name):o.set(n,n)}i.end(),s.pause()})),n.onEnd((async n=>{s.resume();const r=t.time("collecting errors and warnings"),i=e.bundler.outDir,a=e.buildRoot;for(const t of n.errors)e.build.errors.push(t.text);for(const t of n.warnings)e.build.warnings.push(t.text);if(r.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const c=[],d=[],l=[],p=[],f=[],m={},h={},g=t.time("indexing metafile data"),y=Vs(n.metafile.inputs,a),b=Vs(n.metafile.outputs,a);g.end();const w=e=>{if(!ee(e))return e;const t=y[eo(a,e)];if(!t)return e;const n=t.imports.find((e=>!ee(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(ee(e))continue;const n=eo(a,e),o={name:qs(i,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:zs(e)};m[n]=o,c.push(o)}v.end();const $=t.time("looping through outputs");for(const[e,r]of Object.entries(n.metafile.outputs)){const n=eo(a,e),s=qs(i,n),u=[];for(const e of Object.keys(r.inputs)){if(ee(e))continue;const n=m[eo(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${s}`)}if(r.entryPoint&&!u.length){const e=m[eo(a,r.entryPoint)];if(!e){t.debug(`Input ${r.entryPoint} not found for output ${s}`);continue}u.push(e)}const c={name:s,filepath:n,inputs:u,size:r.bytes,type:zs(n)};if(h[n]=c,"map"===c.type&&p.push(c),d.push(c),!r.entryPoint)continue;const f=m[eo(a,w(r.entryPoint))];if(f){if(!o.get(f.name))continue;const e={...c,name:o.get(f.name)||f.name,outputs:[c],size:c.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of p){const n=h[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}k.end();const x={inputs:{report:m,meta:y},outputs:{report:h,meta:b}},S=/(<runtime>|https:|file:|data:|#)/g,E=e=>!ee(e)&&!e.match(S),I=(e,n,o={})=>{if(!E(e))return o;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const s=n.meta[e];if(!s)return t.debug(`Could not find metafile's ${e}`),o;if(!s.imports||!s.imports.length)return o;for(const t of s.imports){const s=t.path.match(/^\.\.?\//),d=s?u.dirname(e):a,l=eo(d,t.path);if(t.external){if(E(t.path)){const e=s?l:t.path,n=x.inputs.report[e]||{filepath:e,name:qs(i,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(n.dependents.add(r),r.dependencies.add(n)),"inputs"in r&&!r.inputs.includes(n)&&r.inputs.push(n),c.includes(n)||c.push(n),x.inputs.report[e]=n,o[n.filepath]=n}}else I(l,n,o)}return o},D=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)I(n.filepath,x.inputs,t);for(const t of e.outputs)I(t.filepath,x.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),f.push(e)}D.end();const A=t.time("aggregate dependencies and dependents");for(const e of c){if("external"===e.type)continue;const n=x.inputs.meta[e.filepath];if(n)for(const o of n.imports){if(!E(o.path))continue;const n=o.path.match(/^\.?\.\//),r=n?u.dirname(e.filepath):a,s=eo(r,o.path);let i;if(o.external){const e=n?s:o.path;i=x.inputs.report[e]}else i=x.inputs.report[s];i?(e.dependencies.add(i),i.dependents.add(e)):t.debug(`Could not find input file of ${o.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}A.end(),e.build.outputs=d,e.build.inputs=c,e.build.entries=f,s.end(),await e.asyncHook("buildReport",e.build)}))}}),Hs=(e,t)=>{const n=t.time("module parsing",{start:!1}),o=t.time("build report",{start:!1}),r=t.time("filling entries",{start:!1}),s=t.time("filling inputs and outputs",{start:!1}),a=t.time("completing dependencies and dependents",{start:!1}),u=t.time("filling dependencies and dependents",{start:!1}),c=t.time("filling sourcemaps inputs",{start:!1}),d=new Map,l=new Map,p=new Map,f=new Map;return{buildStart(){f.clear(),d.clear(),l.clear(),p.clear()},onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){n.resume();const t=Bs(e.id),o=f.get(t)||{dependencies:new Set,dependents:new Set},r=Us(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),s=Us(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of s)o.dependents.add(e);for(const e of r)o.dependencies.add(e);f.set(t,o),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){o.resume();const h=n.dir?eo(e.buildRoot,n.dir):e.bundler.outDir,g=new Set,y=new Set,b=new Map;a.resume();for(const[e,{dependencies:t,dependents:n}]of f){for(const n of t){const t=Bs(n),o=f.get(t)||{dependencies:new Set,dependents:new Set};o.dependents.has(e)||(o.dependents.add(e),f.set(t,o))}for(const t of n){const n=Bs(t),o=f.get(n)||{dependencies:new Set,dependents:new Set};o.dependencies.has(e)||(o.dependencies.add(e),f.set(n,o))}}a.end(),s.resume();for(const[e,n]of Object.entries(m)){const o=eo(h,e),r="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),s=l.get(o)||{name:e,filepath:o,inputs:[],size:r,type:zs(e)};if("map"===s.type&&y.add(s),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(Bs(e)!==e)continue;let n=t.originalLength;if(!n&&0!==n)try{n=i.statSync(e).size}catch(e){n=t.renderedLength}const o=d.get(e)||{name:qs(h,e),dependencies:new Set,dependents:new Set,filepath:e,size:n,type:zs(e)};s.inputs.push(o),d.set(o.filepath,o)}if("imports"in n)for(const e of n.imports){const n=Bs(e);if(!f.has(n)){b.set(eo(h,n),s);continue}if(d.has(n)){t.debug(`Input report already there for ${n} from ${s.name}.`);continue}const o=d.get(n)||{name:qs(h,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};s.inputs.push(o),d.set(o.filepath,o)}"isEntry"in n&&n.isEntry&&g.add({...s,name:n.name,size:0,outputs:[s]}),l.set(s.filepath,s)}s.end();for(const[e,n]of b){const o=l.get(e);o?n.inputs.includes(o)||n.inputs.push(o):t.debug(`Could not find the output report for ${e}.`)}u.resume();for(const[e,n]of d){const o=f.get(e);if(o){for(const e of o.dependencies){const o=d.get(e);o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${qs(h,e)} of ${n.name}`)}for(const e of o.dependents){const o=d.get(e);o?n.dependents.add(o):t.debug(`Could not find input for dependent ${qs(h,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(u.end(),y.size){c.resume();for(const e of y){const n=e.filepath.replace(/\.map$/,""),o=l.get(n);o?e.inputs.push(o):t.debug(`Could not find output for sourcemap ${e.name}`)}c.end()}const w=(e,n=new Map)=>{if(n.has(e))return n;const o=qs(h,e),r=l.get(e);if(!r)return d.has(o)||t.debug(`Could not find output for ${o}`),n;n.set(e,r);const s=m[qs(h,e)];if(!s)return t.debug(`Could not find asset for ${o}`),n;const i=[];"imports"in s&&i.push(...s.imports),"dynamicImports"in s&&i.push(...s.dynamicImports);for(const e of i)w(eo(h,e),n);return n};r.resume();for(const e of g){const n=w(e.filepath);e.outputs=Array.from(n.values()),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.has(e.filepath)&&t.debug(`Entry "${e.name}":"${qs(h,e.filepath)}" already reported.`),p.set(e.filepath,e)}r.pause(),o.pause()},async closeBundle(){e.build.inputs=Array.from(d.values()),e.build.outputs=Array.from(l.values()),e.build.entries=Array.from(p.values()),r.end(),o.end(),await e.asyncHook("buildReport",e.build)}}},Ws=(e,t,n)=>o=>{let r=[],s=[],i=[];const a=new Map,u=new Map,c=new Map,d=new Map,l=[],p=new Map,f=n.time("build report",{start:!1}),m=e=>!(!e||e.startsWith("webpack/runtime")||e.startsWith("multi ")||ee(e)),h=e=>e.replace(/(^external[^"]+"|"$)/g,""),g=e=>{const t=(e=>{const t=e.identifier();return{identifier:()=>t,dependencies:"dependencies"in e?[...e.dependencies]:[],blocks:"blocks"in e?[...e.blocks]:[],externalType:"externalType"in e?e.externalType:void 0,external:"external"in e?e.external:void 0}})(e),n=(e=>{const t=new Set,n=["rawRequest","resource","request","userRequest"],o=e=>{const n=Bs(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};o(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&o(n)}return t})(e);for(const e of n)if(d.has(e)){const n=d.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else d.set(e,t)},y=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),y(n,t);if("blocks"in e)for(const n of e.blocks)y(n,t);return t},b=(e,t)=>{if("request"in t&&t.request){const n=Bs(t.request);if(d.has(n))return d.get(n);if(e.context){const t=eo(Bs(e.context),n);if(d.has(t))return d.get(t)}}},w=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));o.hooks.thisCompilation.tap(t,(o=>{r=[],s=[],i=[],a.clear(),u.clear(),d.clear(),p.clear(),o.hooks.finishModules.tap(t,(t=>{f.resume();const o=n.time("dependency graph"),s=n.time("indexing modules");for(const e of t)g(e);s.end();const i=n.time("building inputs");for(const n of t){const t=n.identifier(),o=qs(e.bundler.outDir,t),s=new Set(y(n).map((e=>{const o=b(n,e);if(!o?.identifier())return!1;const r=o.identifier();return!!m(r)&&(r!==t&&(w(o)?h(r):r))})).filter(Boolean));if(!m(t))continue;const i=p.get(t)||{dependents:new Set,dependencies:new Set};for(const e of s){const n=p.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),i.dependencies.add(e),p.set(e,n)}p.set(t,i);const u=w(n)?{size:0,name:h(o),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:o,dependencies:new Set,dependents:new Set,filepath:t,type:zs(t)};r.push(u),a.set(t,u),w(n)&&a.set(h(t),u)}i.end();const u=n.time("assigning dependencies and dependents");for(const e of r){const t=p.get(e.filepath);if(t){for(const o of t.dependencies){const t=a.get(o);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${o}`)}for(const o of t.dependents){const t=a.get(o);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${o}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),o.end(),f.pause()}))})),o.hooks.afterEmit.tapPromise(t,(async t=>{f.resume();const o=t.chunks,d=t.getAssets(),p=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>eo(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of o){const t=p(e),n=(g?.getChunkModules(e)||[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(m);for(const e of t){if("map"===zs(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of d){const o={size:t.source.size()||0,name:t.name,inputs:[],filepath:eo(e.bundler.outDir,t.name),type:zs(t.name)};if(u.set(o.filepath,o),s.push(o),"map"===o.type){l.push(o);continue}const r=c.get(o.filepath);if(r)for(const e of r){const t=a.get(e);t?o.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${o.name}`)}y.end();const b=n.time("filling sourcemaps inputs");for(const e of l){const t=u.get(e.filepath.replace(/\.map$/,""));t?e.inputs.push(t):n.debug(`Output not found for sourcemap ${e.name}`)}b.end();const w=n.time("building entries"),v=(e,t=new Set)=>{if(t.has(e))return new Set;t.add(e);const n=new Set(e.chunks);for(const o of e.childrenIterable||[]){const e=v(o,t);for(const t of e)n.add(t)}return n};for(const[o,r]of t.entrypoints){const t=new Map,s=new Map;let a=0;const c=v(r),d=Array.from(c).flatMap(p),l=r.chunks.filter((e=>g.getChunkEntryModulesIterable(e)||!1)).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(o)||r.name&&e.includes(r.name))).find((e=>"js"===zs(e)));for(const e of d){const o=u.get(e);if(e&&o){if("map"!==o.type&&!t.has(o.name)){t.set(o.name,o);for(const e of o.inputs)s.has(e.filepath)||s.set(e.filepath,e);a+=o.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const f={name:o,filepath:l?eo(e.bundler.outDir,l):"unknown",size:a,inputs:Array.from(s.values()),outputs:Array.from(t.values()),type:l?zs(l):"unknown"};i.push(f)}w.end();for(const n of t.errors)e.build.errors.push(n.message);for(const n of t.warnings)e.build.warnings.push(n.message);e.build.inputs=r,e.build.outputs=s,e.build.entries=i,f.end(),await e.asyncHook("buildReport",e.build)}))},Js="datadog-build-report-plugin",Gs=e=>{const{context:t}=e,n=t.getLogger(Js);return[{name:Js,enforce:"post",esbuild:Ks(t,n),rspack:Ws(t,Js,n),webpack:Ws(t,Js,n),vite:Hs(t,n),rollup:Hs(t,n)}]},Ys="datadog-bundler-report-plugin",Qs=(e,t)=>t?u.isAbsolute(t)?t:u.resolve(e,t):"",Zs=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?u.dirname(e.file):void 0)).filter(Boolean)},Xs=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=Qs(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.buildRoot=t.options.context),e.hook("buildRoot",e.buildRoot)},ei=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const o=t.build?.rollupOptions?.output,r=Zs(o);e.buildRoot=t.root??process.cwd(),o&&r.length&&(n=no(r,process.cwd())),e.bundler.outDir=Qs(e.buildRoot,n),e.hook("buildRoot",e.buildRoot),e.hook("bundlerReport",e.bundler)}}),ti=e=>{const{context:t}=e,n=t.getLogger(Ys);return[{name:Ys,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.buildRoot=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=Qs(t.buildRoot,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=Qs(t.buildRoot,u.dirname(e.initialOptions.outfile))),t.hook("buildRoot",t.buildRoot),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:Xs(t),rspack:Xs(t),vite:ei(t),rollup:{options(e){let n;if("output"in e){const t=Zs(e.output);n=no(t,process.cwd())}const o=(e=>{const t=new Set;if(e.input){const n=Array.isArray(e.input)?e.input:"object"==typeof e.input?Object.values(e.input):[e.input];for(const e of n){if("string"!=typeof e)throw new Error("Invalid input type");t.add(u.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=eo(process.cwd(),n);const e=no([n,...o],process.cwd());t.buildRoot=e===u.sep?process.cwd():e}else t.buildRoot=no(o,process.cwd()),t.bundler.outDir=u.resolve(process.cwd(),"dist");t.hook("buildRoot",t.buildRoot)},buildStart(e){t.bundler.rawConfig=e},renderStart(e){t.bundler.rawConfig.outputs=t.bundler.rawConfig.outputs||[],t.bundler.rawConfig.outputs.push(e),t.hook("bundlerReport",t.bundler);const o=Zs(e);no(o,process.cwd()).startsWith(t.bundler.outDir)||n.warn("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},ni="datadog-custom-hooks-plugin",oi=e=>{const{context:t}=e,n=t.getLogger(ni),o=e=>(o,...r)=>{const s=n.time(`execution | ${o}`,{tags:["type:custom-hook",`hook:${o}`]}),i=[],a=[];for(const n of t.plugins){if(!(o in n))continue;const t=n[o];if("function"==typeof t)try{const s=t(...r);s instanceof Promise&&(e||i.push(`Plugin "${n.name}" returned a promise on the non async hook "${o}".`),a.push(s))}catch(e){i.push(`Plugin "${n.name}" errored on hook "${o}". [${e}]`)}else i.push(`Plugin "${n.name}" has an invalid hook type for "${o}". [${typeof t}]`)}if(i.length>0){for(const e of i)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>s.end()))};return t.hook=o(!1),t.asyncHook=o(!0),[{name:ni,enforce:"pre"}]};class ri{constructor(e){this.trackedFilenames=new Map;for(const t of e){const e=this.getFilename(t),n=this.trackedFilenames.get(e);n?n.push(t):this.trackedFilenames.set(e,new Array(t))}}displaySource(e){return e.length<=40?e:`[...]${e.slice(-35)}`}matchSourcemap(e,t){const n=Pe(e),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const r=o.sources;if(0===r.length)return void t("Empty 'sources' field in sourcemap.");const s=this.matchSources(r);if(0!==s.length)return s;t(`${r.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const o of e){const e=this.getFilename(o);if(n.has(e))continue;n.add(e);const r=this.trackedFilenames.get(e);r&&(t=t.concat(r))}return t}rawTrackedFilesList(){let e=[];return this.trackedFilenames.forEach((t=>{e=e.concat(t)})),e}getFilename(e){let t=e.lastIndexOf("/");-1===t?t=0:t++;let n=e.lastIndexOf("?");return(-1===n||n<=t)&&(n=e.length),e.substring(t,n)}}const si=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await ii(e);for(const e of t)if(e.name===n)return se(e.refs.push);return se(t[0].refs.push)},ii=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},ai=async e=>e.revparse("HEAD"),ui=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ci=async e=>e.branch(),di=async e=>e.show(["-s","--format=%s"]),li=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),pi="datadog-git-plugin",fi=e=>{const{options:t,context:n}=e,o=n.getLogger(pi),r=o.time("get git information",{start:!1}),s=async e=>{try{const t=await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=E(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return E(t)})(u.dirname(e));if(0===(await t.getRemotes(!0)).length)return o.warn("No git remotes available, skipping git plugin. This is expected for a repository that has not been pushed yet."),void r.end();const s=await(async e=>{const t=[ai(e),ci(e),di(e),li(e),ui(e),si(e)],[n,o,r,s,i,a]=await Promise.all(t),[u,c,d,l,p,f]=s.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:d},committer:{name:l,email:p,date:f},message:r.trim(),hash:n},hash:n,branch:o.current,remote:a.trim(),trackedFilesMatcher:new ri(i)}})(t);n.git=s,r.end(),await n.asyncHook("git",n.git)}catch(e){o.error(`Could not get git information: ${e.message}`)}};return[{name:pi,enforce:"pre",buildRoot(e){if(ne(t))try{r.resume();const t=to(e,".git");if(!t)return o.warn("No .git directory found, skipping git plugin."),void r.end();n.queue(s(t))}catch(e){o.error(`Could not get git information: ${e.message}`)}}}]},mi="datadog-injection-plugin",hi=/^https?:\/\//,gi=[".mjs",".mjsx",".js",".ts",".tsx",".jsx"],yi=t.bold.yellow,bi=async(e,t=process.cwd())=>(e=>r.readFile(e,{encoding:"utf-8"}))(eo(t,e));function wi(e){return e.some((e=>e.injectIntoAllChunks))}const vi=(e,t,n)=>{const o=e.filter((e=>e.position===t&&(!n||n.isEntry||e.injectIntoAllChunks))).map((e=>Di(e.value)?e.value(n):e.value)).filter(Boolean);if(0===o.length)return"";return`// begin injection by Datadog build plugins\n${o.map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},$i=async(e,t,n=process.cwd())=>{const o=Di(e.value)?await e.value():e.value;try{if("file"===e.type){const e=o;return await(e.match(hi)?(async(e,t=5e3)=>{let n;return Promise.race([Q({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error("Timeout"))}),t)}))])})(e):bi(e,n))}return o}catch(r){const s=`${e.type} - ${re(o)}`;return e.fallback?(t.debug(`Fallback for "${s}": ${r.toString()}`),$i(e.fallback,t,n)):(t.warn(`Failed "${s}": ${r.toString()}`),"")}},ki=async(e,t,n,o=process.cwd())=>{const r=t.filter(Ii).map((e=>{const t=e.value;return{...e,value:e=>t(e.sourceOrHash)}})),s=t.filter((e=>!Ii(e))),i=await Promise.all(s.map((async t=>({...t,value:await $i(t,e,o)})))),a=e=>({...e,position:e.position??Ce.BEFORE});n.push(...r.map(a),...i.map(a))},xi=e=>e instanceof Error&&"code"in e,Si=e=>gi.includes(e),Ei=(e,t,n)=>{e.warn(`"${yi(t)}" files are not supported (${yi(n)}).`)},Ii=e=>"function"==typeof e.value&&1===e.value.length,Di=e=>"function"==typeof e,Ai=i.promises,Pi=(e,t,n)=>({setup(o){const{onStart:s,onResolve:a,onLoad:c,onEnd:d,esbuild:l,initialOptions:p}=o,f=[],m=`${t.bundler.name}.${Ce.MIDDLE}.${O}.js`,g=i.realpathSync(h.tmpdir()),y=u.resolve(g,m),b=new RegExp(`${m}$`),w=p.inject;p.inject=w?[...w]:[],p.inject.push(y),s((async()=>{f.push(...await Rs(o,t,e)),o.initialOptions.inject=w;try{await(async(e,t)=>{await De(u.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})})(y,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:b},(async e=>({path:e.path,namespace:mi}))),c({filter:b,namespace:mi},(async()=>({contents:vi(n,Ce.MIDDLE)||" ",resolveDir:t.buildRoot,loader:"js"}))),d((async o=>{if(!o.metafile)return void e.warn("Missing metafile from build result.");if(!function(e){return e.some((e=>e.position===Ce.BEFORE||e.position===Ce.AFTER))}(n))return;const r=[];for(const[s,i]of Object.entries(o.metafile.outputs)){const o=Boolean(i.entryPoint&&f.some((e=>e.resolved.endsWith(i.entryPoint))));if(!o&&!wi(n))continue;const a=eo(t.buildRoot,s),{base:c,ext:d}=u.parse(a);Si(d)?r.push((async()=>{try{const e=`${a}.map`,t=await Ai.readFile(a,"utf-8"),r=await Ai.readFile(e,"utf-8").catch((()=>!1)),s=u.basename(a),i=vi(n,Ce.BEFORE,{sourceOrHash:t,fileName:s,isEntry:o}),c=vi(n,Ce.AFTER,{sourceOrHash:t,fileName:s,isEntry:o});if(!i&&!c)return;const d=t.replace(/\n?\/\/# sourceMappingURL=.*$/m,""),p=r?`${d}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(r).toString("base64")}`:d,f=await l.transform(p,{loader:"default",banner:i,footer:c,sourcemap:r?"external":void 0,sourcefile:s});await Promise.all([Ai.writeFile(a,f.code),r&&f.map?Ai.writeFile(e,f.map):null])}catch(t){if(!xi(t)||"ENOENT"!==t.code)throw t;e.warn(`Could not inject content in ${a}: ${t}`)}})()):Ei(e,d,c)}await Promise.all(r)}))}}),ji=O,Mi="?inject-proxy",Ti=(e,t)=>({renderChunk(n,o){const{base:r,ext:s}=u.parse(o.fileName);if(!Si(s))return Ei(e,s,r),null;const i=vi(t,Ce.BEFORE,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry}),a=vi(t,Ce.AFTER,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry});if(!i&&!a)return null;const c=new I(n);return i&&c.prepend(`${i}\n`),a&&c.append(`\n${a}`),{code:c.toString(),map:c.generateMap({file:o.fileName,hires:"boundary"})}},async resolveId(e,n,o){if(ee(e))return{id:e,moduleSideEffects:!0};if(o.isEntry&&vi(t,Ce.MIDDLE)){if(e.endsWith(".html"))return null;const t=await this.resolve(e,n,o);if(!t||t.external)return t;return(await this.load(t)).moduleSideEffects=!0,`${t.id}${Mi}`}return null},load(e){if(ee(e))return vi(t,Ce.MIDDLE);if(e.endsWith(Mi)){const t=e.slice(0,-13),n=this.getModuleInfo(t);let o=`import ${JSON.stringify(ji)};\nexport * from ${JSON.stringify(t)};`;return n?.hasDefaultExport&&(o+=`export { default } from ${JSON.stringify(t)};`),o}return null}}),Ci=(e,t,n,o,r)=>s=>{const a=new WeakMap,c=e.sources.ConcatSource,d=n.bundler.name,l=u.resolve(n.buildRoot,"node_modules",".cache","datadog-build-plugins",`${d}.${Ce.MIDDLE}.${O}.js`);Ae(l,"");s.hooks.shutdown.tap(mi,(()=>{var e;e=l,i.rmSync(e,{force:!0,maxRetries:3,recursive:!0})}));const p=async()=>{await ki(t,o,r,n.buildRoot)};s.hooks.beforeRun.tapPromise(mi,p),s.hooks.watchRun.tapPromise(mi,p),s.hooks.compilation.tap(mi,(n=>{const o=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;n.hooks.processAssets.tap({name:mi,stage:o},(()=>{for(const e of n.chunks){const o=e.canBeInitial(),s=e.contentHash?.javascript??e.hash;for(const i of e.files){const{base:e,ext:d}=u.parse(i);if(!Si(d)){Ei(t,d,e);continue}const l=u.basename(i),p=vi(r,Ce.BEFORE,{sourceOrHash:s,fileName:l,isEntry:o}),f=vi(r,Ce.AFTER,{sourceOrHash:s,fileName:l,isEntry:o});""===p&&""===f||n.updateAsset(i,(e=>{const t=a.get(e);if(!t||t.banner!==p||t.footer!==f){const t=new c(p,"\n",e,"\n",f);return a.set(e,{source:t,banner:p,footer:f}),t}return t.source}))}}}))}));const f=(e=>{const n={import:[l]},o=e=>{for(const[n,o]of Object.entries(e))"object"==typeof o?(o.import=o.import||[],o.import.unshift(l)):"string"==typeof o?e[n]=[l,o]:Array.isArray(o)?o.unshift(l):t.error("Invalid entry type: "+typeof o)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[n,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:n}})(s.options.entry);s.options.entry=f},Oi=e=>{const{bundler:t,context:n}=e,o=n.getLogger(mi),r=[],s=[];n.inject=e=>{r.push(e)};const i={name:mi,enforce:"post",esbuild:Pi(o,n,s),webpack:Ci(t,o,n,r,s),rspack:Ci(t,o,n,r,s),rollup:Ti(o,s),vite:{...Ti(o,s),enforce:"pre",transformIndexHtml:{order:"pre",handler:()=>vi(s,Ce.MIDDLE)?[{tag:"script",attrs:{type:"module",src:"/@id/__datadog-helper-file"},injectTo:"head-prepend"}]:[]}}};var a;return a=n.bundler.name,["rspack","webpack"].includes(a)?i.load={filter:{id:N},handler:()=>({code:vi(s,Ce.MIDDLE)})}:i.buildStart=async()=>{await ki(o,r,s,n.buildRoot)},[i]},Ni="datadog-true-end-plugin",Ri=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},o=async()=>{await t.asyncHook("flush")},r=()=>{t.hook("syncTrueEnd")},s=async()=>{r(),await n(),await o()},i=e=>{e.hooks.shutdown.tapPromise(Ni,s)},a={async writeBundle(){},async closeBundle(){await s()}};return[{name:Ni,enforce:"post",webpack:i,esbuild:{setup(e){e.onEnd((async()=>{await n(),await o()})),e.onDispose((()=>{r()}))}},vite:a,rollup:a,rspack:i}]},_i={[Rr]:ls},Fi=t.bold.red;var zi="3.2.7";const Li=(({bundler:t,version:n})=>{const o=Date.now();return e(((e,r)=>{const s=Date.now(),i=((e={})=>{const t=(e=>{const t=[];return void 0===e||void 0!==e.version&&"string"!=typeof e.version&&t.push("metadata.version must be a string"),t})(e.metadata),n=q("SITE"),o=H(n,"DATADOG_SITE/DD_SITE",t)??H(e.auth?.site,"auth.site",t),r={site:o?.site??F,siteSubdomain:o?.subdomain};if(t.length)throw new Error(`Invalid Datadog plugin configuration:\n - ${t.join("\n - ")}`);return Object.defineProperty(r,"apiKey",{value:q("API_KEY")||e.auth?.apiKey,enumerable:!1}),Object.defineProperty(r,"appKey",{value:q("APP_KEY")||e.auth?.appKey,enumerable:!1}),{enableGit:!0,logLevel:"warn",metadata:{},...e,auth:r}})(e);"esbuild"===r.framework&&(r.esbuildHostName=z);const a=process.env.BUILD_PLUGINS_ENV||"production",u=R.includes(a)?a:"development",c=t.rspackVersion||t.version||t.VERSION,d=r.framework,l={bundler:{name:d,version:c},env:u,metadata:i.metadata||{},packageName:`@datadog/${d}-plugin`,version:n},p={errors:[],logs:[],metrics:new Set,queue:[],timings:[],warnings:[]},f=(({start:e,options:t,data:n,stores:o})=>{const r=process.cwd(),s={errors:o.errors,warnings:o.warnings,logs:o.logs,metadata:n.metadata,timings:o.timings,bundler:n.bundler};return{addMetric:()=>{throw new Error("AddMetric function called before it was initialized.")},auth:t.auth,pluginNames:[],bundler:{...s.bundler,outDir:r},build:s,buildRoot:r,env:n.env,getLogger:pe(n,o,t.logLevel),asyncHook:()=>{throw new Error("AsyncHook function called before it was initialized.")},hook:()=>{throw new Error("Hook function called before it was initialized.")},inject:()=>{throw new Error("Inject function called before it was initialized.")},plugins:[],queue:()=>{throw new Error("Queue function called before it was initialized.")},sendLog:Z(n),start:e,version:n.version}})({start:o,options:i,data:l,stores:p}),m=f.getLogger("factory"),h=m.time("Plugins initialization",{start:s});f.pluginNames.push(z);const g=[];g.push(["analytics",Cs],["async-queue",Ns],["build-report",Gs],["bundler-report",ti],["custom-hooks",oi],["git",fi],["injection",Oi],["true-end",Ri]),i.customPlugins&&g.push(["custom",i.customPlugins]);const y=[["apps",be,So],["error-tracking",Eo,Ko],["live-debugger",Ho,Or],["metrics",Rr,ps],["output",fs,ws],["rum",vs,Ms]];for(const[e,t,n]of y)ye(i,t,m)&&g.push([e,n]);for(const[e,n]of g)f.plugins.push(...he(f,n,e)({bundler:t,context:f,options:i,data:l,stores:p}));return(e=>{const t=[];for(const n of B){const o=K(n);if(o.length>1&&!o.every((e=>process.env[e]===process.env[o[0]]))){const r=o.map((e=>U(e))).join(" and "),s=U(`DATADOG_${n}`);e.warn(`Conflicting keys ${r}, will use ${s}`),t.push(`${r} (using ${s})`)}else if(o.length){const e=o.map((e=>L(e))).join(" and ");t.push(`${e} (same value)`)}}t.length&&e.info(`Overrides from environment:\n - ${t.join("\n - ")}`)})(m),f.pluginNames.push(...f.plugins.map((e=>e.name))),(e=>{const t=new Set(e.filter((t=>e.filter((e=>e===t)).length>1)));if(t.size>0)throw new Error(`Duplicate plugin names: ${Fi(Array.from(t).join(", "))}`)})(f.pluginNames),f.hook("init",f),h.end(),f.plugins}))})({bundler:D,version:zi}).vite,Ui=zi,Bi=_i;export{Li as datadogVitePlugin,Bi as helpers,Ui as version};
|
|
1
|
+
import{createUnplugin as e}from"unplugin";import t from"chalk";import n from"async-retry";import{File as o}from"buffer";import r,{mkdtemp as i}from"fs/promises";import s from"fs";import{JsonStreamStringify as a}from"json-stream-stringify";import u from"path";import{Readable as c}from"stream";import{spawn as d}from"child_process";import{randomBytes as l,createHash as p,randomUUID as f}from"crypto";import m from"http";import h,{tmpdir as g}from"os";import*as y from"eslint-scope";import b from"jszip";import{glob as w}from"glob";import v from"pretty-bytes";import $ from"p-queue";import k from"@jridgewell/remapping";import{performance as x}from"perf_hooks";import{instrument as S}from"@datadog/js-instrumentation-wasm";import{simpleGit as E}from"simple-git";import I from"magic-string";import*as D from"vite";import A from"node:url";import P from"node:path";import j from"node:module";const M=A.fileURLToPath(import.meta.url),T=P.dirname(M),C=j.createRequire(import.meta.url),O="__datadog-helper-file",N=new RegExp(O),R=["development","production","test"],_=["datadoghq.com","us3.datadoghq.com","us5.datadoghq.com","datadoghq.eu","ddog-gov.com","us2.ddog-gov.com","ap1.datadoghq.com","ap2.datadoghq.com","datad0g.com"],F=_[0],z="datadog-build-plugins",L=t.bold.green,U=t.bold.yellow,B=["API_KEY","APP_KEY","SOURCEMAP_INTAKE_URL","APPS_INTAKE_URL","APPS_PUBLISH","APPS_UPLOAD_ASSETS","APPS_VERSION_NAME","APPS_AUTH_METHOD","APPS_BITS_CHAT_ID","SITE"],q=e=>process.env[`DATADOG_${e}`]||process.env[`DD_${e}`],V=(e,t)=>{if(void 0===e)return t;const n=e.toLowerCase();return!!["1","true","yes","on"].includes(n)||!["0","false","no","off"].includes(n)&&t},H=e=>{const t=[];return process.env[`DD_${e}`]&&t.push(`DD_${e}`),process.env[`DATADOG_${e}`]&&t.push(`DATADOG_${e}`),t},K=(e,t,n)=>{if(void 0===e)return;const o=(e=>{if("string"!=typeof e)return;const t=e.toLowerCase(),n=_.find((e=>e===t));if(n)return{site:n};const o=_.filter((e=>t.endsWith(`.${e}`)));if(!o.length)return;const r=o.reduce(((e,t)=>t.length>e.length?t:e)),i=t.slice(0,t.length-r.length-1);return i&&/^[a-z0-9-]+$/.test(i)?{site:r,subdomain:i}:void 0})(e);if(o)return o;n.push(`${t} "${e}" is not a supported Datadog site. See the site parameters in https://docs.datadoghq.com/getting_started/site/.`)},W=e=>null===e||"object"!=typeof e?"":Object.entries(e).map((([e,t])=>`${e}: ${"string"==typeof t?t:JSON.stringify(t)}`)).join(", "),J=e=>({"DD-EVP-ORIGIN":`${e.bundler}-build-plugin_${e.plugin}`,"DD-EVP-ORIGIN-VERSION":e.version}),G=async e=>{const{getForm:t,defaultHeaders:n={},zip:o=!0}=e,r=await t(),i=new Request("fake://url",{method:"POST",body:r});return{data:o?i.body.pipeThrough(new CompressionStream("gzip")):i.body,headers:{"Content-Encoding":o?"gzip":"multipart/form-data",...n,...Object.fromEntries(i.headers.entries())}}},Y=[400,401,403,404,405,409,413],Q=async e=>{const{auth:t,url:o,method:r="GET",getData:i,type:s="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return n((async(e,n)=>{let a;try{const e={method:r,duplex:"half"};let n={"X-Datadog-Origin":"build-plugins"};if(t&&"accessToken"in t?t.accessToken&&(n.Authorization=`Bearer ${t.accessToken}`):(t?.apiKey&&(n["DD-API-KEY"]=t.apiKey),t?.appKey&&(n["DD-APPLICATION-KEY"]=t.appKey)),"function"==typeof i){const{data:t,headers:o}=await i();e.body=t,n={...n,...o}}a=await fetch(o,{...e,headers:n})}catch(t){return e(t),{}}if(!a.ok){let t=`HTTP ${a.status} ${a.statusText}`;try{const e=(e=>{try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t)if("errors"in t&&Array.isArray(t.errors)){const e=t.errors.map(W).filter((e=>e.length>0)).join("\n");if(e)return e}else{const e=W(t);if(e)return e}}catch{}return e})(await a.text());e&&(t+=`\n${e}`)}catch{}if(Y.includes(a.status))return e(new Error(t)),{};throw new Error(t)}try{let e;return e="json"===s?await a.json():await a.text(),e}catch(t){return e(t),{}}}),a)},Z=e=>({message:t,context:n})=>Q({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:e.packageName||z,message:t,service:"build-plugins",team:"language-foundations",env:e.env,version:e.version,bundler:{name:e.bundler.name,version:e.bundler.version},metadata:e.metadata,...n};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}}),X=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),ee=e=>e.includes(O),te=e=>{const t={bundler:e.bundler,errors:e.errors,metadata:e.metadata,warnings:e.warnings,logs:e.logs,timings:e.timings,start:e.start,end:e.end,duration:e.duration,writeDuration:e.writeDuration,entries:[],inputs:[],outputs:[]};for(const n of e.entries||[]){const e={...n,inputs:[],outputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),n.outputs&&(e.outputs=n.outputs.map((e=>e.filepath))),t.entries.push(e)}for(const n of e.inputs||[]){const e={...n,dependencies:[],dependents:[]};if(n.dependencies)for(const t of n.dependencies)e.dependencies.push(t.filepath);if(n.dependents)for(const t of n.dependents)e.dependents.push(t.filepath);t.inputs.push(e)}for(const n of e.outputs||[]){const e={...n,inputs:[]};n.inputs&&(e.inputs=n.inputs.map((e=>e.filepath))),t.outputs.push(e)}return t},ne=e=>{const t=!!e.errorTracking?.sourcemaps,n=e.enableGit??!0;return t&&n},oe=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),o=n.getUTCHours(),r=n.getUTCMinutes(),i=n.getUTCSeconds(),s=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${o?`${o}h `:""}${r?`${r}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||s?` ${s}ms`:""}`.trim()},re=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const o=Math.max(4,t-n.length),r=Math.min(10,Math.floor(o/2)),i=o-r;return`${e.slice(0,r)}${n}${e.slice(-i)}`},ie=(e="")=>{try{if(!e||e.startsWith("git@"))return e;const t=new URL(e),n="/"===t.pathname?"":t.pathname;return`${t.protocol?`${t.protocol}//`:""}${t.host}${n}`}catch{return e}},se=e=>e.trim().toLowerCase().replace(/[^a-z0-9_:./-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown",ae=e=>Object.entries(e).map((([e,n])=>` - ${e}: ${t.bold.green((e=>{if(void 0===e)return"undefined";if(null===e)return"null";if(Array.isArray(e))return e.join(", ");if("object"==typeof e)try{return JSON.stringify(e,null,2)}catch{return String(e)}return e?.toString()??""})(n))}`)).join("\n"),ue={debug:0,info:1,warn:2,error:3,none:4},ce=e=>e.split(">").map(X).join(">"),de=(e,n,o,r)=>{const i=ce(e);return(s,a="debug",{forward:u,context:c}={})=>{let d=t.dim,l=console.log;"error"===a?(d=t.red,l=console.error):"warn"===a?(d=t.yellow,l=console.warn):"info"===a&&(d=t.cyan,l=console.log);const p=`[${n.metadata?.name?`${n.metadata.name}|`:""}${a}|${n.bundler.name}|${i}]`,f="string"==typeof s?s:JSON.stringify(s,null,2);if(o.logs.push({bundler:n.bundler.name,pluginName:e,type:a,message:f,time:Date.now()}),"error"===a&&o.errors.push(f),"warn"===a&&o.warnings.push(f),u){const t=async()=>{try{const t=Z(n);await t({message:f,context:{plugin:e,status:a,...c}})}catch(t){de(e,n,o,r)(`Error forwarding log: ${t}`,"debug")}};o.queue.push(t())}ue[a]>=ue[r]&&l(`${d(p)} ${f}`)}},le=(e,n,o)=>(r,i={})=>{const{level:s="debug",start:a=!0,log:u=!0,tags:c=[]}=i,d={pluginName:e,label:r,spans:[],tags:[...c,`plugin:${e}`,`level:${s}`],logLevel:s,total:0};n.push(d);const l=()=>d.spans.filter((e=>!e.end)),p=n=>{l().length||(!d.spans.length&&u&&o(t.dim(`[${t.cyan(r)}] : start`),"debug"),d.spans.push({start:n||Date.now(),tags:[`plugin:${e}`]}))},f=(e,n=!0)=>{const i=l();if(i?.length){i.length>1&&o(`Timer ${t.cyan(r)} has more than one ongoing span.`,"debug");for(const t of i)t.end=e||Date.now()}else n&&o(`Timer ${t.cyan(r)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),p(e)}return{timer:d,resume:p,end:e=>{f(e,!1);const n=d.spans.reduce(((e,t)=>e+(t.end-t.start)),0);d.total=n,u&&o(`[${t.cyan(r)}] : ${t.cyan(oe(n))}`,s)},pause:f,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else d.tags.push(...e)}}},pe=(e,t,n="warn")=>o=>{const r=de(o,e,t,n);return{getLogger:r=>pe(e,t,n)(`${ce(o)}>${r}`),time:le(o,t.timings,r),error:(e,t)=>r(e,"error",t),warn:(e,t)=>r(e,"warn",t),info:(e,t)=>r(e,"info",t),debug:(e,t)=>r(e,"debug",t)}},fe=["buildEnd","buildStart","load","resolveId","transform","watchChange","writeBundle","buildRoot","init","buildReport","bundlerReport","git"],me=(e,t,n,o)=>{const r=n=>function(...r){const i=o.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),s=n.apply(this,r);return s instanceof Promise?s.finally((()=>{i.end()})):(i.end(),s)};return"object"==typeof n&&null!==n&&"handler"in n?{...n,handler:r(n.handler)}:r(n)},he=(e,t,n)=>{const o=e.getLogger(z);return e=>{const r=o.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},o=X(e.name);for(const r of fe){const i=e[r];i&&(n[r]=me(o,r,i,t))}return n})(e,o))),s=i.map((e=>`plugin:${e.name}`));return r.tag(s),r.end(),i}},ge=new Set,ye=(e,t,n)=>{const o=e[t];if(o&&"object"==typeof o&&"enable"in o){const e=o.enable;if("boolean"!=typeof e&&void 0!==e&&(ge.has(t)||(ge.add(t),n.warn(`\`${t}.enable\` should be a boolean, got ${typeof e}. Non-boolean values are coerced today but will be rejected in the next major.`))),void 0!==e)return!!e}return!!o},be="apps",we="datadog-apps-plugin",ve="api/unstable/app-builder-code/apps",$e="datadog-apps-assets.zip",ke=/\.backend\.(ts|tsx|js|jsx)$/,xe=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],Se=["apiKey","oauth"],Ee=e=>{const t=e[be]||{},n=(e=>{if(void 0!==e){if(Se.includes(e))return e;throw new Error(`apps.authOverrides.method must be one of: ${Se.join(", ")}`)}})(q("APPS_AUTH_METHOD")||t.authOverrides?.method)||((e=>Boolean((q("API_KEY")||e.auth?.apiKey)&&(q("APP_KEY")||e.auth?.appKey)))(e)?"apiKey":"oauth");return{include:t.include||[],dryRun:t.dryRun??!V(q("APPS_UPLOAD_ASSETS"),!1),identifier:t.identifier?.trim(),name:t.name?.trim()||e.metadata?.name?.trim(),...null!=t.description&&{description:t.description},...null!=t.selfService&&{selfService:t.selfService},...null!=t.permissions&&{permissions:t.permissions},authOverrides:{method:n}}},Ie=async e=>r.rm(e,{force:!0,maxRetries:3,recursive:!0}),De=async e=>r.mkdir(e,{recursive:!0}),Ae=(e,t)=>{var n;n=u.dirname(e),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t,{encoding:"utf-8"})},Pe=e=>s.readFileSync(e,{encoding:"utf-8"}),je=e=>{try{return s.existsSync(e)}catch(e){if("ENOENT"===e.code)return!1;throw e}},Me=async(e,t)=>{if("function"==typeof s.openAsBlob){const n=await s.openAsBlob(e,{type:t.contentType});return new o([n],t.filename)}{const n=c.toWeb(s.createReadStream(e)),r=await new Response(n).blob();return new o([r],t.filename,{type:t.contentType})}},Te=async e=>{const t={empty:!1,exists:!0};try{const{size:n}=await r.stat(e);0===n&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t};var Ce=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Ce||{});const Oe=()=>import("oauth4webapi"),Ne=t.cyan.bold,Re=e=>e.toString("base64url"),_e=(e,t)=>{const n=(e=>"datad0g.com"===e?"f4bacdd2-0c8c-49f5-bf3e-a62ba3ec02e6":"e17b9ffa-3daf-4124-ba1b-4ac8c547d506")(e);return{authorizationUrl:`https://${t?`${t}.${e}`:`app.${e}`}/oauth2/v1/authorize`,cacheTokens:!0,clientId:n,openBrowser:!0,redirectUri:"http://localhost:8060",timeoutMs:3e5,tokenUrl:`https://api.${e}/oauth2/v1/token`}},Fe=e=>({client_id:e}),ze=e=>({issuer:new URL(e.authorizationUrl).origin,authorization_endpoint:e.authorizationUrl,token_endpoint:e.tokenUrl}),Le=(e,t)=>`${e}:${t.clientId}:${((e,t)=>p("sha256").update([t.clientId,e,t.authorizationUrl,t.tokenUrl].join("|")).digest("hex").slice(0,16))(e,t)}`,Ue=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=UTF-8"}),e.end(n)},Be=(e,t,n=Date.now())=>({accessToken:e.access_token,expiresAt:"number"==typeof e.expires_in?n+1e3*e.expires_in:void 0,expiresIn:e.expires_in,refreshToken:e.refresh_token,scope:e.scope,site:t,tokenType:e.token_type}),qe=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ve=e=>e instanceof Error?e.message:String(e),He=e=>{const t=Ve(e).toLowerCase();return"NoEntry"===(e=>qe(e)&&"string"==typeof e.code?e.code:void 0)(e)||t.includes("noentry")||t.includes("no matching entry")||t.includes("not found")},Ke=async(e,t)=>{const{AsyncEntry:n}=await import("@napi-rs/keyring");return new n("datadog-build-plugins:oauth",Le(e,t))},We=(e,t)=>new Error(`Could not ${e} Datadog OAuth token in the OS credential store. ${t instanceof Error?t.message:String(t)}`),Je=async(e,t)=>{try{const n=await Ke(e,t),o=await n.getPassword();if(!o)return;const r=JSON.parse(o);return(e=>{if(qe(e)&&1===e.version&&qe(e.token)&&"string"==typeof e.token.accessToken&&"string"==typeof e.token.clientId&&"string"==typeof e.token.site)return e})(r)?.token}catch(e){if(He(e))return;throw We("read",e)}},Ge=async(e,t,n,o=e.site)=>{if(t.cacheTokens)try{await(async(e,t,n)=>{try{const o=await Ke(e,n),r={version:1,token:t};await o.setPassword(JSON.stringify(r))}catch(e){throw We("save",e)}})(o,((e,t)=>({accessToken:e.accessToken,clientId:t,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(e,t.clientId),t),n.debug("Saved Datadog OAuth token to the OS credential store.")}catch(e){n.warn(`Could not save Datadog OAuth token to the OS credential store; continuing without a persistent cache. ${Ve(e)}`)}},Ye=async(e,t,n)=>{if(t.cacheTokens)try{await(async(e,t)=>{try{const n=await Ke(e,t);await n.deletePassword()}catch(e){if(!He(e))throw We("delete",e)}})(e,t)}catch(e){n.warn(`Could not delete cached Datadog OAuth token. ${Ve(e)}`)}},Qe=async(e,t,n)=>{if(!t.cacheTokens)return;let o;try{o=await Je(e,t)}catch(e){n.warn(`Could not read cached Datadog OAuth token; starting browser authorization. ${Ve(e)}`)}if(o){if(void 0===(r=o).expiresAt||r.expiresAt>Date.now()+3e5)return n.debug("Using cached Datadog OAuth access token."),(e=>({accessToken:e.accessToken,expiresAt:e.expiresAt,refreshToken:e.refreshToken,scope:e.scope,site:e.site,tokenType:e.tokenType}))(o);var r;if(o.refreshToken)try{n.debug("Refreshing cached Datadog OAuth access token.");const r=await(async(e,t,n)=>{const o=await Oe(),r=ze(t),i=Fe(t.clientId),s=await o.refreshTokenGrantRequest(r,i,o.None(),n),a=await o.processRefreshTokenResponse(r,i,s);return Be({...a,refresh_token:a.refresh_token||n},e)})(e,t,o.refreshToken);return await Ge(r,t,n),r}catch(o){return n.warn(`Cached Datadog OAuth token could not be refreshed; starting browser authorization. ${o instanceof Error?o.message:String(o)}`),void await Ye(e,t,n)}}},Ze=async(e,t,n)=>{const o=await Oe(),r=ze(t),i=Fe(t.clientId),s=Re(l(32)),a=await(async e=>(await Oe()).calculatePKCECodeChallenge(e))(s),u=Re(l(32)),c=(e=>{const t=new URL(e.authorizationUrl);return t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("client_id",e.clientId),t.searchParams.set("response_type","code"),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("state",e.state),t})({authorizationUrl:t.authorizationUrl,clientId:t.clientId,codeChallenge:a,redirectUri:t.redirectUri,state:u}),p=(async e=>{const t=new URL(e.redirectUri),n=Number(t.port||80);if("http:"!==t.protocol)throw new Error("OAuth redirect URI must use http for the local OAuth callback.");if(!Number.isInteger(n)||n<=0)throw new Error("OAuth redirect URI must include a valid port.");let o,r=!1;const i=m.createServer();try{return await new Promise(((s,a)=>{const u=e=>{r||(r=!0,e())};i.on("request",((n,o)=>{const r=new URL(n.url||"/",t.origin);if(r.pathname!==t.pathname)return void Ue(o,404,"Not found.");let i;try{i=e.oauth.validateAuthResponse(e.authorizationServer,e.client,r,e.state)}catch(e){return Ue(o,400,"OAuth authorization failed. You may now close this tab."),void u((()=>a(e instanceof Error?e:new Error(String(e)))))}if(!i.get("code"))return Ue(o,400,"Missing OAuth authorization code. You may now close this tab."),void u((()=>a(new Error("Missing OAuth authorization code."))));Ue(o,200,"OAuth authorization complete. You may now close this tab."),u((()=>s({callbackParameters:i})))})),i.once("error",(e=>u((()=>a(e))))),o=setTimeout((()=>{u((()=>a(new Error(`Timed out waiting for OAuth callback after ${e.timeoutMs}ms.`))))}),e.timeoutMs);try{const e="localhost"===t.hostname?void 0:t.hostname;i.listen(n,e)}catch(e){u((()=>a(e instanceof Error?e:new Error(String(e)))))}}))}finally{o&&clearTimeout(o),i.listening&&(i.close(),i.closeAllConnections?.(),i.closeIdleConnections?.())}})({authorizationServer:r,client:i,oauth:o,redirectUri:t.redirectUri,state:u,timeoutMs:t.timeoutMs});n.info(`Authorize Datadog Apps upload:\n ${Ne(c.toString())}`),t.openBrowser&&((e,t)=>{const n="darwin"===process.platform?{command:"open",args:[e]}:"win32"===process.platform?{command:"cmd",args:["/c","start","",e]}:{command:"xdg-open",args:[e]};try{const e=d(n.command,n.args,{detached:!0,stdio:"ignore"});e.once("error",(e=>{t.warn(`Could not open browser automatically: ${Ve(e)}`)})),e.unref()}catch(e){t.warn(`Could not open browser automatically: ${Ve(e)}`)}})(c.toString(),n);return(async e=>{const t=await Oe(),n=ze(e),o=Fe(e.clientId),r=await t.authorizationCodeGrantRequest(n,o,t.None(),e.callbackParameters,e.redirectUri,e.codeVerifier),i=await t.processAuthorizationCodeResponse(n,o,r);return Be(i,e.site)})({callbackParameters:(await p).callbackParameters,clientId:t.clientId,codeVerifier:s,redirectUri:t.redirectUri,site:e,tokenUrl:t.tokenUrl,authorizationUrl:t.authorizationUrl})},Xe=new Map,et=async(e,t,n)=>{const o=_e(e,n),r=`${e}:${n??""}:${o.clientId}`;let i=Xe.get(r);return i||(i=(async(e,t,n)=>{const o=await Qe(e,t,n);return o?{persistAfterSuccessfulRequest:!1,token:o}:{persistAfterSuccessfulRequest:!0,token:await Ze(e,t,n)}})(e,o,t).catch((e=>{throw Xe.delete(r),e})),Xe.set(r,i)),i},tt='Set apps.authOverrides.method: "oauth" or DD_APPS_AUTH_METHOD=oauth to use OAuth, or set DD_API_KEY and DD_APP_KEY to use API/App key auth.';class nt extends Error{constructor(){super(`Missing authentication. ${tt}`),this.statusCode=400,this.name="MissingAuthenticationError"}}const ot=(e,t,n)=>{if("oauth"===e)return e=>(async({auth:e,log:t,...n})=>{const{site:o,siteSubdomain:r}=e,{persistAfterSuccessfulRequest:i,token:s}=await et(o,t,r);if(!s.accessToken)throw new Error("OAuth authentication did not return an access token.");const a=await Q({...n,auth:{accessToken:s.accessToken}});return i&&await Ge(s,_e(o,r),t,o),a})({...e,auth:t,log:n});if(t.apiKey&&t.appKey)return e=>Q({...e,auth:{apiKey:t.apiKey,appKey:t.appKey}});throw new nt};function rt(e,t){if(!function(e){return"Program"===e.type}(e))throw new Error(`Expected a Program node from this.parse() for ${t}, got ${e.type}`);return e}function it(e){return"object"==typeof e&&null!==e&&"Literal"===e.type&&"string"==typeof e.value}function st(e){return"type"===e.importKind||"type"===e.exportKind}function at(e,t){return function(e,t){const n=rt(e,t),o=function(e){const t=new Map;for(const n of e.body)if("FunctionDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"function"});else if("ClassDeclaration"===n.type&&n.id)t.set(n.id.name,{kind:"class"});else if("VariableDeclaration"===n.type)for(const e of n.declarations)"Identifier"===e.id.type&&t.set(e.id.name,{kind:"variable",init:e.init});else if("ImportDeclaration"===n.type)for(const e of n.specifiers)t.set(e.local.name,{kind:"import"});return t}(n),r=[];for(const e of n.body){if("ExportDefaultDeclaration"===e.type)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);if("ExportAllDeclaration"===e.type)throw new Error(`"export *" is not supported in .backend.ts files. Use explicit named exports instead: ${t}`);if("ExportNamedDeclaration"!==e.type)continue;e.declaration&&r.push(...dt(e.declaration,t).map((e=>({kind:"local",name:e,localName:e}))));const n="string"==typeof e.source?.value?e.source.value:null;for(const i of e.specifiers){if("Identifier"!==i.exported.type)continue;if("default"===i.exported.name)throw new Error(`Default exports are not supported in .backend.ts files. Use a named export instead: ${t}`);const e="Identifier"===i.local.type?i.local.name:"string"==typeof i.local.value?i.local.value:null;e&&(n?r.push({kind:"re-export",name:i.exported.name,localName:e,source:n}):("Identifier"===i.local.type&<(e,o,t),r.push({kind:"local",name:i.exported.name,localName:e})))}}return r}(e,t).map((e=>e.name))}const ut=new Set(["ArrayExpression","Literal","ObjectExpression","TemplateLiteral"]);function ct(e){return null==e||ut.has(e.type)}function dt(e,t){if("FunctionDeclaration"===e.type&&e.id)return[e.id.name];if("ClassDeclaration"===e.type)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${t}`);if("VariableDeclaration"===e.type)return e.declarations.flatMap((e=>{if("Identifier"!==e.id.type)throw new Error(`Destructured exports are not supported in backend files. Use individual named exports instead: ${t}`);if(ct(e.init))throw new Error(`Non-function export "${e.id.name}" in backend file ${t}. Only function exports are supported — use "export function ${e.id.name}(…) { }" instead.`);return[e.id.name]}));throw new Error(`Unsupported export declaration type "${e.type}" in backend file ${t}. Only function and variable exports are allowed.`)}function lt(e,t,n){const o=t.get(e);if(o){if("class"===o.kind)throw new Error(`Class exports are not supported in .backend.ts files. Only function exports are allowed: ${n}`);if("variable"===o.kind&&ct(o.init))throw new Error(`Non-function export "${e}" in backend file ${n}. Only function exports are supported — use "export function ${e}(…) { }" instead.`)}}function pt(e){const t=e.relativePath.split(u.sep).join("/");return`${p("sha256").update(t).digest("hex")}.${e.name}`}function ft(e){const t=[];for(const{exportName:n,queryName:o}of e)t.push(`export async function ${n}(...args) {`),t.push(` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(o)}, args);`),t.push("}"),t.push("");return t.join("\n")}function mt(e,t){try{return C.resolve(e,{paths:[t]}),!0}catch{return!1}}function ht(e,t,n){const o=[],r=mt("@datadog/apps-backend/runtime/jsFunctionWithActions",n);return o.push(`import { ${e} } from ${JSON.stringify(t)};`),r&&o.push("import { buildRuntimeFromJsFunctionWithActions } from '@datadog/apps-backend/runtime/jsFunctionWithActions';\nimport { setBackend } from '@datadog/apps-backend/runtime';"),function(e){return mt("@datadog/action-catalog/action-execution",e)}(n)&&o.push("import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';"),o.push(""),o.push('/** @param {import("./context.types").Context} $ */'),o.push("export async function main($) {"),o.push(" globalThis.$ = $;"),o.push(""),r&&(o.push(" // Supply the backend runtime context"),o.push(" if (typeof buildRuntimeFromJsFunctionWithActions === 'function' && typeof setBackend === 'function') {\n setBackend(buildRuntimeFromJsFunctionWithActions($));\n }"),o.push("")),o.push(" // Register the $.Actions-based implementation for executeAction"),o.push(" if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\.datadoghq\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }"),o.push(""),o.push(" const args = $.backendFunctionArgs ?? [];"),o.push(` const result = await ${e}(...args);`),o.push(" return result;"),o.push("}"),o.join("\n")}function gt(e,t,n){const o={state:t},r=e=>{n._?.(e,o),function(e,t){return t[e.type]}(e,n)?.(e,o);for(const t of Object.keys(e))"type"!==t&&i(e[t])},i=e=>{if(Array.isArray(e))for(const t of e)yt(t)&&r(t);else yt(e)&&r(e)};r(e)}function yt(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function bt(e){gt(e,null,{_(e){const t=e;t.range||"number"!=typeof t.start||"number"!=typeof t.end||(t.range=[t.start,t.end])}});const t=y.analyze(e,{ecmaVersion:2022,ignoreEval:!0,sourceType:"module"}),n=new Map;for(const e of t.scopes)for(const t of e.references)n.set(t.identifier,t);return{scopeManager:t,referencesByIdentifier:n,moduleScope:kt(t)}}function wt(e,t){return t.referencesByIdentifier.get(e)?.resolved??void 0}function vt(e){return e.defs.some((e=>"ImportBinding"===e.type))}function $t(e,t){return t.moduleScope.set.get(e)}function kt(e){return e.scopes.find((e=>"module"===e.type))??e.globalScope}function xt(e,t,n){const o={scopeAnalysis:t,unsupportedAliases:St(e,t)},r=[];return gt(e,o,{CallExpression(e,{state:t}){(function(e,t,n){const o=e.callee;if("Identifier"===o.type){if(At(o,t.unsupportedAliases,t.scopeAnalysis))throw Tt(n,"action-catalog call aliases");if(At(o,t.scopeAnalysis.actionFunctions,t.scopeAnalysis)){if(e.optional)throw Tt(n,"optional action-catalog calls");return!0}return!1}if("MemberExpression"!==o.type)return!1;if(!Et(o,t.scopeAnalysis))return!1;if(e.optional||Dt(o))throw Tt(n,"optional or computed action-catalog namespace calls");return!0})(e,t,n)&&r.push(e)}}),r}function St(e,t){const n=new Set;return gt(e,t,{VariableDeclarator(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.id.type&&"Identifier"===e.init?.type&&At(e.init,t.actionFunctions,t))return jt(e,t,[e.id.name]);if("Identifier"===e.id.type&&"MemberExpression"===e.init?.type&&Et(e.init,t))return jt(e,t,[e.id.name]);if("ObjectPattern"!==e.id.type||"Identifier"!==e.init?.type||!At(e.init,t.actionNamespaces,t))return[];const n=e.id.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Mt(e.value))).map((e=>e.name));return jt(e,t,n)}(e,t))n.add(o)},AssignmentExpression(e,{state:t}){for(const o of function(e,t){if("Identifier"===e.left.type&&"Identifier"===e.right.type&&At(e.right,t.actionFunctions,t))return Pt([e.left],t);if("Identifier"===e.left.type&&"MemberExpression"===e.right.type&&Et(e.right,t))return Pt([e.left],t);if("ObjectPattern"!==e.left.type||"Identifier"!==e.right.type||!At(e.right,t.actionNamespaces,t))return[];const n=e.left.properties.flatMap((e=>"RestElement"===e.type||e.computed?[]:Mt(e.value)));return Pt(n,t)}(e,t))n.add(o)}}),n}function Et(e,t){const n=It(e);return!!n&&At(n,t.actionNamespaces,t)}function It(e){return"Identifier"===e.object.type?e.object:"MemberExpression"===e.object.type?It(e.object):void 0}function Dt(e){return!(!e.optional&&!e.computed)||"MemberExpression"===e.object.type&&Dt(e.object)}function At(e,t,n){return function(e,t,n){const o=wt(e,n);return!!o&&t.has(o)}(e,t,n.moduleScope)}function Pt(e,t){return e.flatMap((e=>{const n=wt(e,t.moduleScope);return n?[n]:[]}))}function jt(e,t,n){const o=new Set(n);return t.moduleScope.scopeManager.getDeclaredVariables(e).filter((e=>o.has(e.name)))}function Mt(e){switch(e.type){case"Identifier":return[e];case"ObjectPattern":return e.properties.flatMap((e=>"RestElement"===e.type?Mt(e.argument):Mt(e.value)));case"ArrayPattern":return e.elements.flatMap((e=>e?Mt(e):[]));case"RestElement":return Mt(e.argument);case"AssignmentPattern":return Mt(e.left);case"MemberExpression":return[]}}function Tt(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Ct="@datadog/action-catalog";function Ot(e,t,n){const o=e.get(t);if(!o)return Ut(t,[],n.name);const r=wt(n,o.scopeAnalysis);return r?function(e,t){return t.defs.some((t=>t.name===e))}(n,r)?Bt(t,[],n.name):_t({modules:e,visitedExports:new Set},t,r,[]):Bt(t,[],n.name)}function Nt(e,t,n,o){const r=e.modules.get(t);if(!r)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"export",exportName:n,message:`Module '${e}' was not collected while resolving export '${n}'.`,hops:t}}(t,o,n);if("default"===n)return zt(t,o,n);const i=`${t}\0${n}`;if(e.visitedExports.has(i))return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"cycle",exportName:n,message:`Resolving export '${n}' from module '${e}' would cycle through the module graph.`,hops:t}}(t,o,n);e.visitedExports.add(i);try{const t=r.exportsByName.get(n);return t?function(e,t,n,o,r){if("unsupported"===o.kind)return function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-export",exportName:n,exportReason:o,message:`Export '${n}' from module '${e}' is unsupported: ${o}.`,hops:t}}(t.id,r,n,o.reason);if("re-export"===o.kind)return"default"===o.importedName?zt(t.id,r,n):Nt(e,o.resolvedId,o.importedName,[...r,{kind:"re-export",moduleId:t.id,exportName:n,sourceModuleId:o.resolvedId,sourceExportName:o.importedName}]);return _t(e,t.id,o.variable,[...r,{kind:"local-export",moduleId:t.id,exportName:n,localName:o.variable.name}])}(e,r,n,t,o):function(e,t,n,o){let r;for(const i of t.starExports){const s=Nt(e,i.resolvedId,n,[...o,{kind:"star-export",moduleId:t.id,exportName:n,sourceModuleId:i.resolvedId}]);if("unsupported"===s.kind){if("missing-export"===s.reason)continue;return s}if(!r||!Rt(r,s)){if(r)return Ft(t.id,o,n);r=s}}return r??function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-export",exportName:n,message:`Module '${e}' does not expose export '${n}'.`,hops:t}}(t.id,o,n)}(e,r,n,o)}finally{e.visitedExports.delete(i)}}function Rt(e,t){return e.moduleId===t.moduleId&&e.variable===t.variable}function _t(e,t,n,o){const r=e.modules.get(t);if(!r)return Ut(t,o,n.name);const i=r.importsByVariable.get(n);if(i)return function(e,t,n,o,r){if("default"===o.kind)return Lt(t,r,n);if("namespace"===o.kind)return function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"namespace-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported namespace import.`,hops:t}}(t,r,n);if("default"===o.importedName)return Lt(t,r,n);return Nt(e,o.resolvedId,o.importedName,[...r,{kind:"import",moduleId:t,localName:n,exportName:o.importedName,sourceModuleId:o.resolvedId}])}(e,r.id,n.name,i,o);const s=r.topLevelBindingsByVariable.get(n);return s?"const"===s.kind?{kind:"local",moduleId:r.id,variable:n,binding:s,hops:o}:"mutable"===s.kind?function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"mutable-binding",variableName:n,declarationKind:o,message:`Variable '${n}' in module '${e}' is declared with mutable '${o}'.`,hops:t}}(r.id,o,n.name,s.declarationKind):function(e,t,n,o){return{kind:"unsupported",moduleId:e,reason:"unsupported-binding",variableName:n,bindingReason:o,message:`Variable '${n}' in module '${e}' has unsupported binding: ${o}.`,hops:t}}(r.id,o,n.name,s.reason):function(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-static-binding",variableName:n,message:`Variable '${n}' in module '${e}' does not have a recorded top-level static binding.`,hops:t}}(r.id,o,n.name)}function Ft(e,t,n){return{kind:"unsupported",moduleId:e,reason:"ambiguous-star-export",exportName:n,message:`Module '${e}' exposes ambiguous star exports for '${n}'.`,hops:t}}function zt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-export",exportName:n,message:`Export '${n}' from module '${e}' resolves through an unsupported default export.`,hops:t}}function Lt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"default-import",variableName:n,message:`Variable '${n}' in module '${e}' is an unsupported default import.`,hops:t}}function Ut(e,t,n){return{kind:"unsupported",moduleId:e,reason:"missing-module-record",requestKind:"variable",variableName:n,message:`Module '${e}' was not collected while resolving variable '${n}'.`,hops:t}}function Bt(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unresolved-identifier",variableName:n,message:`Identifier '${n}' in module '${e}' is not a resolvable reference.`,hops:t}}function qt(e,t,n){const o=en(n);switch(o.type){case"Literal":return function(e,t){if("string"==typeof t.value)return{kind:"resolved",moduleId:e,value:t.value};return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-string-literal",valueType:t,message:`Literal value type '${t}' in module '${e}' is not a string.`}}(e,typeof t.value)}(t,o);case"TemplateLiteral":return function(e,t){if(t.expressions.length>0)return function(e){return{kind:"unsupported",moduleId:e,reason:"dynamic-template-literal",message:`Dynamic template literals in module '${e}' cannot be resolved to static strings.`}}(e);return{kind:"resolved",moduleId:e,value:t.quasis.map((e=>e.value.cooked??e.value.raw)).join("")}}(t,o);case"Identifier":return function(e,t,n){const o=Ot(e.modules,t,n);if("unsupported"===o.kind)return dn(o,n.name);if(!o.binding.expression)return ln(o.moduleId,o.variable.name);if(e.seenVariables.has(o.variable))return rn(o.moduleId,o.variable.name);e.seenVariables.add(o.variable);try{return qt(e,o.moduleId,o.binding.expression)}finally{e.seenVariables.delete(o.variable)}}(e,t,o);case"MemberExpression":return function(e,t,n){const o=Vt(e,t,n);if("unsupported"===o.kind)return o;return qt(e,o.moduleId,o.expression)}(e,t,o);default:return function(e,t){return{kind:"unsupported",moduleId:e,reason:"unsupported-expression",expressionType:t,message:`Expression type '${t}' in module '${e}' cannot be resolved to a static string.`}}(t,o.type)}}function Vt(e,t,n){if(n.optional)return function(e){return{kind:"unsupported",moduleId:e,reason:"optional-member-expression",message:`Optional member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if(n.computed)return function(e){return{kind:"unsupported",moduleId:e,reason:"computed-member-expression",message:`Computed member expressions in module '${e}' cannot be resolved to static strings.`}}(t);if("Identifier"!==n.property.type)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"non-static-member-property",propertyType:t,message:`Member property type '${t}' in module '${e}' is not statically named.`}}(t,n.property.type);const o=Ht(e,t,n.object);return"unsupported"===o.kind?o:function(e,t,n){let o;for(const r of t.properties){if("SpreadElement"===r.type)return cn(e);if(r.computed)return on(e);if(Xt(r)===n){if(o)return sn(e,n);if("init"!==r.kind)return nn(e,n);if(!Kt(r))return un(e,n,r.value.type);o=r}}if(!o)return function(e,t){return{kind:"unsupported",moduleId:e,reason:"missing-object-property",propertyName:t,message:`Static object in module '${e}' does not have property '${t}'.`}}(e,n);return{kind:"resolved",moduleId:e,expression:o.value}}(o.moduleId,o.expression,n.property.name)}function Ht(e,t,n){if("Super"===n.type)return an(t,n.type);const o=en(n);if("ObjectExpression"===o.type)return{kind:"resolved",moduleId:t,expression:o};if("MemberExpression"===o.type){const n=Vt(e,t,o);return"unsupported"===n.kind?n:Ht(e,n.moduleId,n.expression)}if("Identifier"!==o.type)return an(t,o.type);const r=Ot(e.modules,t,o);if("unsupported"===r.kind)return dn(r,o.name);if(!r.binding.expression)return ln(r.moduleId,r.variable.name);if(e.mutatedImportedObjectVariables.has(r.variable))return function(e,t){return{kind:"unsupported",moduleId:e,reason:"imported-object-mutation",variableName:t,message:`Imported object '${t}' from module '${e}' is mutated in the module graph.`}}(r.moduleId,r.variable.name);if(e.seenVariables.has(r.variable))return rn(r.moduleId,r.variable.name);e.seenVariables.add(r.variable);try{return Ht(e,r.moduleId,r.binding.expression)}finally{e.seenVariables.delete(r.variable)}}function Kt(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function Wt(e){const t=new Set;for(const n of e.values())gt(n.ast,{modules:e,mutatedVariables:t,record:n},{AssignmentExpression(e,{state:t}){Gt(e.left,t)},UpdateExpression(e,{state:t}){Gt(e.argument,t)},UnaryExpression(e,{state:t}){"delete"===e.operator&&Gt(e.argument,t)},ForInStatement(e,{state:t}){Jt(e.left,t)},ForOfStatement(e,{state:t}){Jt(e.left,t)}});return t}function Jt(e,t){"VariableDeclaration"!==e.type&&Gt(e,t)}function Gt(e,t){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&Gt(e.left,t):Gt(e.argument,t);else for(const n of e.elements)n&&Gt(n,t);else for(const n of e.properties)Gt("RestElement"===n.type?n.argument:n.value,t);else{const n=Zt(e);n&&Yt(n,t)}else Yt(e,t)}function Yt(e,t){const n=Qt(t,e,new Set);n&&t.mutatedVariables.add(n)}function Qt(e,t,n){const o=wt(t,e.record.scopeAnalysis);if(!o||n.has(o))return;if(n.add(o),vt(o)){const n=Ot(e.modules,e.record.id,t);return"local"===n.kind?n.variable:void 0}const r=function(e){for(const t of e.defs){const e=t.node;if("VariableDeclarator"===e.type&&e.init)return e.init}return}(o);if(!r)return;const i=function(e){const t=en(e);if("Identifier"===t.type)return t;if("MemberExpression"===t.type)return Zt(t);return}(r);return i?Qt(e,i,n):void 0}function Zt(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?Zt(e.object):void 0}function Xt(e){return"Identifier"===e.key.type?e.key.name:"Literal"===e.key.type&&"string"==typeof e.key.value?e.key.value:void 0}function en(e){let t=e;for(;tn(t);)t=t.expression;return t}function tn(e){const t=e.type;return("TSAsExpression"===t||"TSSatisfiesExpression"===t||"TSNonNullExpression"===t||"TSTypeAssertion"===t)&&!!e.expression}function nn(e,t){return{kind:"unsupported",moduleId:e,reason:"accessor-object-property",propertyName:t,message:`Static object property '${t}' in module '${e}' is an accessor.`}}function on(e){return{kind:"unsupported",moduleId:e,reason:"computed-object-property",message:`Computed object properties in module '${e}' cannot be resolved to static strings.`}}function rn(e,t){return{kind:"unsupported",moduleId:e,reason:"cycle",variableName:t,message:`Resolving variable '${t}' in module '${e}' would cycle through static string values.`}}function sn(e,t){return{kind:"unsupported",moduleId:e,reason:"duplicate-object-property",propertyName:t,message:`Static object in module '${e}' has duplicate property '${t}'.`}}function an(e,t){return{kind:"unsupported",moduleId:e,reason:"non-object-member-value",expressionType:t,message:`Expression type '${t}' in module '${e}' is not a static object value.`}}function un(e,t,n){return{kind:"unsupported",moduleId:e,reason:"unsupported-object-property-value",propertyName:t,valueType:n,message:`Static object property '${t}' in module '${e}' has unsupported value type '${n}'.`}}function cn(e){return{kind:"unsupported",moduleId:e,reason:"object-spread",message:`Object spreads in module '${e}' cannot be resolved to static strings.`}}function dn(e,t){return{kind:"unsupported",moduleId:e.moduleId,reason:"static-definition-unsupported",variableName:t,definition:e,message:`Variable '${t}' could not be resolved to a static definition: ${e.message}`}}function ln(e,t){return{kind:"unsupported",moduleId:e,reason:"uninitialized-const",variableName:t,message:`Const variable '${t}' in module '${e}' does not have an initializer.`}}const pn=new Set(["node_modules",".yarn"]);function fn(e,t,n,o=[]){if(!Mn(e,t))return null;const r=rt(n,e),i=bt(r),s=function(e,t){const n=function(e){return e.body.flatMap((e=>("ImportDeclaration"===e.type||"ExportNamedDeclaration"===e.type||"ExportAllDeclaration"===e.type)&&e.source&&it(e.source)?[e.source.value]:[]))}(e);return t.map(((e,t)=>({source:n[t]??e,resolvedId:e})))}(r,o);return{id:e,ast:r,scopeAnalysis:i,staticDependencies:s,unsupportedDependencies:Pn(r),importsByVariable:mn(r,i,s),exportsByName:hn(r,i,s),starExports:bn(r,s),topLevelBindingsByVariable:wn(r,i)}}function mn(e,t,n){const o=new Map;for(const r of e.body){if("ImportDeclaration"!==r.type||!it(r.source))continue;const e=An(n,r.source.value);for(const n of r.specifiers){const[r]=t.scopeManager.getDeclaredVariables(n);r&&("ImportSpecifier"!==n.type?o.set(r,{kind:"ImportDefaultSpecifier"===n.type?"default":"namespace",resolvedId:e}):o.set(r,{kind:"named",importedName:In(n.imported),resolvedId:e}))}}return o}function hn(e,t,n){const o=new Map;for(const r of e.body)"ExportNamedDeclaration"!==r.type?"ExportDefaultDeclaration"!==r.type?"ExportAllDeclaration"===r.type&&yn(r,n,o):o.set("default",{kind:"unsupported",reason:"default export"}):gn(r,t,n,o);return o}function gn(e,t,n,o){if(e.declaration)!function(e,t,n){if(!e)return;if("VariableDeclaration"===e.type){for(const o of e.declarations){const e=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const t of e)n.set(t.name,{kind:"unsupported",reason:"binding pattern export"});continue}const[r]=e;r&&n.set(o.id.name,{kind:"local",variable:r})}return}if(("FunctionDeclaration"===e.type||"ClassDeclaration"===e.type)&&e.id){const[o]=t.scopeManager.getDeclaredVariables(e);o&&n.set(e.id.name,{kind:"local",variable:o})}}(e.declaration,t,o);else if(e.source&&it(e.source)){const t=An(n,e.source.value);for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=In(n.exported);"default"!==e?o.set(e,{kind:"re-export",importedName:In(n.local),resolvedId:t}):o.set(e,{kind:"unsupported",reason:"default re-export",resolvedId:t})}}else for(const n of e.specifiers){if("ExportSpecifier"!==n.type)continue;const e=In(n.exported);if("default"===e){o.set(e,{kind:"unsupported",reason:"default export"});continue}const r=$t(In(n.local),t);o.set(e,r?{kind:"local",variable:r}:{kind:"unsupported",reason:"unresolved local export"})}}function yn(e,t,n){const o=Dn(e);o&&it(e.source)&&n.set(o,{kind:"unsupported",reason:"namespace re-export",resolvedId:An(t,e.source.value)})}function bn(e,t){return e.body.flatMap((e=>"ExportAllDeclaration"!==e.type||Dn(e)||!it(e.source)?[]:[{resolvedId:An(t,e.source.value)}]))}function wn(e,t){const n=new Map;for(const o of e.body)vn(o,t,n);return function(e,t,n){gt(e,{scopeAnalysis:t,bindings:n},{AssignmentExpression(e,{state:t}){xn(e.left,t.scopeAnalysis,t.bindings)},UpdateExpression(e,{state:t}){xn(e.argument,t.scopeAnalysis,t.bindings)},UnaryExpression(e,{state:t}){"delete"===e.operator&&xn(e.argument,t.scopeAnalysis,t.bindings)},ForInStatement(e,{state:t}){kn(e.left,t.scopeAnalysis,t.bindings)},ForOfStatement(e,{state:t}){kn(e.left,t.scopeAnalysis,t.bindings)}})}(e,t,n),n}function vn(e,t,n){if("VariableDeclaration"===e.type)return void $n(e,t,n);if("ExportNamedDeclaration"===e.type&&"VariableDeclaration"===e.declaration?.type)return void $n(e.declaration,t,n);const o="ExportNamedDeclaration"===e.type||"ExportDefaultDeclaration"===e.type?e.declaration:e;if(o&&("FunctionDeclaration"===o.type||"ClassDeclaration"===o.type)&&o.id){const[e]=t.scopeManager.getDeclaredVariables(o);e&&n.set(e,{kind:"unsupported",reason:`${o.type} binding`})}}function $n(e,t,n){for(const o of e.declarations){const r=t.scopeManager.getDeclaredVariables(o);if("Identifier"!==o.id.type){for(const e of r)n.set(e,{kind:"unsupported",reason:"binding pattern"});continue}const[i]=r;i&&("const"===e.kind?n.set(i,{kind:"const",expression:o.init??null}):n.set(i,{kind:"mutable",declarationKind:e.kind}))}}function kn(e,t,n){"VariableDeclaration"!==e.type&&xn(e,t,n)}function xn(e,t,n){if("Identifier"!==e.type)if("MemberExpression"!==e.type)if("ObjectPattern"!==e.type)if("ArrayPattern"!==e.type)"RestElement"!==e.type?"AssignmentPattern"===e.type&&xn(e.left,t,n):xn(e.argument,t,n);else for(const o of e.elements)o&&xn(o,t,n);else for(const o of e.properties)xn("RestElement"===o.type?o.argument:o.value,t,n);else{const o=En(e);o&&Sn(o,t,n,"mutated object binding")}else Sn(e,t,n,"reassigned binding")}function Sn(e,t,n,o){const r=wt(e,t);if(!r||vt(r)||!n.has(r))return;const i=n.get(r);"mutable"!==i?.kind&&n.set(r,{kind:"unsupported",reason:o})}function En(e){return"Identifier"===e.type?e:"MemberExpression"===e.type?En(e.object):void 0}function In(e){return"Identifier"===e.type?e.name:String(e.value)}function Dn(e){const t=e.exported;return t?In(t):void 0}function An(e,t){return e.find((e=>e.source===t))?.resolvedId??t}function Pn(e){const t=[];return gt(e,t,{ImportExpression(e,{state:t}){const n=function(e){return Cn(e.source,"non-literal dynamic import")}(e);jn(n)&&t.push({specifier:n,kind:"dynamic-import"})},CallExpression(e,{state:t}){if(function(e){return"Import"===e.callee.type}(e)){const n=function(e){return Cn(e.arguments[0],"non-literal dynamic import")}(e);jn(n)&&t.push({specifier:n,kind:"dynamic-import"})}else(function(e){if("Identifier"!==e.callee.type||"require"!==e.callee.name)return!1;const[t]=e.arguments;return!t||!it(t)||On(t.value)})(e)&&t.push({specifier:Tn(e),kind:"require"})}}),t}function jn(e){return"non-literal dynamic import"===e||On(e)}function Mn(e,t){if(!xe.some((t=>e.endsWith(t))))return!1;const n=u.relative(u.resolve(t),e);return!n.startsWith("..")&&!u.isAbsolute(n)&&!n.split(u.sep).some((e=>pn.has(e)))}function Tn(e){return Cn(e.arguments[0],"local require")}function Cn(e,t){return it(e)?e.value:t}function On(e){return e.startsWith(".")||e.startsWith("/")}function Nn(e,t){return new Error(`Unsupported local module graph for ${e}: ${t} could hide an action-catalog connectionId.`)}function Rn(e,t,n){const o=new Set;return function(e,t,n,o){const r=[e],i=new Set;for(;r.length>0;){const s=r.shift();if(i.has(s))continue;i.add(s);const a=t.get(s);if(!a)throw Nn(e,`missing module record for ${s}`);o({entryId:e,moduleId:s,record:a});for(const t of a.unsupportedDependencies)throw Nn(e,`${t.kind} ${t.specifier}`);for(const o of a.staticDependencies){const i=o.resolvedId;if(Mn(i,n)){if(!t.has(i))throw Nn(e,`uncollected local import ${i} from ${a.id}`);r.push(i)}}}}(e,t,n,(({record:e})=>{const n=function(e){const t=new Set,n=new Set;for(const r of e.body)if("ImportDeclaration"===r.type&&"string"==typeof(o=r.source.value)&&(o===Ct||o.startsWith(`${Ct}/`))&&!st(r))for(const e of r.specifiers)st(e)||("ImportNamespaceSpecifier"===e.type?n.add(e.local.name):t.add(e.local.name));var o;return{functions:t,namespaces:n}}(e.ast),r=function(e,t){const n=new Set,o=new Set;for(const r of e.scopeManager.scopes)for(const e of r.variables)vt(e)&&(t.functions.has(e.name)&&n.add(e),t.namespaces.has(e.name)&&o.add(e));return{moduleScope:e,actionFunctions:n,actionNamespaces:o}}(e.scopeAnalysis,n);for(const n of xt(e.ast,r,e.id)){const r=_n(n,t,e);r&&o.add(r)}})),[...o].sort()}function _n(e,t,n){const[o]=e.arguments;if(!o||"ObjectExpression"!==o.type)throw Ln(n.id,"non-object action-catalog call arguments");const r=function(e,t){let n;for(const o of e.properties){if("SpreadElement"===o.type)throw Ln(t,"spread object arguments");if(o.computed)throw Ln(t,"computed object property keys");if(zn(o)){if(n)throw Ln(t,"multiple connectionId properties");if("init"!==o.kind)throw Ln(t,"accessor connectionId properties");if(!Fn(o))throw Ln(t,"destructuring pattern in connectionId value");n=o}}return n}(o,n.id);if(!r)return;const i=function(e,t,n){return qt({modules:e,mutatedImportedObjectVariables:Wt(e),seenVariables:new Set},t,n)}(t,n.id,r.value);if("resolved"===i.kind)return i.value;throw s=n.id,a=`static string resolution ${function(e){return"static-definition-unsupported"===e.reason?`${e.reason}/${e.definition.reason}`:e.reason}(i)}: ${i.message}`,new Error(`Unsupported action-catalog connectionId in ${s}: ${a}.`);var s,a}function Fn(e){const{value:t}=e;return"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&"RestElement"!==t.type&&"AssignmentPattern"!==t.type}function zn(e){return"connectionId"===function(e){if("Identifier"===e.key.type)return e.key.name;if("Literal"===e.key.type&&"string"==typeof e.key.value)return e.key.value;return}(e)}function Ln(e,t){return new Error(`Unsupported action-catalog call in ${e}: ${t} could hide a connectionId.`)}const Un=/^(?:\0|virtual:)/;function Bn(e){const t=new Map;return{plugin:{name:"dd-backend-module-graph-collector",moduleParsed(n){const o=qn(n.id);if(r=o,Un.test(r))return;var r;const i=fn(o,e,n.ast,function(e){return e.importedIdResolutions?.map((({id:e})=>e))??[...e.importedIds]}(n).map(qn));i&&t.set(i.id,i)}},getModuleRecords:()=>t}}function qn(e){return e.split("?")[0]}function Vn(e,t){const n=Bn(t);return{plugin:n.plugin,getAllowedConnectionIds:()=>Rn(e,n.getModuleRecords(),t)}}function Hn(e,t){return{name:e,enforce:"pre",resolveId:e=>t[e]?{id:e,moduleSideEffects:!0}:null,load:e=>t[e]?t[e]:null}}function Kn(e,t,n=[]){return{configFile:!1,root:e,logLevel:"silent",build:{minify:!1,target:"esnext",rollupOptions:{output:{format:"es",exports:"named",inlineDynamicImports:!0},preserveEntrySignatures:"exports-only",treeshake:!1,onwarn(e,t){"MODULE_LEVEL_DIRECTIVE"!==e.code&&t(e)}}},resolve:{extensions:[...xe,".json"]},plugins:[Hn("dd-backend-resolve",t),...n]}}function Wn(e){return`${e.relativePath}/${e.name}`}async function Jn(e,t,n,o){const r=Wn(t),i=`virtual:dd-backend-dev:${r}`,s=function(e,t,n){return ht(e,t,n??process.cwd())}(t.name,t.absolutePath,n),a=Vn(t.absolutePath,n);o.debug(`Bundling backend function "${r}" from ${t.absolutePath}`);const u=Kn(n,{[i]:s},[a.plugin]),c=await e({...u,build:{...u.build,write:!1,rollupOptions:{...u.build.rollupOptions,input:i,output:u.build.rollupOptions.output}}}),d=Array.isArray(c)?c[0]:c;if(!("output"in d))throw new Error(`Unexpected vite.build result for "${r}"`);const l="chunk"===d.output[0].type?d.output[0].code:"",p={...t,allowedConnectionIds:a.getAllowedConnectionIds()};return o.debug(`Bundled "${r}" (${l.length} bytes)`),{func:p,code:l}}async function Gn(e,t,n,o,r,i){const s=`https://api.${o.site}/api/v2/app-builder/queries/preview-async`,a=Wn(t);i.debug(`Calling Datadog API: ${s}`);const u=JSON.stringify({data:{type:"queries",attributes:{query:{id:f(),name:a,type:"action",properties:{spec:{fqn:"com.datadoghq.datatransformation.jsFunctionWithActions",inputs:{script:e,allowedConnectionIds:t.allowedConnectionIds,context:{backendFunctionArgs:n}}},onlyTriggerManually:!0}},template_params:{}}}}),c=await r({url:s,method:"POST",type:"json",getData:()=>({data:u,headers:{"Content-Type":"application/json"}})}),d=c.data?.id;if(!d)throw new Error("No receipt ID returned from Datadog API");return i.debug(`Query execution started with receipt: ${d}`),async function(e,t,n,o){const r=`https://api.${t.site}/api/v2/app-builder/queries/execution-long-polling/${e}`,i=10;for(let e=0;e<i;e++){o.debug(`Long-poll attempt ${e+1}/${i}...`);const t=await n({url:r,type:"json"});if(t.errors?.length){const e=t.errors.map((e=>e.detail||e.title)).join("; ");throw new Error(`Query execution failed: ${e}`)}const s=t.data?.attributes;if(o.debug(`Long-poll response, done: ${s?.done}`),s?.done){if(!s.outputs)throw new Error("Query execution completed without outputs");return s.outputs}}throw new Error("Query execution timed out")}(d,o,r,i)}function Yn(e,t,n){e.statusCode=t,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify({success:!1,error:n}))}class Qn extends Error{constructor(e,t){super(t),this.statusCode=e}}async function Zn(e,t,n){const{functionName:o,args:r=[]}=await function(e){return new Promise(((t,n)=>{let o="";e.on("data",(e=>{o+=e.toString()})),e.on("end",(()=>{try{t(JSON.parse(o))}catch{n(new Error("Invalid JSON body"))}})),e.on("error",n)}))}(e);if(!o||"string"!=typeof o)throw new Qn(400,"Missing or invalid functionName");const i=t.get(o);if(!i)throw new Qn(404,`Backend function "${o}" not found`);return{...await n(i),args:r}}function Xn(e,t,n,o,r,i){const s=t=>Jn(e,t,r,i),a=t();return a.length>0&&i.info(`Dev server middleware active for ${a.length} backend function(s): ${a.map((e=>e.name)).join(", ")}`),o||i.warn(`Auth credentials not configured. The /__dd/executeAction endpoint will be unavailable. ${tt}`),(e,r,a)=>{if("POST"!==e.method)return void a();const u=(c=t(),new Map(c.map((e=>[pt(e),e]))));var c;if("/__dd/debugBundle"===e.url)(async function(e,t,n,o){try{const{code:r}=await Zn(e,n,o);t.statusCode=200,t.setHeader("Content-Type","text/plain"),t.end(r)}catch(e){Yn(t,e instanceof Qn?e.statusCode:500,e instanceof Error?e.message:"Internal server error")}})(e,r,u,s).catch((()=>{Yn(r,500,"Unexpected error")}));else if("/__dd/executeAction"===e.url){if(!o)return void Yn(r,400,`Auth credentials not configured. ${tt}`);(async function(e,t,n,o,r,i,s){try{const{func:a,code:u,args:c}=await Zn(e,n,o),d=Wn(a);s.debug(`Executing action: ${d} with args`);const l=await Gn(u,a,c,r,i,s);t.statusCode=200,t.setHeader("Content-Type","application/json"),t.end(JSON.stringify({success:!0,result:l}))}catch(e){const n=e instanceof Qn?e.statusCode:500,o=e instanceof Error?e.message:"Internal server error";s.debug(`Error handling executeAction: ${o}`),Yn(t,n,o)}})(e,r,u,s,n,o,i).catch((()=>{Yn(r,500,"Unexpected error")}))}else a()}}const eo=async(e,t)=>{const n=(await Promise.all(e.map((e=>w(e,{absolute:!0,cwd:t,nodir:!0}))))).flat(),o=Array.from(new Set(n)).map((e=>u.relative(t,e))),r=(e=>{if(0===e.length)return"";const t=e[0].split(u.sep);let n="";for(let o=0;o<t.length-1;o++){const r=t.slice(0,o+1).join(u.sep);if(!e.every((e=>e.startsWith(`${r}${u.sep}`))))break;n=r}return n})(o);return o.map(((e,t)=>{const o=r?e.slice(r.length+1):e;return{absolutePath:n[t],relativePath:o.split(u.sep).join("/")}}))},to=(e,t)=>ee(t)?O:t.startsWith(e)||u.isAbsolute(t)?t:u.resolve(e,t),no=(e,t)=>{let n,o=to(process.cwd(),e);for(;!n;){const e=u.resolve(o,t);if(je(e)&&(n=e),o=o.split(u.sep).slice(0,-1).join(u.sep),[u.sep,""].includes(o))break}return n},oo=(e,t)=>{const n=[...e].map((e=>to(t||process.cwd(),e).split(u.sep))),o=n.length?Math.min(...n.map((e=>e.length))):0,r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0&&r.join(u.sep)||u.sep},ro=t.bold.red,io=t.bold.yellow,so=e=>{const t=no(e,"package.json");if(t)try{const e=Pe(t);return JSON.parse(e)}catch(e){return}},ao=(e,t,n)=>{if(n?.name&&n?.identifier)return{identifier:n?.identifier,name:n.name};const o=so(e);o||t.warn(io("No package.json found to infer the app name."));const r=n?.name||o?.name?.trim();r||t.error(ro("Unable to determine the app name to compute the app identifier."));const i=((e,t)=>{const n=e||(e=>{if(e&&e.repository)return"string"==typeof e.repository?e.repository:"url"in e.repository?e.repository.url:void 0})(t);if(!n)return;const o=ie(n.trim());return o?o.replace(/\.git$/,""):void 0})(n?.url,o);i||t.error(ro("Unable to determine the git remote to compute the app identifier."));const s=n?.identifier||((e,t)=>{if(!e||!t)return;const n=`${e}:${t}`;return p("sha256").update(n).digest("hex").slice(0,32)})(i,r);return s&&r||t.error(ro("Unable to compute the app identifier.")),{identifier:s,name:r}},uo=t.green.bold,co=t.yellow.bold,lo=t.cyan.bold,po=t.bold,fo=(e,t,n,o,r)=>{if(o)return o;if(!r)return;return`https://${n??"app"}.${t}${"upload"===e?`/app-builder/apps/edit/${r}?viewMode=preview`:`/app-builder/apps/${r}`}`},mo=(e,t)=>`Could not resolve the App Builder URL for this ${e} — find "${t}" in your App Builder apps list to view it.`,ho=(e,t={},n)=>async()=>{const o=await Me(e,{contentType:"application/zip",filename:$e});return G({getForm:()=>{const e=new FormData;e.append("name",n),e.append("bundle",o,$e);const t=q("APPS_VERSION_NAME")?.trim();t&&e.append("version",t);const r=q("APPS_BITS_CHAT_ID")?.trim();return r&&e.append("bits_chat_id",r),e},defaultHeaders:t,zip:!1})},go=async(e,t,n)=>{const o=[],r=[],i=t.doAuthenticatedRequest;if(!t.identifier)return o.push(new Error("No app identifier provided")),{errors:o,warnings:r};const s=(a=t.site,u=t.identifier,q("APPS_INTAKE_URL")||`https://api.${a}/${ve}/${u}/upload`);var a,u;const d=J({bundler:t.bundlerName,plugin:"apps",version:t.version}),l=ae({identifier:t.identifier,intakeUrl:s,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),p=`an archive of:\n - ${uo(e.assets.length.toString())} files\n - ${uo(v(e.size))}\n\nWith the configuration:\n${l}`;if(t.dryRun)return n.error(`\n${lo("Dry run enabled")}\n\nSkipping assets upload.\nWould have uploaded ${p}`),{errors:o,warnings:r};try{const o=await i({url:s,method:"POST",type:"json",getData:ho(e.archivePath,d,t.name),onRetry:(e,t)=>{const o=`Failed to upload archive (attempt ${co(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}});n.debug(`Uploaded ${p}\n`);const a=fo("upload",t.site,t.siteSubdomain,o.app_builder_url,o.app_builder_id);if(a)n.info(`Your application is available at:\n ${lo(a)}`);else{const e=mo("upload",t.name);r.push(e),n.warn(e)}const u=V(q("APPS_PUBLISH"),!0);if(o.version_id&&u){const e=((e,t)=>`https://api.${e}/${ve}/${t}/release/live`)(t.site,t.identifier),s=await i({url:e,method:"PUT",type:"json",getData:async()=>({data:c.from(JSON.stringify({version_id:o.version_id})),headers:{"Content-Type":"application/json",...d}}),onRetry:(e,t)=>{const o=`Failed to release version (attempt ${co(`${t}/5`)}): ${e.message}`;r.push(o),n.warn(o)}}),a=fo("release",t.site,t.siteSubdomain,s.app_builder_url,s.app_builder_id??o.app_builder_id);if(a)n.info(`Published uploaded version ${po(o.version_id)} to live.\n ${lo(a)}`);else{n.info(`Published uploaded version ${po(o.version_id)} to live.`);const e=mo("release",t.name);r.push(e),n.warn(e)}}else o.version_id&&!u&&n.info(`Uploaded version ${po(o.version_id)} as a draft (publish skipped).`)}catch(e){const t=e instanceof Error?e:new Error(String(e));o.push(t)}return{errors:o,warnings:r}},yo=t.yellow.bold,bo=t.red.bold,wo="manifest.json";async function vo(e,t){const n=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-manifest-")),o=u.join(n,wo);try{await r.writeFile(o,JSON.stringify(function(e,t){const n={};for(const t of e)n[pt(t)]={allowedConnectionIds:[...t.allowedConnectionIds]};const o={backend:{functions:n}};null!=t.description&&(o.description=t.description),null!=t.selfService&&(o.selfService=t.selfService);const r=t.permissions?.protectionLevel??null,i=t.permissions?.runAs??null;return null==r&&null==i||(o.permissions={...null!=r&&{protectionLevel:r},...null!=i&&{runAs:i}}),o}(e,t),null,2))}catch(e){throw await Ie(n),e}return{manifestAsset:{absolutePath:o,relativePath:wo},cleanup:()=>Ie(n)}}const $o=async({backendOutputs:e,backendFunctions:t,context:n,doAuthenticatedRequest:o,options:i})=>{const a=n.getLogger(we),{auth:c,buildRoot:d,bundler:{name:l,outDir:p},git:f,version:m}=n,g=a.time("handle assets");let y,w,v;try{const n=a.time("resolve identifier"),{name:g,identifier:v}=ao(d,a,{url:f?.remote,name:i.name,identifier:i.identifier});if(!v||!g)throw new Error("Missing apps identification.\nEither:\n - pass an 'options.apps.identifier' and 'options.apps.name' to your plugin's configuration.\n - have a 'name' and a 'repository' in your 'package.json'.\n - have a valid remote url on your git project.\n");n.end();const $=u.relative(d,p),k=[...i.include,`${$}/**/*`],x=await eo(k,d);if(!x.length)return void a.debug("No assets to upload.");const S=new Set(e.values()),E=x.filter((e=>!S.has(e.absolutePath))).map((e=>({...e,relativePath:`frontend/${e.relativePath}`})));for(const[t,n]of e)E.push({absolutePath:n,relativePath:`backend/${t}.js`});const{manifestAsset:I,cleanup:D}=await vo(t,i);w=D,E.push(I);const A=a.time("archive assets"),P=await(async e=>{const t=await r.mkdtemp(u.join(h.tmpdir(),"dd-apps-")),n=u.join(t,$e),o=new b;for(const t of e)o.file(t.relativePath,s.createReadStream(t.absolutePath),{binary:!0,compression:"DEFLATE",compressionOptions:{level:9}});await new Promise(((e,t)=>{const r=s.createWriteStream(n),i=o.generateNodeStream({type:"nodebuffer",streamFiles:!0,compression:"DEFLATE",compressionOptions:{level:9}});i.on("error",t),r.on("error",t),r.on("close",e),i.pipe(r)}));const{size:i}=await r.stat(n);return{archivePath:n,size:i,assets:e}})(E);A.end(),y=u.dirname(P.archivePath);const j=a.time("upload assets"),{errors:M,warnings:T}=await go(P,{bundlerName:l,doAuthenticatedRequest:o,dryRun:i.dryRun,identifier:v,name:g,site:c.site,siteSubdomain:c.siteSubdomain,version:m},a);if(j.end(),T.length>0&&a.warn(`${yo("Warnings while uploading assets:")}\n - ${T.join("\n - ")}`),M.length>0){const e=M.map((e=>{const t=e.cause instanceof Error?e.cause.message:e.cause,n=e.message||e.stack||String(e);return t?`${t}\n${n}`:n})).join("\n - ");throw new Error(` - ${e}`)}}catch(e){v=e,a.error(`${bo("Failed to upload assets:")}\n${e?.message||e}`)}if(y&&await Ie(y),w&&await w(),g.end(),v)throw v};const ko=u.join(T,"./apps-runtime.mjs"),xo=async()=>{throw new Error("Dry run should not perform authenticated requests.")},So=({bundler:e,context:t,options:n})=>{const o=t.getLogger(we),{auth:r}=t;t.inject({type:"file",position:Ce.MIDDLE,value:ko});const{setBackendFunctions:s,getBackendFunctions:a}=function(){const e=new Map;return{setBackendFunctions(t,n){e.set(t,n)},getBackendFunctions:()=>Array.from(e.values()).flat()}}();return{transform:{filter:{id:{include:[ke],exclude:[/node_modules/,/[/\\]dist[/\\]/]}},handler(e,n){const r=at(this.parse(e),n);if(0===r.length)return o.warn(`Backend file ${n} has no exported functions. Did you forget to add a named export?`),s(n,[]),{code:"",map:null};const{functions:i,proxyCode:a}=function(e,t,n){const o=u.relative(n,t).replace(ke,""),r=[],i=[];for(const n of e){const e={relativePath:o,name:n,absolutePath:t,allowedConnectionIds:[]};r.push(e),i.push({exportName:n,queryName:pt(e)})}return{functions:r,proxyCode:ft(i)}}(r,n,t.buildRoot);return s(n,i),o.debug(`Generated proxy for ${n} with ${i.length} export(s)`),{code:a,map:null}}},async closeBundle(){let s,c=new Map,d=a();if(d.length>0){const n=await async function(e,t,n,o){const r=await i(u.join(g(),"dd-apps-backend-")),s=new Map,a=new Map;o.debug(`Building ${t.length} backend function(s) via vite.build()`);for(const i of t){const t=pt(i),c=`\0dd-backend:${t}`,d=ht(i.name,i.absolutePath,n),l=Vn(i.absolutePath,n),p=Kn(n,{[c]:d},[l.plugin]),f=await e({...p,build:{...p.build,write:!0,outDir:r,emptyOutDir:!1,rollupOptions:{...p.build.rollupOptions,input:{[t]:c},output:{...p.build.rollupOptions.output,entryFileNames:"[name].js"}}}}),m=Array.isArray(f)?f[0]:f;if("output"in m)for(const e of m.output){if("chunk"!==e.type||!e.isEntry)continue;const n=u.resolve(r,e.fileName);s.set(t,n),o.debug(`Backend function "${t}" output: ${n}`)}a.set(i.absolutePath,l.getAllowedConnectionIds())}return{outDir:r,outputs:s,functions:t.map((e=>({...e,allowedConnectionIds:a.get(e.absolutePath)})))}}(e.build,d,t.buildRoot,o);s=n.outDir,c=n.outputs,d=n.functions}try{const e=n.dryRun?xo:ot(n.authOverrides.method,r,o);await $o({backendOutputs:c,backendFunctions:d,context:t,doAuthenticatedRequest:e,options:n})}finally{s&&await Ie(s)}},configureServer(i){let s;try{s=ot(n.authOverrides.method,r,o)}catch(e){if(!(e instanceof nt))throw e}i.middlewares.use(Xn(e.build,a,r,s,t.buildRoot,o))}}},Eo=({options:e,context:t,bundler:n})=>{const o=t.getLogger(we),r=Ee(e);return"vite"!==t.bundler.name?(o.warn(`The apps plugin only supports Vite; skipping under '${t.bundler.name}'.`),[]):[{name:we,enforce:"post",vite:So({bundler:n,context:t,options:r})}]},Io="errorTracking",Do="datadog-error-tracking-plugin",Ao=(e,n,o)=>{if(".map"!==u.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=u.relative(n,r),s=((e,t)=>{if(e.startsWith("/"))return u.join(e,t);try{const n=e.replace(/\/*$/,"/"),o=new URL(n),r=t.replace(/^[\\/]*/,"");return new URL(r,o).href}catch{return`${e}${t}`}})(e,i);return{minifiedFilePath:r,minifiedUrl:s,relativePath:i}},Po=/[/]+|[\\]+/g,jo=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,Mo=(e,t)=>{const n=e.replace(jo,"").split(Po),o=t.replace(jo,"").split(Po),r=n.join("/");let i="";for(let e=0;e<o.length;e+=1){const t=o.slice(-e).join("/");r.startsWith(t)&&(i=t)}return i},To=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,o]=await Promise.all([Te(e.minifiedFilePath),Te(e.sourcemapFilePath)]);return{file:n,sourcemap:o,repeatedPrefix:Mo(e.relativePath,t)}})(e,n),i=[],s=[],a=new Map([["event",{type:"string",options:{contentType:"application/json",filename:"event"},value:JSON.stringify({...t,minified_url:e.minifiedUrl})}],["source_map",{type:"file",path:e.sourcemapFilePath,options:{filename:"source_map",contentType:"application/json"}}],["minified_file",{type:"file",path:e.minifiedFilePath,options:{filename:"minified_file",contentType:"application/javascript"}}]]);if(o)try{a.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{s.push(`${u.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){s.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&i.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||i.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&i.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||i.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&s.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:a,errors:i,warnings:s}},Co=e=>{const t=e.message.match(/HTTP (\d{3})/);return t?`status_code:${t[1]}`:"status_code:unknown"},Oo=e=>{const t=Co(e);return"status_code:unknown"!==t?`error_type:http_${t.replace("status_code:","")}`:`error_type:${se(e.name||"unknown")}`},No=(e,t,n)=>{const o=((e,t)=>`${e}|${t.join("|")}`)(t,n),r=e.metrics.get(o);r?r.value++:e.metrics.set(o,{name:t,value:1,tags:n})},Ro=(e,t,n)=>{No(e,"retry",[...e.baseTags,`attempt:${n}`,Co(t),Oo(t)])},_o=(e,t)=>{No(e,"failure",[...e.baseTags,Co(t),Oo(t)])},Fo=(e,t)=>{if(!t.sendMetrics)return;if(!e.metrics.size)return;const n=(e=>{const t=Math.floor(Date.now()/1e3);return Array.from(e.metrics.values()).map((e=>({metric:`sourcemaps.upload.${e.name}`,type:"count",points:[[t,e.value]],tags:e.tags})))})(e);for(const e of n)t.addMetric(e)},zo=t.green.bold,Lo=t.yellow.bold,Uo=t.red.bold,Bo=(e,t={})=>async()=>G({getForm:async()=>{const t=new FormData;for(const[n,o]of e.content){const e="file"===o.type?await Me(o.path,o.options):new Blob([o.value],{type:o.options.contentType});t.append(n,e,o.options.filename)}return t},defaultHeaders:t,zip:!0}),qo=async(e,t,n,o)=>{const r=[],i=[];if(!n.apiKey)return r.push({error:new Error("No authentication token provided")}),{errors:r,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:r,warnings:i};const s=o.time("Queue uploads"),a=new($.default?$.default:$)({concurrency:t.maxConcurrency}),u=(c=n.site,q("SOURCEMAP_INTAKE_URL")||`https://sourcemap-intake.${c}/api/v2/srcmap`);var c;const d=J({bundler:n.bundlerName,plugin:"sourcemaps",version:n.version}),l=(e=>({metrics:new Map,baseTags:[`service:${e.service}`]}))(t),p=ae({...t,intakeUrl:u,outDir:n.outDir,defaultHeaders:`\n${JSON.stringify(d,null,2)}`}),f=`\nUploading ${zo(e.length.toString())} sourcemaps with configuration:\n${p}`;o.debug(f);const m=[];for(const s of e){const e={sourcemap:s.content.get("source_map")?.path.replace(n.outDir,"."),file:s.content.get("minified_file")?.path.replace(n.outDir,".")};m.push(a.add((async()=>{try{await Q({auth:{apiKey:n.apiKey},url:u,method:"POST",getData:Bo(s,d),onRetry:(t,n)=>{Ro(l,t,n);const r=`Failed to upload ${Lo(e.sourcemap)} | ${Lo(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(r),o.debug(r)}})}catch(n){if(_o(l,n),r.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}s.end(),o.debug(`Queued ${zo(e.length.toString())} uploads.`);try{await Promise.all(m),await a.onIdle()}finally{Fo(l,n)}return{warnings:i,errors:r}},Vo=async(e,t,n)=>{const o=n.time("get sourcemaps files"),r=((e,t)=>{if(!t.outputs||0===t.outputs.length)throw new Error("No output files found.");return t.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...Ao(e.minifiedPathPrefix,t.outDir,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,{outDir:t.outDir,outputs:t.outputs});o.end();const i=n.time("send sourcemaps");await(async(e,t,n,o)=>{const r=Date.now(),i=t.minifiedPathPrefix,s={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=o.time("Compute payloads"),u=await Promise.all(e.map((e=>To(e,s,i,n.git))));a.end();const c=u.map((e=>e.errors)).flat(),d=u.map((e=>e.warnings)).flat();if(d.length>0&&o.warn(`Warnings while preparing payloads:\n - ${d.join("\n - ")}`),c.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${c.join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e);return}const l=o.time("Upload sourcemaps"),{errors:p,warnings:f}=await qo(u,t,{apiKey:n.apiKey,bundlerName:n.bundlerName,version:n.version,outDir:n.outDir,site:n.site,sendMetrics:n.sendMetrics,addMetric:n.addMetric},o);if(l.end(),o.debug(`Done uploading ${zo(`${e.length-p.length}/${e.length}`)} sourcemaps in ${zo(oe(Date.now()-r))}.`),p.length>0){const e=`Failed to upload some sourcemaps:\n - ${p.map((({metadata:e,error:t})=>{const n=t.cause||t.stack||t.message;return e?`${Uo(e.file)} | ${Uo(e.sourcemap)} :\n${n}`:n})).join("\n - ")}`;if(o.error(e),!0===t.bailOnError)throw new Error(e)}f.length>0&&o.warn(`Warnings while uploading sourcemaps:\n - ${f.join("\n - ")}`)})(r,e.sourcemaps,{addMetric:t.addMetric,apiKey:t.apiKey,bundlerName:t.bundlerName,git:t.git,outDir:t.outDir,sendMetrics:t.sendMetrics,site:t.site,version:t.version},n),i.end()},Ho=e=>{const n=t.bold.red,o=e[Io]||{},r={errors:[]};if(o.sourcemaps){const t=o.sourcemaps,i=t.releaseVersion||e.metadata?.version;i||r.errors.push(`${n("sourcemaps.releaseVersion")} is required (set it directly or via ${n("metadata.version")}).`),t.releaseVersion&&e.metadata?.version&&t.releaseVersion!==e.metadata.version&&r.errors.push(`${n("sourcemaps.releaseVersion")} must match ${n("metadata.version")} when both are configured.`),t.service||r.errors.push(`${n("sourcemaps.service")} is required.`),t.minifiedPathPrefix||r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),t.minifiedPathPrefix&&!(e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(t.minifiedPathPrefix)&&r.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`),i&&(r.config={bailOnError:!1,dryRun:!1,maxConcurrency:20,...t,releaseVersion:i})}return r},Ko=({options:e,context:t})=>{const n=t.getLogger(Do),o=n.time("validate options"),r=((e,t)=>{const n=[],o=Ho(e);if(n.push(...o.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${Do}.`);return{...e[Io],sourcemaps:o.config}})(e,n);o.end();const i=ye(e,"metrics",n);let s,a,u=!1;const c=async()=>{if(!r.sourcemaps||u)return;u=!0;const e=n.time("sourcemaps process");await Vo(r,{apiKey:t.auth.apiKey,bundlerName:t.bundler.name,git:s,addMetric:t.addMetric,outDir:t.bundler.outDir,outputs:a?.outputs||[],sendMetrics:i,site:t.auth.site,version:t.version},n),e.end()};return[{name:Do,enforce:"post",async git(e){s=e,a&&await c()},async buildReport(t){a=t,!s&&ne(e)||await c()},async asyncTrueEnd(){u||await c()}}]},Wo="liveDebugger",Jo="datadog-live-debugger-plugin",Go="if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}",Yo="__DD_LIVE_DEBUGGER_BUILD__",Qo=e=>void 0===e?Go:`${Go};if(typeof globalThis.${Yo}==='undefined'){globalThis.${Yo}={version:${JSON.stringify(e)}}}`;function Zo(e){return"function"==typeof e?e:e.default}function Xo(e,t,n,o,r){const i=u.relative(t,e).replace(/\\/g,"/"),s=er(n,r);if(s)return`${i};${s}`;const a=function(e){const t=e.node.loc?.start.line??0,n=e.node.loc?.start.column??0;return`${t}:${n}`}(n);return`${i};<anonymous>@${a}:${o}`}function er(e,t){const n=e.node,o=e.parent;return"id"in n&&t.isIdentifier(n.id)?n.id.name:t.isObjectMethod(n)||t.isClassMethod(n)||t.isClassPrivateMethod(n)?or(n.key,t):t.isVariableDeclarator(o)&&t.isIdentifier(o.id)?o.id.name:t.isAssignmentExpression(o)?function(e,t){if(t.isIdentifier(e))return e.name;if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=tr(e.object,t),o=nr(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}(o.left,t):t.isObjectProperty(o)||t.isClassProperty(o)||t.isClassPrivateProperty(o)?or(o.key,t):null}function tr(e,t){if(t.isIdentifier(e))return e.name;if(t.isThisExpression(e))return"this";if(t.isMemberExpression(e)||t.isOptionalMemberExpression(e)){const n=tr(e.object,t),o=nr(e.property,e.computed,t);if(n&&o)return`${n}.${o}`}return null}function nr(e,t,n){return n.isPrivateName(e)&&n.isIdentifier(e.id)?`#${e.id.name}`:t?null:n.isIdentifier(e)?e.name:null}function or(e,t){return t.isIdentifier(e)?e.name:t.isStringLiteral(e)||t.isNumericLiteral(e)||t.isBigIntLiteral(e)?String(e.value):t.isPrivateName(e)&&t.isIdentifier(e.id)?`#${e.id.name}`:null}function rr(e,t){if(e.node.leadingComments)for(const n of e.node.leadingComments)if(n.value.includes(t))return!0;return!1}function ir(e,t){const n=[];if(t.isBlockStatement(e.body)){const o=e.params.flatMap((e=>lr(e,t))),r=new Set(o),i="id"in e&&t.isIdentifier(e.id)?e.id.name:"";for(const o of e.body.body)if(t.isVariableDeclaration(o)){const e=o.end;if(null==e)continue;for(const s of o.declarations)for(const o of lr(s.id,t))r.has(o)||o===i||n.push({name:o,declarationEnd:e,temporalDeadZones:[]})}}const o=n.length>25?n.slice(0,25):n;if(t.isBlockStatement(e.body)){const n=o.map((({name:e})=>e)),r=new Set(n),i=function(e,t,n){const o=new Map;for(const r of e.body)sr(r,t,o,n);return o}(e.body,r,t);for(const e of o)e.temporalDeadZones=i.get(e.name)??[]}return o}function sr(e,t,n,o){o.isFunctionDeclaration(e)||o.isClassDeclaration(e)||(o.isBlockStatement(e)?ar(e,t,n,o):o.isIfStatement(e)?(sr(e.consequent,t,n,o),e.alternate&&sr(e.alternate,t,n,o)):o.isForStatement(e)||o.isForInStatement(e)||o.isForOfStatement(e)||o.isWhileStatement(e)||o.isDoWhileStatement(e)?sr(e.body,t,n,o):o.isSwitchStatement(e)?function(e,t,n,o){for(const r of e.cases){ur(r.consequent,e.start,t,n,o);for(const e of r.consequent)sr(e,t,n,o)}}(e,t,n,o):o.isTryStatement(e)?(ar(e.block,t,n,o),e.handler&&ar(e.handler.body,t,n,o),e.finalizer&&ar(e.finalizer,t,n,o)):(o.isLabeledStatement(e)||o.isWithStatement(e))&&sr(e.body,t,n,o))}function ar(e,t,n,o){ur(e.body,e.start,t,n,o);for(const r of e.body)sr(r,t,n,o)}function ur(e,t,n,o,r){if(null!=t)for(const i of e)r.isVariableDeclaration(i)&&"var"!==i.kind?cr(i,t,n,o,r):r.isClassDeclaration(i)&&i.id&&dr(i.id.name,t,i.end,n,o)}function cr(e,t,n,o,r){for(const i of e.declarations)for(const s of lr(i.id,r))dr(s,t,e.end,n,o)}function dr(e,t,n,o,r){if(null==n||!o.has(e))return;const i=r.get(e)??[];i.push({start:t,end:n}),r.set(e,i)}function lr(e,t){return t.isIdentifier(e)?[e.name]:t.isRestElement(e)?t.isIdentifier(e.argument)?[e.argument.name]:lr(e.argument,t):t.isAssignmentPattern(e)?lr(e.left,t):t.isObjectPattern(e)?e.properties.flatMap((e=>t.isRestElement(e)?lr(e.argument,t):lr(e.value,t))):t.isArrayPattern(e)?e.elements.flatMap((e=>e?lr(e,t):[])):t.isTSParameterProperty(e)&&t.isIdentifier(e.parameter)?[e.parameter.name]:[]}const pr=["@babel/parser","@babel/traverse","@babel/types","magic-string"];let fr,mr,hr,gr,yr=!1;function br(e){try{return function(e){switch(e){case"@babel/parser":return C("@babel/parser");case"@babel/traverse":return C("@babel/traverse");case"@babel/types":return C("@babel/types");case"magic-string":return C("magic-string");default:throw new Error(`Unknown peer dependency: ${e}`)}}(e)}catch(e){throw function(e){if(!function(e){if(!(e instanceof Error))return!1;const t=e.code;if("MODULE_NOT_FOUND"!==t&&"ERR_MODULE_NOT_FOUND"!==t)return!1;return pr.some((t=>e.message.includes(t)))}(e))return e instanceof Error?e:new Error(String(e));const t=pr.find((t=>e.message.includes(t))),n=t??pr.join(", ");return new Error(`Datadog Live Debugger could not load "${n}". It is an optional peer dependency that must be installed in your project when the \`liveDebugger\` plugin is enabled. Install the peer dependencies with: \`npm install --save-dev ${pr.join(" ")}\` (or the yarn/pnpm/bun equivalent). Underlying error: ${e.message}`)}(e)}}const wr=/\bfunction\b|=>|\bclass\b|\)\s*\{/;function vr(e){const{code:t,filePath:n,buildRoot:o,honorSkipComments:r,functionTypes:i,namedOnly:s}=e;let a=0,u=0,c=0,d=0,l=0;if(function(e){return/['"][^'"]*(?:@css-module:|\?worker\b|\?sprite\b|dynamic!)[^'"]*['"]/.test(e)}(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:1,skippedUnsupportedCount:d,totalFunctions:l};if(!wr.test(t))return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};yr||(fr=br("@babel/parser").parse,mr=Zo(br("@babel/traverse")),hr=br("@babel/types"),gr=Zo(br("magic-string")),yr=!0);const p=fr(t,{sourceType:"unambiguous",plugins:["jsx","typescript"],sourceFilename:n}),f=[],m=new Map,h=new Set,g=new Map,y=new Map;let b=0;if(mr(p,{Function(e){l++;const t=function(e,t){if(t.isClassMethod(e.node)&&"constructor"===e.node.kind&&Dr(e,t))return e.node;return}(e,hr);if(t&&(m.set(t,t.body.start),g.set(t,function(e,t){const n=[];for(const o of e)xr(o,n,t);return n}(t.body.body,hr))),!function(e,t){const n=e.node;return!(n.generator||t.isClassMethod(n)&&"constructor"===n.kind)}(e,hr))return void d++;if(r&&function(e,t,n){let o=e;for(;o;){if(rr(o,t))return!0;if(n.isStatement(o.node)||n.isExportDeclaration(o.node)){if(o.parentPath&&n.isExportDeclaration(o.parentPath.node))return rr(o.parentPath,t);break}o=o.parentPath}return!1}(e,"@dd-no-instrumentation",hr))return void c++;if(i&&!i.includes(function(e,t){if(t.isFunctionDeclaration(e))return"functionDeclaration";if(t.isArrowFunctionExpression(e))return"arrowFunction";if(t.isObjectMethod(e))return"objectMethod";if(t.isClassPrivateMethod(e))return"classPrivateMethod";if(t.isClassMethod(e))return"classMethod";return"functionExpression"}(e.node,hr)))return void d++;if(s&&!er(e,hr))return void d++;let p=0;if(!er(e,hr)){const t=e.parentPath?.node;t&&(p=y.get(t)||0,y.set(t,p+1))}const w=Xo(n,o,e,p,hr);try{const t=e.node,n=b++,o=`$dd_p${n}`,r=function(e,t){const n=[];for(const o of e.params)for(const e of lr(o,t))"this"!==e&&n.push(e);return n.length>25?n.slice(0,25):n}(t,hr),i=ir(t,hr),s=hr.isArrowFunctionExpression(t)&&!hr.isBlockStatement(t.body),a=s&&hr.isSequenceExpression(t.body),c=function(e,t){if(t.isFunction(e.node)&&!t.isArrowFunctionExpression(e.node))return;let n=e.parentPath;for(;n;){const e=n.node;if(t.isClassMethod(e)&&"constructor"===e.kind){if(!Dr(n,t))return;return{node:e,parent:n.parent,parentPath:n.parentPath}}if(t.isFunction(e)){if(t.isArrowFunctionExpression(e)){n=n.parentPath;continue}return}n=n.parentPath}return}(e,hr),d=null!=c;c&&(h.add(c.node),m.set(c.node,c.node.body.start));const l=[],p=s||!hr.isBlockStatement(t.body)||!jr(t.body.body,hr);let g;if(!s&&hr.isBlockStatement(t.body)&&Pr(t.body.body,l,hr),!s&&hr.isBlockStatement(t.body)&&t.body.directives.length>0){g=t.body.directives[t.body.directives.length-1].end}f.push({bodyStart:t.body.start,bodyEnd:t.body.end,functionEnd:t.end,isExpressionBody:s,hasSequenceExpressionBody:a,aliasesExpressionBodySuperCall:d&&s&&Ir(t.body,hr),needsTrailingReturn:p,useThisAlias:d,bodyParenStart:s&&"number"==typeof t.body.extra?.parenStart?t.body.extra.parenStart:void 0,directivesEnd:g,functionId:w,probeVarName:o,probeIdx:String(n),entryVars:r,localVars:i,returns:l}),u++}catch(e){a++}}}),0===u)return{code:t,failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l};const w=new gr(t),v=function(e){const t=new Set;for(const n of e)n.aliasesExpressionBodySuperCall&&t.add(Er({start:n.bodyStart,end:n.bodyEnd}));return t}(f),$=function(e,t,n,o){const r=[];for(const i of e){const e=t.get(i);null!=e&&r.push({bodyStart:e,superCalls:(n.get(i)??[]).filter((e=>!o.has(Er(e))))})}return r}(h,m,g,v);for(let e=f.length-1;e>=0;e--)$r(w,t,f[e]);for(const e of $)kr(w,t,e);return{code:w.toString(),map:w.generateMap({source:n,hires:!0}),failedCount:a,instrumentedCount:u,skippedByCommentCount:c,skippedFileCount:0,skippedUnsupportedCount:d,totalFunctions:l}}function $r(e,t,n){const{probeVarName:o,probeIdx:r,functionId:i,entryVars:s,localVars:a,returns:u,bodyStart:c,bodyEnd:d,functionEnd:l,isExpressionBody:p,hasSequenceExpressionBody:f,aliasesExpressionBodySuperCall:m,useThisAlias:h,bodyParenStart:g,directivesEnd:y}=n,b=`$dd_e${r}`,w=`$dd_rv${r}`,v=h?"$dd_t":"this",$=s.join(", "),k=""!==$,x=k?`, ${b}()`:"";const S=`const ${o} = $dd_probes('${i.replace(/['\\\n\r\u2028\u2029]/g,(e=>{switch(e){case"'":return"\\'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}}))}');`,E=k?`const ${b} = () => ({${$}});`:"",I=`if (${o}) $dd_entry(${o}, ${v}${x});`,D=`catch(e) { if (${o}) $dd_throw(${o}, e, ${v}${x}); throw e; }`;if(p){if(null!=g){const n=function(e,t,n){const o=[];for(let r=t;r<n;r++)"("===e[r]&&o.push(r);return o}(t,g,c),o=function(e,t,n){const o=[];for(let r=n-1;r>=t;r--)")"===e[r]&&o.push(r);return o}(t,d,l),r=Math.min(n.length,o.length);for(let t=0;t<r;t++){const r=n[t],i=o[t];e.remove(r,r+1),e.remove(i,i+1)}}const n=["{",S,E,"try {",I,m?`const ${w} = ($dd_t = `:`const ${w} = `].filter(Boolean).join("\n");let r=f?");":";";m&&(r=f?"));":");");const i=[r,`if (${o}) $dd_return(${o}, ${w}, ${v}${Ar(b,k,a,d)});`,`return ${w};`,`} ${D}`,"}"].join("\n");if(d-c>=2){const o=f?`${n}(${t[c]}`:n+t[c];e.update(c,c+1,o),e.update(d-1,d,t[d-1]+i)}else e.update(c,d,n+t.slice(c,d)+i)}else{const r=[S,E,"try {",`let ${w};`,I].filter(Boolean).join("\n");for(const t of u){const n=Ar(b,k,a,t.start);if(null!=t.argStart&&null!=t.argEnd){const r=t.hasSequenceExpressionArgument?`(${w} = (`:`(${w} = `,i=t.hasSequenceExpressionArgument?")":"";e.appendLeft(t.argStart,r),e.appendLeft(t.argEnd,`${i}, ${o} ? $dd_return(${o}, ${w}, ${v}${n}) : ${w})`)}else e.appendLeft(t.start,`if (${o}) $dd_return(${o}, undefined, ${v}${n}); `)}if(null!=y){const n=y-1;e.update(n,y,`${t[n]}\n${r}`)}else e.update(c,c+1,`${t[c]}${r}`);const i=Ar(b,k,a,d),s=`\n${n.needsTrailingReturn?`if (${o}) $dd_return(${o}, undefined, ${v}${i});\n`:""}} ${D}\n`;e.update(d-1,d,`${s}${t[d-1]}`)}}function kr(e,t,n){e.update(n.bodyStart,n.bodyStart+1,`${t[n.bodyStart]}let $dd_t;`);for(const t of n.superCalls)e.appendLeft(t.start,"($dd_t = "),e.appendLeft(t.end,")")}function xr(e,t,n){Ir(e,n)&&t.push({start:e.start,end:e.end});const o=Object.values(e);for(const e of o)if(Array.isArray(e))for(const o of e)Sr(o,t,n);else Sr(e,t,n)}function Sr(e,t,n){n.isNode(e)&&(n.isFunction(e)&&!n.isArrowFunctionExpression(e)||xr(e,t,n))}function Er(e){return`${e.start}:${e.end}`}function Ir(e,t){return t.isCallExpression(e)&&t.isSuper(e.callee)}function Dr(e,t){const n=e.parentPath?.parentPath;if(!n)return!1;const o=n.node;return(t.isClassDeclaration(o)||t.isClassExpression(o))&&null!=o.superClass}function Ar(e,t,n,o){const r=function(e,t){const n=e.filter((({declarationEnd:e,temporalDeadZones:n})=>e<=t&&!function(e,t){return e.some((({start:e,end:n})=>e<=t&&t<n))}(n,t))).map((({name:e})=>e));if(0===n.length)return;return`{${n.join(", ")}}`}(n,o);return t&&r?`, ${e}(), ${r}`:t?`, ${e}()`:r?`, undefined, ${r}`:""}function Pr(e,t,n){for(const o of e)if(n.isReturnStatement(o))t.push({start:o.start,end:o.end,argStart:o.argument?.start??void 0,argEnd:o.argument?.end??void 0,hasSequenceExpressionArgument:n.isSequenceExpression(o.argument)});else if(!n.isFunctionDeclaration(o)&&!n.isClassDeclaration(o))if(n.isBlockStatement(o))Pr(o.body,t,n);else if(n.isIfStatement(o))Pr([o.consequent],t,n),o.alternate&&Pr([o.alternate],t,n);else if(n.isForStatement(o)||n.isForInStatement(o)||n.isForOfStatement(o)||n.isWhileStatement(o)||n.isDoWhileStatement(o))Pr([o.body],t,n);else if(n.isSwitchStatement(o))for(const e of o.cases)Pr(e.consequent,t,n);else n.isTryStatement(o)?(Pr(o.block.body,t,n),o.handler&&Pr(o.handler.body.body,t,n),o.finalizer&&Pr(o.finalizer.body,t,n)):(n.isLabeledStatement(o)||n.isWithStatement(o))&&Pr([o.body],t,n)}function jr(e,t){if(0===e.length)return!1;const n=e[e.length-1];if(t.isReturnStatement(n))return!0;if(t.isIfStatement(n)&&n.alternate){const e=t.isBlockStatement(n.consequent)?n.consequent.body:[n.consequent],o=t.isBlockStatement(n.alternate)?n.alternate.body:[n.alternate];return jr(e,t)&&jr(o,t)}return!1}const Mr=["functionDeclaration","functionExpression","arrowFunction","objectMethod","classMethod","classPrivateMethod"],Tr=t.bold.red,Cr=Number(process.env.DD_LD_LIMIT)||1/0,Or=(e,t)=>{const n=t.getLogger(Jo);let o=0,r=0,i=0,s=0,a=0,u=0,c=0,d=0;return{name:Jo,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(l,p){if(e.include.length>0){if(!e.include.some((e=>"string"==typeof e?p.includes(e):e.test(p))))return{code:l}}for(const t of e.exclude){if("string"==typeof t?p.includes(t):t.test(p))return{code:l}}if(d>=Cr)return{code:l};try{const f=vr({code:l,filePath:p,buildRoot:t.buildRoot,honorSkipComments:e.honorSkipComments,functionTypes:e.functionTypes,namedOnly:e.namedOnly});if(o+=f.instrumentedCount,c+=f.totalFunctions,r+=f.failedCount,i+=f.skippedByCommentCount,s+=f.skippedFileCount,a+=f.skippedUnsupportedCount,f.totalFunctions>0&&d++,0===f.instrumentedCount)return{code:l};u++;const m=function(e){const t=e.getNativeBuildContext?.();return t?.inputSourceMap}(this),h=f.map&&m?function(e,t,n,o){try{return k(e,((e,n)=>1===n.depth?t:null))}catch(t){return o.error(`Failed to compose source map for ${n}: ${t}`,{forward:!0}),e}}(f.map,m,p,n):f.map;return{code:f.code,map:h}}catch(e){return n.error(`Instrumentation Error in ${p}: ${e}`,{forward:!0}),{code:l}}}},buildEnd:()=>{c>0&&n.info(`Live Debugger: ${o}/${c} functions instrumented across ${u}/${d} files`,{forward:!0,context:{failedCount:r,skippedByCommentCount:i,skippedFileCount:s,skippedUnsupportedCount:a,totalFilesWithFunctions:d,instrumentedCount:o,totalFunctions:c,transformedFileCount:u}})}}},Nr=({options:e,context:t})=>{const n=((e,t)=>{const n=e[Wo]||{},o=e.metadata?.version,r=[];if(void 0!==n.include)if(Array.isArray(n.include)){for(const e of n.include)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Tr("include")} patterns must be strings or RegExp`);break}}else r.push(`${Tr("include")} must be an array of strings or RegExp`);if(void 0!==n.exclude)if(Array.isArray(n.exclude)){for(const e of n.exclude)if("string"!=typeof e&&!(e instanceof RegExp)){r.push(`${Tr("exclude")} patterns must be strings or RegExp`);break}}else r.push(`${Tr("exclude")} must be an array of strings or RegExp`);if(void 0!==n.honorSkipComments&&"boolean"!=typeof n.honorSkipComments&&r.push(`${Tr("honorSkipComments")} must be a boolean`),void 0!==n.functionTypes)if(Array.isArray(n.functionTypes)){for(const e of n.functionTypes)if(!Mr.includes(e)){r.push(`${Tr("functionTypes")} contains invalid value "${e}". Valid values: ${Mr.join(", ")}`);break}}else r.push(`${Tr("functionTypes")} must be an array of FunctionKind values`);if(void 0!==n.namedOnly&&"boolean"!=typeof n.namedOnly&&r.push(`${Tr("namedOnly")} must be a boolean`),r.length)throw t.error(`\n - ${r.join("\n - ")}`),new Error(`Invalid configuration for ${Jo}.`);return{version:o,include:n.include||[/\.[jt]sx?$/],exclude:n.exclude||[/\/node_modules\//,/\.min\.js$/,/\/pyodide-lib\//,/^vite\//,/\0/,/commonjsHelpers\.js$/,/__vite-browser-external/,/@datadog\/browser-/,/browser-sdk\/packages\//],honorSkipComments:n.honorSkipComments??!0,functionTypes:n.functionTypes,namedOnly:n.namedOnly??!1}})(e,t.getLogger(Jo));return t.inject({type:"code",position:Ce.BEFORE,injectIntoAllChunks:!0,value:Qo(n.version)}),[Or(n,t)]};const Rr=[e=>/modules\.tree\.(count|size)$/.test(e.metric)?null:e,e=>e.tags.some((e=>/^assetName:.*\.map$/.test(e)||/^moduleName:\/node_modules/.test(e)))?null:e,e=>{const t={size:1e5,count:10,duration:1e3};/^sourcemaps\.upload\.(failure|retry)$/.test(e.metric)&&(t.count=0),/(entries|loaders|warnings|errors)\.count$/.test(e.metric)&&(t.count=0),/(modules\.(dependencies|dependents)$)/.test(e.metric)&&(t.count=30),/modules\.tree\.count$/.test(e.metric)&&(t.count=150),/modules\.tree\.size$/.test(e.metric)&&(t.size=15e5),/entries\.size$/.test(e.metric)&&(t.size=0),/entries\.modules\.count$/.test(e.metric)&&(t.count=0);return(e.points.length?e.points.reduce(((e,t)=>e+t[1]),0)/e.points.length:0)>t[e.type]?e:null}],_r="metrics",Fr="datadog-metrics-plugin",zr=e=>Math.floor((e||Date.now())/1e3),Lr=(e,t)=>{const n=[`bundler:${se(e.bundler.name)}`,`plugin_version:${se(e.version)}`,`site:${se(e.auth.site)}`];return e.build.metadata.name&&n.push(`build_name:${se(e.build.metadata.name)}`),e.build.metadata.version&&n.push(`build_version:${se(e.build.metadata.version)}`),[...n,...t]},Ur=(e,t,n)=>({...e,tags:[...e.tags,...t],metric:n?`${n}.${e.metric}`:e.metric}),Br=(e,t,n,o,r)=>{const i=new Set;for(const t of e){let e={...t,toSend:!0};if(n?.length)for(const t of n){const n=t({metric:e.metric,type:e.type,points:e.points,tags:e.tags});n?e={...n,toSend:e.toSend}:e.toSend=!1}i.add(Ur(e,o,r))}const s=Array.from(i).filter((e=>e.toSend)).length;return i.add(Ur({metric:"metrics.count",type:"count",points:[[t,s+1]],tags:[],toSend:!0},o,r)),i},qr=(e="")=>e.endsWith("/")?e:`${e}/`,Vr=(e,t)=>{let n=e;return e.split(qr(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},Hr=(e,t)=>e.split("!").pop().replace(qr(t),"./"),Kr=(e,t,n)=>{let o=e.name||e.userRequest;return o||(o=((e,t)=>{let n=e.userRequest;if(!n){let o;o=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=o?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),Hr(o||"no-name",n)},Wr=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Jr=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Gr=t.bold.red,Yr=t.bold.cyan,Qr=e=>(t,n)=>{let o,r;return"function"==typeof e?(o=e(t),r=e(n)):(o=t[e],r=n[e]),o>r?-1:o<r?1:0},Zr=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(Qr("duration"));const o={name:`${e} duration`,values:n.map((e=>({name:e.name,value:oe(e.duration)}))),top:!0};n.sort(Qr("increment"));return[o,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},Xr=(e,t,n)=>{const o=[];var r;n&&(o.push(...Zr("Loader",n.loaders)),o.push(...Zr("Tapable",n.tapables)),o.push(...Zr("Module",n.modules))),o.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},o={name:"Module size",values:[],top:!0},r={name:"Module aggregated size",values:[],top:!0},i=new Set,s=te(e.build),a=new Map,u=new Map,c=new Map;for(const e of s.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)c.has(n)||c.set(n,new Set),c.get(n).add(e.filepath);for(const t of n)u.has(t)||u.set(t,new Set),u.get(t).add(e.filepath);if(u.has(e.filepath)){const n=u.get(e.filepath);for(const e of n)t.add(e)}if(c.has(e.filepath)){const t=c.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),c.set(e.filepath,n),a.set(e.filepath,{name:e.name,size:e.size,dependencies:t,dependents:n})}for(const[e,t]of a){const n=u.get(e)||new Set,o=c.get(e)||new Set;let r=t.size;for(const e of n)r+=a.get(e)?.size||0;i.add({name:t.name,size:t.size,aggregatedSize:r,dependents:o,dependencies:n})}if(!i.size)return[t,n,o];const d=Array.from(i);return d.sort(Qr((e=>e.dependents.size))),t.values=d.map((e=>({name:e.name,value:e.dependents.size.toString()}))),d.sort(Qr((e=>e.dependencies.size))),n.values=d.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),d.sort(Qr("size")),o.values=d.map((e=>({name:e.name,value:v(e.size)}))),d.sort(Qr("aggregatedSize")),r.values=d.map((e=>({name:e.name,value:v(e.aggregatedSize||e.size)}))),[t,n,o,r]})(e)),o.push(...(r=e,[{name:"Asset size",values:(r.build.outputs||[]).filter((e=>"map"!==e.type)).sort(Qr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry aggregated size",values:(r.build.entries||[]).sort(Qr((e=>e.size))).map((e=>({name:e.name,value:v(e.size)}))),top:!0},{name:"Entry number of modules",values:(r.build.entries||[]).sort(Qr((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),o.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,o=e.build.outputs?e.build.outputs.length:0,r=e.build.warnings.length,i=e.build.errors.length,s=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:oe(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:oe(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:oe(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:o.toString()},{name:"Number of entries",value:s.toString()},{name:"Number of warnings",value:r.toString()},{name:"Number of errors",value:i.toString()}),[t]})(e));const i=(e=>{let t="";for(const t of e){t.top&&t.values.length>=5&&(t.values=t.values.slice(0,5),t.name=`Top 5 ${t.name}`);for(const e of t.values)e.name=re(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),r=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),i=Math.max(n+4,o+r+4);for(const n of e){if(0===n.values.length)continue;const e=i-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=r-e.value.length;t+=` [${Gr(e.value)}] ${" ".repeat(n)}${Yr(e.name)}\n`}}return t})(o);t.info(i)},ei="api/v1/series",ti=t.bold.green,ni=(e,t,n)=>{if(!t.apiKey)return void n.info("Won't send metrics to Datadog: missing API Key.");if(!e.size)return void n.debug("No metrics to send.");const o=Array.from(e).filter((e=>e.toSend)).map((e=>({...e,toSend:void 0}))),r=new Map;for(const e of o)r.has(e.metric)||r.set(e.metric,0),r.set(e.metric,r.get(e.metric)+1);const i=Array.from(r.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${o.length} metrics with configuration:\n - intake: ${ti(`https://api.${t.site}/${ei}`)}\n\nMetrics:\n - ${i.join("\n - ")}`),Q({method:"POST",url:`https://api.${t.site}/${ei}?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:o})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))},oi=["onStart","onLoad","onResolve","onEnd"],ri=new Map,ii=new Map,si=new Map,ai=(e,t,n)=>{const o=Object.assign({},e);for(const r of oi)o[r]=async(o,i)=>{const s=ii.get(t)||{name:t,increment:0,duration:0,events:{}};s.events[r]=s.events[r]||{name:r,values:[]};const a="onLoad"===r;return(0,e[r])(o,(async(...e)=>{const o=Hr(e[0].path,n),u=si.get(o)||{name:o,increment:0,duration:0,events:{}};u.events[r]=u.events[r]||{name:r,values:[]};const c=x.now();try{return await i(...e)}finally{const n=x.now(),i=n-c,d={start:c,end:n,duration:i,context:Jr(e)};if(s.events[r].values.push(d),s.duration+=i,s.increment+=1,ii.set(t,s),u.events[r].values.push(d),u.duration+=i,u.increment+=1,si.set(o,u),a){const e=ri.get(t)||{name:t,increment:0,duration:0,events:{}};e.events[r]=e.events[r]||{name:r,values:[]},e.events[r].values.push(d),e.duration+=i,e.increment+=1,ri.set(t,e)}}}))};return o},ui=(e,t)=>({setup:n=>{n.initialOptions.metafile=!0;const o=t.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const o of n){const n=o.setup;o.setup=async r=>{const i=ai(r,o.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(n,e.buildRoot),o.end(),n.onEnd((async n=>{if(!n.metafile)return void t.warn("Missing metafile, can't proceed with modules data.");const o=t.time("getting plugins results"),{plugins:r,loaders:i,modules:s}={plugins:ii,modules:si,loaders:ri};o.end(),await e.asyncHook("timings",{tapables:r,loaders:i,modules:s})}))}});class ci{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Kr(e,t,this.cwd),o=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(Wr))(e);o.length||o.push("no-loader"),this.started[n]={module:Vr(n),timings:{start:x.now(),duration:0,end:0},loaders:o}}doneModule(e,t){const n=Kr(e,t,this.cwd),o=this.started[n];o&&(o.timings.end=x.now(),o.timings.duration=o.timings.end-o.timings.start,this.finished.push(o),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const o=n.timings.end-n.timings.start,r=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},i=n.loaders.join(",");r.events[i]=r.events[i]||{name:i,values:[]},r.events[i].values.push(n.timings),r.increment+=1,r.duration+=o,t.set(n.module,r);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=o,e.set(t,n)}}return{loaders:e,modules:t}}}class di{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,o,r,i){const s=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};s.events[n]||(s.events[n]={name:n,values:[]}),s.events[n].values.push({start:r,end:i,duration:i-r,context:o,type:e}),s.duration+=i-r,s.increment+=1,this.timings.set(t,s)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const o=n;o.duration=Object.values(n.events).map((e=>e.values.reduce(((e,t)=>e+t.end-t.start),0))).reduce(((e,t)=>e+t),0),e.set(t,o)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r),a=()=>{this.saveResult(e,n,o,Jr(r),i,x.now())};return s.then(a,a),s}}getAsyncTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=r.pop();return t.apply(this,[...r,(...t)=>(this.saveResult(e,n,o,Jr(r),i,x.now()),s(...t))])}}getDefaultTapPatch(e,t,n,o){return(...r)=>{this.checkNewHooks();const i=x.now(),s=t.apply(this,r);return this.saveResult(e,n,o,Jr(r),i,x.now()),s}}getTapPatch(e,t,n,o){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,o);case"async":return this.getAsyncTapPatch(e,t,n,o);default:return this.getDefaultTapPatch(e,t,n,o)}}newTap(e,t,n,o){return(r,i)=>{const s="string"==typeof(a=r)?a:a.name;var a;const u=`${t}-${s}`;if(this.monitoredTaps[u])return n.call(o,r,i);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,i,s,t);return n.call(o,r,c)}}replaceTaps(e,t){t.tap=this.newTap("default",e,t.tap,t),t.tapAsync=this.newTap("async",e,t.tapAsync,t),t.tapPromise=this.newTap("promise",e,t.tapPromise,t)}patchHook(e,t,n){n._fakeHook||e.includes(Fr)||(this.hooks[e]||(this.hooks[e]=[]),this.hooks[e].includes(t)||(this.hooks[e].push(t),this.replaceTaps(t,n)))}patchHooks(e){const t=e.constructor.name,n=Object.keys(e.hooks).filter((e=>!this.ignoredHooks.includes(e)&&!this.hooks[t]?.includes(e)));for(const o of n)this.patchHook(t,o,e.hooks[o])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const li=e=>async t=>{const n=e.getLogger(Fr),o={name:Fr},r=new di(e.buildRoot),i=new ci(e.buildRoot),s=n.time("parse compiler hooks");r.throughHooks(t),s.end(),t.hooks.thisCompilation.tap(o,(e=>{const t=n.time("parse compilation hooks");r.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{i.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{i.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{i.doneModule(t,e)}))})),t.hooks.afterEmit.tapPromise(o,(async()=>{const{timings:t}=r.getResults(),{loaders:n,modules:o}=i.getResults();await e.asyncHook("timings",{tapables:t,loaders:n,modules:o})}))},pi={filters:Rr},fi=({options:e,context:t,stores:n})=>{const o=t.getLogger(Fr);let r=0;((e,t)=>{e.addMetric=e=>{t.metrics.add(e)}})(t,n);const i=((e,t)=>{const n=e[_r],o=zr(n?.timestamp);let r=!1===n?.enableDefaultPrefix?"":`build.${t}`;return n?.prefix&&(r+=r?`.${n.prefix}`:n.prefix),{enableDefaultPrefix:!0,enableTracing:!1,filters:Rr,tags:[],...e[_r],timestamp:o,prefix:r.toLowerCase().replace(/(^\.*|\.*$)/g,"")}})(e,t.bundler.name),s=[],a={name:Fr,enforce:"pre",esbuild:ui(t,o),webpack:li(t),rspack:li(t)},u=o.time("build",{start:!1}),c=i.enableTracing&&["esbuild","webpack","rspack"].includes(t.bundler.name);let d,l;const p=async()=>{if(!n.metrics.size)return;const e=o.time("aggregating collected metrics"),r=(()=>{const e=new Set(n.metrics);n.metrics.clear();const o=Lr(t,i.tags);return Br(e,i.timestamp,i.filters,o,i.prefix)})();await t.asyncHook("metrics",r),e.end();const s=o.time("sending collected metrics to Datadog");await ni(r,{apiKey:t.auth.apiKey,site:t.auth.site},o),s.end()},f=async()=>{t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-r;const e=o.time("aggregating metrics"),n=i.timestamp,s=o.time("aggregate universal metrics"),a=((e,t)=>{const n=new Set,o=e.inputs||[],r=e.outputs||[],i=e.entries||[],s=e.warnings.length,a=e.errors.length,u=e.duration,c=new Map,d=new Map,l=new Map;for(const e of i){for(const t of e.inputs)c.has(t.filepath)||c.set(t.filepath,[]),c.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");l.has(n)||l.set(n,[]),l.get(n).push(e.name)}}for(const e of r)for(const t of e.inputs)d.has(t.filepath)||d.set(t.filepath,[]),d.get(t.filepath).push(e.name);n.add({metric:"assets.count",type:"count",points:[[t,r.length]],tags:[]}).add({metric:"entries.count",type:"count",points:[[t,i.length]],tags:[]}).add({metric:"errors.count",type:"count",points:[[t,a]],tags:[]}).add({metric:"modules.count",type:"count",points:[[t,o.length]],tags:[]}).add({metric:"warnings.count",type:"count",points:[[t,s]],tags:[]}),u&&n.add({metric:"compilation.duration",type:"duration",points:[[t,u]],tags:[]});for(const e of o){const o=[`moduleName:${e.name}`,`moduleType:${e.type}`];c.has(e.filepath)&&o.push(...c.get(e.filepath).map((e=>`entryName:${e}`))),d.has(e.filepath)&&o.push(...d.get(e.filepath).map((e=>`assetName:${e}`))),n.add({metric:"modules.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"modules.dependencies",type:"count",points:[[t,e.dependencies.size]],tags:o}).add({metric:"modules.dependents",type:"count",points:[[t,e.dependents.size]],tags:o})}for(const e of r){const o=[`assetName:${e.name}`,`assetType:${e.type}`],r=e.filepath.replace(/\.map$/,"");l.has(r)&&o.push(...l.get(r).map((e=>`entryName:${e}`))),n.add({metric:"assets.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"assets.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o})}for(const e of i){const o=[`entryName:${e.name}`];n.add({metric:"entries.size",type:"size",points:[[t,e.size]],tags:o}).add({metric:"entries.modules.count",type:"count",points:[[t,e.inputs.length]],tags:o}).add({metric:"entries.assets.count",type:"count",points:[[t,e.outputs.length]],tags:o})}return n})(l,n);s.end();const u=o.time("aggregate plugins metrics"),c=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"plugins.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values()){let e=0,r=0;for(const i of Object.values(o.events)){let s=0;r+=i.values.length;for(const t of i.values){const n=t.end-t.start;s+=n,e+=n}n.add({metric:"plugins.hooks.duration",type:"duration",points:[[t,s]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]}).add({metric:"plugins.hooks.increment",type:"count",points:[[t,i.values.length]],tags:[`pluginName:${o.name}`,`hookName:${i.name}`]})}n.add({metric:"plugins.duration",type:"duration",points:[[t,e]],tags:[`pluginName:${o.name}`]}).add({metric:"plugins.increment",type:"count",points:[[t,r]],tags:[`pluginName:${o.name}`]})}return n})(d?.tapables,n);u.end();const p=o.time("aggregate loaders metrics"),f=((e,t)=>{const n=new Set;if(!e)return n;n.add({metric:"loaders.count",type:"count",points:[[t,e.size]],tags:[]});for(const o of e.values())n.add({metric:"loaders.duration",type:"duration",points:[[t,o.duration]],tags:[`loaderName:${o.name}`]}).add({metric:"loaders.increment",type:"count",points:[[t,o.increment]],tags:[`loaderName:${o.name}`]});return n})(d?.loaders,n);p.end();const m=new Set([...a,...c,...f]),h=Lr(t,i.tags),g=Br(m,n,i.filters,h,i.prefix);await t.asyncHook("metrics",g),e.end();const y=o.time("outputing report");Xr(t,o,d),y.end();const b=o.time("sending metrics to Datadog");await ni(g,{apiKey:t.auth.apiKey,site:t.auth.site},o),b.end()},m={name:"datadog-universal-metrics-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now(),e[_r]?.timestamp||(i.timestamp=zr(t.build.start))},buildEnd(){u.end(),r=Date.now()},async timings(e){d=e,l&&await f()},async buildReport(e){l=e,!d&&c||await f()},async flush(){await p()}};return i.enableTracing&&s.push(a),s.push(m),s},mi="output",hi="datadog-output-plugin",gi=(e,t)=>"string"==typeof t?t.replace(/(\.json)?$/,".json"):!0===t?`${e}.json`:t,yi=e=>{const t=void 0===e;return{build:gi("build",e?.build??t),bundler:gi("bundler",e?.bundler??t),dependencies:gi("dependencies",e?.dependencies??t),errors:gi("errors",e?.errors??t),logs:gi("logs",e?.logs??t),metrics:gi("metrics",e?.metrics??t),timings:gi("timings",e?.timings??t),warnings:gi("warnings",e?.warnings??t)}},bi=(e,t)=>n=>{n.hooks.done.tap("bundler-outputs",(n=>{t((()=>{const t=e.time("stats serialization"),o=n.toJson({all:!1,assets:!0,children:!0,chunks:!0,chunkGroupAuxiliary:!0,chunkGroupChildren:!0,chunkGroups:!0,chunkRelations:!0,entrypoints:!0,errors:!0,ids:!0,modules:!0,nestedModules:!0,relatedAssets:!0,warnings:!0,reasons:!1,chunkModules:!1});return t.end(),o}))}))},wi=e=>{const t=new Set;return{buildStart(){t.clear()},writeBundle(e,n){t.add(n)},closeBundle(){e((()=>Array.from(t)))}}},vi=({options:e,context:t})=>{const n=t.getLogger(hi),o=(e=>({path:"./",...e[mi],files:yi(e[mi]?.files)}))(e),r=(e,r)=>{const i=o.files[e];if(!r||!1===i)return;t.queue((async()=>{const e=n.time(`output ${i}`),c=((e,t,n)=>{const o=u.isAbsolute(t)?t:u.resolve(e,t);return u.resolve(o,n)})(t.bundler.outDir,o.path,i);let d;try{const e="function"==typeof r?await r():r;await(async(e,t)=>{await De(u.dirname(e));const n=s.createWriteStream(e),o=new a(t,void 0,2),r=new Promise(((e,t)=>{o.on("end",(()=>{e()})),o.on("error",(e=>{t(e)}))}));return o.pipe(n),r})(c,e)}catch(e){d=e}d?n.error(`Failed writing ${i}: ${d}`):n.debug(`Wrote "./${u.relative(t.buildRoot,c)}"`),e.end()})())};return[{name:hi,buildReport(e){const t=n.time("serialize report"),o=te(e);t.end(),r("build",{bundler:o.bundler,metadata:o.metadata,start:o.start,end:o.end,duration:o.duration,writeDuration:o.writeDuration,entries:o.entries,outputs:o.outputs}),r("logs",o.logs),r("timings",o.timings),r("dependencies",o.inputs),r("errors",o.errors),r("warnings",o.warnings)},metrics(e){r("metrics",(()=>Array.from(e)))},esbuild:{setup(e){e.onEnd((e=>{r("bundler",e.metafile)}))}},rspack:bi(n,(e=>{r("bundler",e)})),rollup:wi((e=>{r("bundler",e)})),vite:wi((e=>{r("bundler",e)})),webpack:bi(n,(e=>{r("bundler",e)}))}]},$i="rum",ki="datadog-rum-plugin",xi=["8","9","a","b"],Si=(e,t)=>{const n={service:e.service,version:e.version};return e.debugId&&(n.ddDebugId=t?(e=>{const t=p("sha256").update(e).digest("hex").slice(0,32),n=`${t.slice(0,12)}4${t.slice(13)}`,o=n.charCodeAt(16)%4,r=`${n.slice(0,16)}${xi[o]}${n.slice(17)}`;return[r.slice(0,8),r.slice(8,12),r.slice(12,16),r.slice(16,20),r.slice(20,32)].join("-")})(t):f()),`(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(n)},${JSON.stringify("DD_SOURCE_CODE_CONTEXT")});`},Ei="datadog-rum-privacy-plugin";const Ii=(e,t)=>{const n=t.getLogger(Ei),o=function(e,t){const n={privacy:{addToDictionaryHelper:{expression:{code:e}}}};return["esbuild","webpack","rspack"].includes(t)&&(n.output={...n.output,inlineSourceMap:!1,embedCodeInSourceMap:!0}),n}(e.helperCodeExpression,t.bundler.name);let r=0,i=0;return{name:Ei,enforce:"post",transform:{filter:{id:{include:e.include,exclude:e.exclude}},handler(e,t){try{const n=function(e){if("rspack"===e?.framework||"webpack"===e?.framework)switch(typeof e.inputSourceMap){case"undefined":return;case"string":return e.inputSourceMap;default:return JSON.stringify(e.inputSourceMap)}}(this.getNativeBuildContext?.()),s=S({id:t,code:e,map:n},o);return 0===s.privacyDictionarySize?{code:e}:(r+=s.privacyDictionarySize,i++,s)}catch(t){return n.error(`Instrumentation Error: ${t}`,{forward:!0}),{code:e}}}},buildEnd:()=>{n.debug(`Privacy dictionary will include ${r} entries across ${i} files`,{forward:!0,context:{dictionaryEntryCount:r,fileCount:i}})}}},Di=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,Ai=(e,t)=>{const n=e.sdk;if(n.clientToken)return Di(e);if(!t.auth.apiKey||!t.auth.appKey)throw new Error('Missing "auth.apiKey" and/or "auth.appKey" to fetch "rum.sdk.clientToken".');return async()=>{let o;try{const e=await Q({url:`https://api.${t.auth.site}/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});o=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!o)throw new Error("Missing clientToken in the API response.");return Di({...e,sdk:{clientToken:o,...n}})}},Pi=e=>{const n=t.bold.red,o=e[$i]||{},r={errors:[]};if(!o.sdk)return r;o.sdk.applicationId||r.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth.apiKey&&e.auth.appKey||o.sdk.clientToken||r.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const i={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:e.auth.site||"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};return r.config={...i,...o.sdk},r},ji=e=>{const t=e[$i]||{},n={errors:[]};if(t.privacy){const e={exclude:[/\/node_modules\//,/\.preval\./,/^[!@#$%^&*()=+~`-]/],include:[/\.(?:c|m)?(?:j|t)sx?$/],addToDictionaryFunctionName:"$",helperCodeExpression:"/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()"};n.config={...e,...t.privacy}}return n},Mi=e=>{const n=t.bold.red,o=e[$i]||{},r={errors:[]};if(!o.sourceCodeContext)return r;const i=o.sourceCodeContext;return i?.debugId||i?.service&&"string"==typeof i.service||r.errors.push(`Missing ${n('"rum.sourceCodeContext.service"')}.`),r.config={...i,version:i.version||e.metadata?.version},r},Ti=({options:e,context:t})=>{const n=((e,t)=>{const n=[],o=Pi(e),r=ji(e),i=Mi(e);if(n.push(...o.errors),n.push(...r.errors),n.push(...i.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${ki}.`);const s={...e[$i],sdk:void 0,privacy:void 0,sourceCodeContext:void 0};return o.config&&(s.sdk=o.config),r.config&&(s.privacy=r.config,t.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(s.privacy,((e,t)=>t instanceof RegExp?t.toString():t))}`,{forward:!0})),i.config&&(s.sourceCodeContext=i.config),s})(e,t.getLogger(ki)),o=[],r=n.sourceCodeContext;if(r&&t.inject({type:"code",position:Ce.BEFORE,injectIntoAllChunks:!0,value:e=>Si(r,e)}),n.sdk&&(t.inject({type:"file",position:Ce.MIDDLE,value:u.join(T,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Ce.MIDDLE,value:Ai(n,t)})),n.privacy){t.inject({type:"file",position:Ce.BEFORE,value:u.join(T,"./privacy-helpers.js")});const e=Ii(n.privacy,t);o.push(e)}return o},Ci="datadog-analytics-plugin",Oi=({context:e})=>{const t=e.getLogger(Ci);return[{name:Ci,async buildStart(){"production"===e.env&&e.queue((async()=>{try{await e.sendLog({message:"Build started",context:{plugins:e.pluginNames}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}})())}}]},Ni="datadog-async-queue-plugin",Ri=e=>{const{context:t,stores:n}=e,o=t.getLogger(Ni),r=[];return t.queue=e=>{const t=e.catch((e=>{r.push(e.message||e.toString())}));n.queue.push(t)},[{name:Ni,asyncTrueEnd:async()=>{await Promise.all(n.queue),r.length>0&&o.error(`Error occurred while processing async queue:\n ${r.join("\n ")}`)}}]},_i=async(e,t,n)=>{const o=[],r=e.initialOptions.entryPoints,i=[],s=[];if(Array.isArray(r))for(const e of r){const t=e&&"object"==typeof e?e.in:e;i.push({path:t})}else r&&"object"==typeof r&&i.push(...Object.entries(r).map((([e,t])=>({name:e,path:t}))));const a=i.flatMap((e=>{return(t=e.path,t.includes("*")?w.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,r])=>{const i=await e.resolve(r,{kind:"entry-point",resolveDir:t.buildRoot});i.errors.length&&s.push(...i.errors.map((e=>e.text))),i.path&&o.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of s)n.error(e);return await Promise.all(a),o},Fi=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,zi=/(\?|%3F|\|)+/gi,Li=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=qi(e),Fi.lastIndex=0,Fi.exec(t)?.[1]||"unknown");var t},Ui=["unknown","commonjsHelpers.js",`vite${u.sep}preload-helper.js`],Bi=(e,t,n)=>{const o=new Set;for(const n of e){const e=qi(n);ee(n)||e===t||Ui.includes(e)||o.add(e)}return o},qi=e=>e.split("!").pop().split(zi).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),Vi=(e,t)=>ee(t)?O:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(u.sep),o=e.split(u.sep).filter(((e,t)=>e===n[t])).join(u.sep);return e.replace(o,"")})(t.split("!").pop(),e).split("node_modules").pop().split(zi).shift().replace(/^((\.\.?)?[/\\])+/g,""),Hi=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[to(t,e),n]))),Ki=(e,t)=>({setup(n){const o=new Map;let r=[];const i=t.time("build report",{start:!1});n.onStart((async()=>{o.clear(),r=[],i.resume();const s=t.time("process entries");r.push(...await _i(n,e,t));for(const t of r){const n=Vi(e.bundler.outDir,t.resolved);t.name?o.set(n,t.name):o.set(n,n)}s.end(),i.pause()})),n.onEnd((async n=>{i.resume();const r=t.time("collecting errors and warnings"),s=e.bundler.outDir,a=e.buildRoot;for(const t of n.errors)e.build.errors.push(t.text);for(const t of n.warnings)e.build.warnings.push(t.text);if(r.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const c=[],d=[],l=[],p=[],f=[],m={},h={},g=t.time("indexing metafile data"),y=Hi(n.metafile.inputs,a),b=Hi(n.metafile.outputs,a);g.end();const w=e=>{if(!ee(e))return e;const t=y[to(a,e)];if(!t)return e;const n=t.imports.find((e=>!ee(e.path)));return n?n.path:e},v=t.time("looping through inputs");for(const[e,t]of Object.entries(n.metafile.inputs)){if(ee(e))continue;const n=to(a,e),o={name:Vi(s,e),filepath:n,dependents:new Set,dependencies:new Set,size:t.bytes,type:Li(e)};m[n]=o,c.push(o)}v.end();const $=t.time("looping through outputs");for(const[e,r]of Object.entries(n.metafile.outputs)){const n=to(a,e),i=Vi(s,n),u=[];for(const e of Object.keys(r.inputs)){if(ee(e))continue;const n=m[to(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${i}`)}if(r.entryPoint&&!u.length){const e=m[to(a,r.entryPoint)];if(!e){t.debug(`Input ${r.entryPoint} not found for output ${i}`);continue}u.push(e)}const c={name:i,filepath:n,inputs:u,size:r.bytes,type:Li(n)};if(h[n]=c,"map"===c.type&&p.push(c),d.push(c),!r.entryPoint)continue;const f=m[to(a,w(r.entryPoint))];if(f){if(!o.get(f.name))continue;const e={...c,name:o.get(f.name)||f.name,outputs:[c],size:c.size};l.push(e)}}$.end();const k=t.time("looping through sourcemaps");for(const e of p){const n=h[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}k.end();const x={inputs:{report:m,meta:y},outputs:{report:h,meta:b}},S=/(<runtime>|https:|file:|data:|#)/g,E=e=>!ee(e)&&!e.match(S),I=(e,n,o={})=>{if(!E(e))return o;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),o;if(o[r.filepath])return o;o[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),o;if(!i.imports||!i.imports.length)return o;for(const t of i.imports){const i=t.path.match(/^\.\.?\//),d=i?u.dirname(e):a,l=to(d,t.path);if(t.external){if(E(t.path)){const e=i?l:t.path,n=x.inputs.report[e]||{filepath:e,name:Vi(s,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(n.dependents.add(r),r.dependencies.add(n)),"inputs"in r&&!r.inputs.includes(n)&&r.inputs.push(n),c.includes(n)||c.push(n),x.inputs.report[e]=n,o[n.filepath]=n}}else I(l,n,o)}return o},D=t.time("looping through entries");for(const e of l){const t={},n={};for(const n of e.inputs)I(n.filepath,x.inputs,t);for(const t of e.outputs)I(t.filepath,x.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),f.push(e)}D.end();const A=t.time("aggregate dependencies and dependents");for(const e of c){if("external"===e.type)continue;const n=x.inputs.meta[e.filepath];if(n)for(const o of n.imports){if(!E(o.path))continue;const n=o.path.match(/^\.?\.\//),r=n?u.dirname(e.filepath):a,i=to(r,o.path);let s;if(o.external){const e=n?i:o.path;s=x.inputs.report[e]}else s=x.inputs.report[i];s?(e.dependencies.add(s),s.dependents.add(e)):t.debug(`Could not find input file of ${o.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}A.end(),e.build.outputs=d,e.build.inputs=c,e.build.entries=f,i.end(),await e.asyncHook("buildReport",e.build)}))}}),Wi=(e,t)=>{const n=t.time("module parsing",{start:!1}),o=t.time("build report",{start:!1}),r=t.time("filling entries",{start:!1}),i=t.time("filling inputs and outputs",{start:!1}),a=t.time("completing dependencies and dependents",{start:!1}),u=t.time("filling dependencies and dependents",{start:!1}),c=t.time("filling sourcemaps inputs",{start:!1}),d=new Map,l=new Map,p=new Map,f=new Map;return{buildStart(){f.clear(),d.clear(),l.clear(),p.clear()},onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){n.resume();const t=qi(e.id),o=f.get(t)||{dependencies:new Set,dependents:new Set},r=Bi(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),i=Bi(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of i)o.dependents.add(e);for(const e of r)o.dependencies.add(e);f.set(t,o),n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,m){o.resume();const h=n.dir?to(e.buildRoot,n.dir):e.bundler.outDir,g=new Set,y=new Set,b=new Map;a.resume();for(const[e,{dependencies:t,dependents:n}]of f){for(const n of t){const t=qi(n),o=f.get(t)||{dependencies:new Set,dependents:new Set};o.dependents.has(e)||(o.dependents.add(e),f.set(t,o))}for(const t of n){const n=qi(t),o=f.get(n)||{dependencies:new Set,dependents:new Set};o.dependencies.has(e)||(o.dependencies.add(e),f.set(n,o))}}a.end(),i.resume();for(const[e,n]of Object.entries(m)){const o=to(h,e),r="code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),i=l.get(o)||{name:e,filepath:o,inputs:[],size:r,type:Li(e)};if("map"===i.type&&y.add(i),"modules"in n)for(const[e,t]of Object.entries(n.modules)){if(qi(e)!==e)continue;let n=t.originalLength;if(!n&&0!==n)try{n=s.statSync(e).size}catch(e){n=t.renderedLength}const o=d.get(e)||{name:Vi(h,e),dependencies:new Set,dependents:new Set,filepath:e,size:n,type:Li(e)};i.inputs.push(o),d.set(o.filepath,o)}if("imports"in n)for(const e of n.imports){const n=qi(e);if(!f.has(n)){b.set(to(h,n),i);continue}if(d.has(n)){t.debug(`Input report already there for ${n} from ${i.name}.`);continue}const o=d.get(n)||{name:Vi(h,e),dependencies:new Set,dependents:new Set,filepath:n,size:0,type:"external"};i.inputs.push(o),d.set(o.filepath,o)}"isEntry"in n&&n.isEntry&&g.add({...i,name:n.name,size:0,outputs:[i]}),l.set(i.filepath,i)}i.end();for(const[e,n]of b){const o=l.get(e);o?n.inputs.includes(o)||n.inputs.push(o):t.debug(`Could not find the output report for ${e}.`)}u.resume();for(const[e,n]of d){const o=f.get(e);if(o){for(const e of o.dependencies){const o=d.get(e);o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${Vi(h,e)} of ${n.name}`)}for(const e of o.dependents){const o=d.get(e);o?n.dependents.add(o):t.debug(`Could not find input for dependent ${Vi(h,e)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(u.end(),y.size){c.resume();for(const e of y){const n=e.filepath.replace(/\.map$/,""),o=l.get(n);o?e.inputs.push(o):t.debug(`Could not find output for sourcemap ${e.name}`)}c.end()}const w=(e,n=new Map)=>{if(n.has(e))return n;const o=Vi(h,e),r=l.get(e);if(!r)return d.has(o)||t.debug(`Could not find output for ${o}`),n;n.set(e,r);const i=m[Vi(h,e)];if(!i)return t.debug(`Could not find asset for ${o}`),n;const s=[];"imports"in i&&s.push(...i.imports),"dynamicImports"in i&&s.push(...i.dynamicImports);for(const e of s)w(to(h,e),n);return n};r.resume();for(const e of g){const n=w(e.filepath);e.outputs=Array.from(n.values()),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.has(e.filepath)&&t.debug(`Entry "${e.name}":"${Vi(h,e.filepath)}" already reported.`),p.set(e.filepath,e)}r.pause(),o.pause()},async closeBundle(){e.build.inputs=Array.from(d.values()),e.build.outputs=Array.from(l.values()),e.build.entries=Array.from(p.values()),r.end(),o.end(),await e.asyncHook("buildReport",e.build)}}},Ji=(e,t,n)=>o=>{let r=[],i=[],s=[];const a=new Map,u=new Map,c=new Map,d=new Map,l=[],p=new Map,f=n.time("build report",{start:!1}),m=e=>!(!e||e.startsWith("webpack/runtime")||e.startsWith("multi ")||ee(e)),h=e=>e.replace(/(^external[^"]+"|"$)/g,""),g=e=>{const t=(e=>{const t=e.identifier();return{identifier:()=>t,dependencies:"dependencies"in e?[...e.dependencies]:[],blocks:"blocks"in e?[...e.blocks]:[],externalType:"externalType"in e?e.externalType:void 0,external:"external"in e?e.external:void 0}})(e),n=(e=>{const t=new Set,n=["rawRequest","resource","request","userRequest"],o=e=>{const n=qi(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};o(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&o(n)}return t})(e);for(const e of n)if(d.has(e)){const n=d.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else d.set(e,t)},y=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),y(n,t);if("blocks"in e)for(const n of e.blocks)y(n,t);return t},b=(e,t)=>{if("request"in t&&t.request){const n=qi(t.request);if(d.has(n))return d.get(n);if(e.context){const t=to(qi(e.context),n);if(d.has(t))return d.get(t)}}},w=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));o.hooks.thisCompilation.tap(t,(o=>{r=[],i=[],s=[],a.clear(),u.clear(),d.clear(),p.clear(),o.hooks.finishModules.tap(t,(t=>{f.resume();const o=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const s=n.time("building inputs");for(const n of t){const t=n.identifier(),o=Vi(e.bundler.outDir,t),i=new Set(y(n).map((e=>{const o=b(n,e);if(!o?.identifier())return!1;const r=o.identifier();return!!m(r)&&(r!==t&&(w(o)?h(r):r))})).filter(Boolean));if(!m(t))continue;const s=p.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=p.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),s.dependencies.add(e),p.set(e,n)}p.set(t,s);const u=w(n)?{size:0,name:h(o),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:o,dependencies:new Set,dependents:new Set,filepath:t,type:Li(t)};r.push(u),a.set(t,u),w(n)&&a.set(h(t),u)}s.end();const u=n.time("assigning dependencies and dependents");for(const e of r){const t=p.get(e.filepath);if(t){for(const o of t.dependencies){const t=a.get(o);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${o}`)}for(const o of t.dependents){const t=a.get(o);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${o}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),o.end(),f.pause()}))})),o.hooks.afterEmit.tapPromise(t,(async t=>{f.resume();const o=t.chunks,d=t.getAssets(),p=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>to(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of o){const t=p(e),n=(g?.getChunkModules(e)||[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(m);for(const e of t){if("map"===Li(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const y=n.time("building outputs");for(const t of d){const o={size:t.source.size()||0,name:t.name,inputs:[],filepath:to(e.bundler.outDir,t.name),type:Li(t.name)};if(u.set(o.filepath,o),i.push(o),"map"===o.type){l.push(o);continue}const r=c.get(o.filepath);if(r)for(const e of r){const t=a.get(e);t?o.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${o.name}`)}y.end();const b=n.time("filling sourcemaps inputs");for(const e of l){const t=u.get(e.filepath.replace(/\.map$/,""));t?e.inputs.push(t):n.debug(`Output not found for sourcemap ${e.name}`)}b.end();const w=n.time("building entries"),v=(e,t=new Set)=>{if(t.has(e))return new Set;t.add(e);const n=new Set(e.chunks);for(const o of e.childrenIterable||[]){const e=v(o,t);for(const t of e)n.add(t)}return n};for(const[o,r]of t.entrypoints){const t=new Map,i=new Map;let a=0;const c=v(r),d=Array.from(c).flatMap(p),l=r.chunks.filter((e=>g.getChunkEntryModulesIterable(e)||!1)).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(o)||r.name&&e.includes(r.name))).find((e=>"js"===Li(e)));for(const e of d){const o=u.get(e);if(e&&o){if("map"!==o.type&&!t.has(o.name)){t.set(o.name,o);for(const e of o.inputs)i.has(e.filepath)||i.set(e.filepath,e);a+=o.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const f={name:o,filepath:l?to(e.bundler.outDir,l):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:l?Li(l):"unknown"};s.push(f)}w.end();for(const n of t.errors)e.build.errors.push(n.message);for(const n of t.warnings)e.build.warnings.push(n.message);e.build.inputs=r,e.build.outputs=i,e.build.entries=s,f.end(),await e.asyncHook("buildReport",e.build)}))},Gi="datadog-build-report-plugin",Yi=e=>{const{context:t}=e,n=t.getLogger(Gi);return[{name:Gi,enforce:"post",esbuild:Ki(t,n),rspack:Ji(t,Gi,n),webpack:Ji(t,Gi,n),vite:Wi(t,n),rollup:Wi(t,n)}]},Qi="datadog-bundler-report-plugin",Zi=(e,t)=>t?u.isAbsolute(t)?t:u.resolve(e,t):"",Xi=e=>{if(!e)return[];return(Array.isArray(e)?e:[e]).map((e=>e.dir?e.dir:e.file?u.dirname(e.file):void 0)).filter(Boolean)},es=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=Zi(process.cwd(),t.options.output.path)),e.hook("bundlerReport",e.bundler),t.options.context&&(e.buildRoot=t.options.context),e.hook("buildRoot",e.buildRoot)},ts=e=>({configResolved(t){e.bundler.rawConfig=t;let n=t.build?.outDir??"dist";const o=t.build?.rollupOptions?.output,r=Xi(o);e.buildRoot=t.root??process.cwd(),o&&r.length&&(n=oo(r,process.cwd())),e.bundler.outDir=Zi(e.buildRoot,n),e.hook("buildRoot",e.buildRoot),e.hook("bundlerReport",e.bundler)}}),ns=e=>{const{context:t}=e,n=t.getLogger(Qi);return[{name:Qi,enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.absWorkingDir&&(t.buildRoot=e.initialOptions.absWorkingDir),e.initialOptions.outdir&&(t.bundler.outDir=Zi(t.buildRoot,e.initialOptions.outdir)),e.initialOptions.outfile&&(t.bundler.outDir=Zi(t.buildRoot,u.dirname(e.initialOptions.outfile))),t.hook("buildRoot",t.buildRoot),t.hook("bundlerReport",t.bundler),e.initialOptions.metafile=!0}},webpack:es(t),rspack:es(t),vite:ts(t),rollup:{options(e){let n;if("output"in e){const t=Xi(e.output);n=oo(t,process.cwd())}const o=(e=>{const t=new Set;if(e.input){const n=Array.isArray(e.input)?e.input:"object"==typeof e.input?Object.values(e.input):[e.input];for(const e of n){if("string"!=typeof e)throw new Error("Invalid input type");t.add(u.dirname(e))}}return Array.from(t)})(e);if(n){t.bundler.outDir=to(process.cwd(),n);const e=oo([n,...o],process.cwd());t.buildRoot=e===u.sep?process.cwd():e}else t.buildRoot=oo(o,process.cwd()),t.bundler.outDir=u.resolve(process.cwd(),"dist");t.hook("buildRoot",t.buildRoot)},buildStart(e){t.bundler.rawConfig=e},renderStart(e){t.bundler.rawConfig.outputs=t.bundler.rawConfig.outputs||[],t.bundler.rawConfig.outputs.push(e),t.hook("bundlerReport",t.bundler);const o=Xi(e);oo(o,process.cwd()).startsWith(t.bundler.outDir)||n.warn("The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.")}}}]},os="datadog-custom-hooks-plugin",rs=e=>{const{context:t}=e,n=t.getLogger(os),o=e=>(o,...r)=>{const i=n.time(`execution | ${o}`,{tags:["type:custom-hook",`hook:${o}`]}),s=[],a=[];for(const n of t.plugins){if(!(o in n))continue;const t=n[o];if("function"==typeof t)try{const i=t(...r);i instanceof Promise&&(e||s.push(`Plugin "${n.name}" returned a promise on the non async hook "${o}".`),a.push(i))}catch(e){s.push(`Plugin "${n.name}" errored on hook "${o}". [${e}]`)}else s.push(`Plugin "${n.name}" has an invalid hook type for "${o}". [${typeof t}]`)}if(s.length>0){for(const e of s)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=o(!1),t.asyncHook=o(!0),[{name:os,enforce:"pre"}]};class is{constructor(e){this.trackedFilenames=new Map;for(const t of e){const e=this.getFilename(t),n=this.trackedFilenames.get(e);n?n.push(t):this.trackedFilenames.set(e,new Array(t))}}displaySource(e){return e.length<=40?e:`[...]${e.slice(-35)}`}matchSourcemap(e,t){const n=Pe(e),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const r=o.sources;if(0===r.length)return void t("Empty 'sources' field in sourcemap.");const i=this.matchSources(r);if(0!==i.length)return i;t(`${r.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const o of e){const e=this.getFilename(o);if(n.has(e))continue;n.add(e);const r=this.trackedFilenames.get(e);r&&(t=t.concat(r))}return t}rawTrackedFilesList(){let e=[];return this.trackedFilenames.forEach((t=>{e=e.concat(t)})),e}getFilename(e){let t=e.lastIndexOf("/");-1===t?t=0:t++;let n=e.lastIndexOf("?");return(-1===n||n<=t)&&(n=e.length),e.substring(t,n)}}const ss=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await as(e);for(const e of t)if(e.name===n)return ie(e.refs.push);return ie(t[0].refs.push)},as=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},us=async e=>e.revparse("HEAD"),cs=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ds=async e=>e.branch(),ls=async e=>e.show(["-s","--format=%s"]),ps=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),fs="datadog-git-plugin",ms=e=>{const{options:t,context:n}=e,o=n.getLogger(fs),r=o.time("get git information",{start:!1}),i=async e=>{try{const t=await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=E(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return E(t)})(u.dirname(e));if(0===(await t.getRemotes(!0)).length)return o.warn("No git remotes available, skipping git plugin. This is expected for a repository that has not been pushed yet."),void r.end();const i=await(async e=>{const t=[us(e),ds(e),ls(e),ps(e),cs(e),ss(e)],[n,o,r,i,s,a]=await Promise.all(t),[u,c,d,l,p,f]=i.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:d},committer:{name:l,email:p,date:f},message:r.trim(),hash:n},hash:n,branch:o.current,remote:a.trim(),trackedFilesMatcher:new is(s)}})(t);n.git=i,r.end(),await n.asyncHook("git",n.git)}catch(e){o.error(`Could not get git information: ${e.message}`)}};return[{name:fs,enforce:"pre",buildRoot(e){if(ne(t))try{r.resume();const t=no(e,".git");if(!t)return o.warn("No .git directory found, skipping git plugin."),void r.end();n.queue(i(t))}catch(e){o.error(`Could not get git information: ${e.message}`)}}}]},hs="datadog-injection-plugin",gs=/^https?:\/\//,ys=[".mjs",".mjsx",".js",".ts",".tsx",".jsx"],bs=t.bold.yellow,ws=async(e,t=process.cwd())=>(e=>r.readFile(e,{encoding:"utf-8"}))(to(t,e));function vs(e){return e.some((e=>e.injectIntoAllChunks))}const $s=(e,t,n)=>{const o=e.filter((e=>e.position===t&&(!n||n.isEntry||e.injectIntoAllChunks))).map((e=>As(e.value)?e.value(n):e.value)).filter(Boolean);if(0===o.length)return"";return`// begin injection by Datadog build plugins\n${o.map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},ks=async(e,t,n=process.cwd())=>{const o=As(e.value)?await e.value():e.value;try{if("file"===e.type){const e=o;return await(e.match(gs)?(async(e,t=5e3)=>{let n;return Promise.race([Q({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,o)=>{n=setTimeout((()=>{o(new Error("Timeout"))}),t)}))])})(e):ws(e,n))}return o}catch(r){const i=`${e.type} - ${re(o)}`;return e.fallback?(t.debug(`Fallback for "${i}": ${r.toString()}`),ks(e.fallback,t,n)):(t.warn(`Failed "${i}": ${r.toString()}`),"")}},xs=async(e,t,n,o=process.cwd())=>{const r=t.filter(Ds).map((e=>{const t=e.value;return{...e,value:e=>t(e.sourceOrHash)}})),i=t.filter((e=>!Ds(e))),s=await Promise.all(i.map((async t=>({...t,value:await ks(t,e,o)})))),a=e=>({...e,position:e.position??Ce.BEFORE});n.push(...r.map(a),...s.map(a))},Ss=e=>e instanceof Error&&"code"in e,Es=e=>ys.includes(e),Is=(e,t,n)=>{e.warn(`"${bs(t)}" files are not supported (${bs(n)}).`)},Ds=e=>"function"==typeof e.value&&1===e.value.length,As=e=>"function"==typeof e,Ps=s.promises,js=(e,t,n)=>({setup(o){const{onStart:i,onResolve:a,onLoad:c,onEnd:d,esbuild:l,initialOptions:p}=o,f=[],m=`${t.bundler.name}.${Ce.MIDDLE}.${O}.js`,g=s.realpathSync(h.tmpdir()),y=u.resolve(g,m),b=new RegExp(`${m}$`),w=p.inject;p.inject=w?[...w]:[],p.inject.push(y),i((async()=>{f.push(...await _i(o,t,e)),o.initialOptions.inject=w;try{await(async(e,t)=>{await De(u.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})})(y,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:b},(async e=>({path:e.path,namespace:hs}))),c({filter:b,namespace:hs},(async()=>({contents:$s(n,Ce.MIDDLE)||" ",resolveDir:t.buildRoot,loader:"js"}))),d((async o=>{if(!o.metafile)return void e.warn("Missing metafile from build result.");if(!function(e){return e.some((e=>e.position===Ce.BEFORE||e.position===Ce.AFTER))}(n))return;const r=[];for(const[i,s]of Object.entries(o.metafile.outputs)){const o=Boolean(s.entryPoint&&f.some((e=>e.resolved.endsWith(s.entryPoint))));if(!o&&!vs(n))continue;const a=to(t.buildRoot,i),{base:c,ext:d}=u.parse(a);Es(d)?r.push((async()=>{try{const e=`${a}.map`,t=await Ps.readFile(a,"utf-8"),r=await Ps.readFile(e,"utf-8").catch((()=>!1)),i=u.basename(a),s=$s(n,Ce.BEFORE,{sourceOrHash:t,fileName:i,isEntry:o}),c=$s(n,Ce.AFTER,{sourceOrHash:t,fileName:i,isEntry:o});if(!s&&!c)return;const d=t.replace(/\n?\/\/# sourceMappingURL=.*$/m,""),p=r?`${d}\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(r).toString("base64")}`:d,f=await l.transform(p,{loader:"default",banner:s,footer:c,sourcemap:r?"external":void 0,sourcefile:i});await Promise.all([Ps.writeFile(a,f.code),r&&f.map?Ps.writeFile(e,f.map):null])}catch(t){if(!Ss(t)||"ENOENT"!==t.code)throw t;e.warn(`Could not inject content in ${a}: ${t}`)}})()):Is(e,d,c)}await Promise.all(r)}))}}),Ms=O,Ts="?inject-proxy",Cs=(e,t)=>({renderChunk(n,o){const{base:r,ext:i}=u.parse(o.fileName);if(!Es(i))return Is(e,i,r),null;const s=$s(t,Ce.BEFORE,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry}),a=$s(t,Ce.AFTER,{sourceOrHash:n,fileName:o.fileName,isEntry:o.isEntry});if(!s&&!a)return null;const c=new I(n);return s&&c.prepend(`${s}\n`),a&&c.append(`\n${a}`),{code:c.toString(),map:c.generateMap({file:o.fileName,hires:"boundary"})}},async resolveId(e,n,o){if(ee(e))return{id:e,moduleSideEffects:!0};if(o.isEntry&&$s(t,Ce.MIDDLE)){if(e.endsWith(".html"))return null;const t=await this.resolve(e,n,o);if(!t||t.external)return t;return(await this.load(t)).moduleSideEffects=!0,`${t.id}${Ts}`}return null},load(e){if(ee(e))return $s(t,Ce.MIDDLE);if(e.endsWith(Ts)){const t=e.slice(0,-13),n=this.getModuleInfo(t);let o=`import ${JSON.stringify(Ms)};\nexport * from ${JSON.stringify(t)};`;return n?.hasDefaultExport&&(o+=`export { default } from ${JSON.stringify(t)};`),o}return null}}),Os=(e,t,n,o,r)=>i=>{const a=new WeakMap,c=e.sources.ConcatSource,d=n.bundler.name,l=u.resolve(n.buildRoot,"node_modules",".cache","datadog-build-plugins",`${d}.${Ce.MIDDLE}.${O}.js`);Ae(l,"");i.hooks.shutdown.tap(hs,(()=>{var e;e=l,s.rmSync(e,{force:!0,maxRetries:3,recursive:!0})}));const p=async()=>{await xs(t,o,r,n.buildRoot)};i.hooks.beforeRun.tapPromise(hs,p),i.hooks.watchRun.tapPromise(hs,p),i.hooks.compilation.tap(hs,(n=>{const o=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;n.hooks.processAssets.tap({name:hs,stage:o},(()=>{for(const e of n.chunks){const o=e.canBeInitial(),i=e.contentHash?.javascript??e.hash;for(const s of e.files){const{base:e,ext:d}=u.parse(s);if(!Es(d)){Is(t,d,e);continue}const l=u.basename(s),p=$s(r,Ce.BEFORE,{sourceOrHash:i,fileName:l,isEntry:o}),f=$s(r,Ce.AFTER,{sourceOrHash:i,fileName:l,isEntry:o});""===p&&""===f||n.updateAsset(s,(e=>{const t=a.get(e);if(!t||t.banner!==p||t.footer!==f){const t=new c(p,"\n",e,"\n",f);return a.set(e,{source:t,banner:p,footer:f}),t}return t.source}))}}}))}));const f=(e=>{const n={import:[l]},o=e=>{for(const[n,o]of Object.entries(e))"object"==typeof o?(o.import=o.import||[],o.import.unshift(l)):"string"==typeof o?e[n]=[l,o]:Array.isArray(o)?o.unshift(l):t.error("Invalid entry type: "+typeof o)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[n,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:n}})(i.options.entry);i.options.entry=f},Ns=e=>{const{bundler:t,context:n}=e,o=n.getLogger(hs),r=[],i=[];n.inject=e=>{r.push(e)};const s={name:hs,enforce:"post",esbuild:js(o,n,i),webpack:Os(t,o,n,r,i),rspack:Os(t,o,n,r,i),rollup:Cs(o,i),vite:{...Cs(o,i),enforce:"pre",transformIndexHtml:{order:"pre",handler:()=>$s(i,Ce.MIDDLE)?[{tag:"script",attrs:{type:"module",src:"/@id/__datadog-helper-file"},injectTo:"head-prepend"}]:[]}}};var a;return a=n.bundler.name,["rspack","webpack"].includes(a)?s.load={filter:{id:N},handler:()=>({code:$s(i,Ce.MIDDLE)})}:s.buildStart=async()=>{await xs(o,r,i,n.buildRoot)},[s]},Rs="datadog-true-end-plugin",_s=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},o=async()=>{await t.asyncHook("flush")},r=()=>{t.hook("syncTrueEnd")},i=async()=>{r(),await n(),await o()},s=e=>{e.hooks.shutdown.tapPromise(Rs,i)},a={async writeBundle(){},async closeBundle(){await i()}};return[{name:Rs,enforce:"post",webpack:s,esbuild:{setup(e){e.onEnd((async()=>{await n(),await o()})),e.onDispose((()=>{r()}))}},vite:a,rollup:a,rspack:s}]},Fs={[_r]:pi},zs=t.bold.red;var Ls="3.2.9-dev.0";const Us=(({bundler:t,version:n})=>{const o=Date.now();return e(((e,r)=>{const i=Date.now(),s=((e={})=>{const t=(e=>{const t=[];return void 0===e||void 0!==e.version&&"string"!=typeof e.version&&t.push("metadata.version must be a string"),t})(e.metadata),n=q("SITE"),o=K(n,"DATADOG_SITE/DD_SITE",t)??K(e.auth?.site,"auth.site",t),r={site:o?.site??F,siteSubdomain:o?.subdomain};if(t.length)throw new Error(`Invalid Datadog plugin configuration:\n - ${t.join("\n - ")}`);return Object.defineProperty(r,"apiKey",{value:q("API_KEY")||e.auth?.apiKey,enumerable:!1}),Object.defineProperty(r,"appKey",{value:q("APP_KEY")||e.auth?.appKey,enumerable:!1}),{enableGit:!0,logLevel:"warn",metadata:{},...e,auth:r}})(e);"esbuild"===r.framework&&(r.esbuildHostName=z);const a=process.env.BUILD_PLUGINS_ENV||"production",u=R.includes(a)?a:"development",c=t.rspackVersion||t.version||t.VERSION,d=r.framework,l={bundler:{name:d,version:c},env:u,metadata:s.metadata||{},packageName:`@datadog/${d}-plugin`,version:n},p={errors:[],logs:[],metrics:new Set,queue:[],timings:[],warnings:[]},f=(({start:e,options:t,data:n,stores:o})=>{const r=process.cwd(),i={errors:o.errors,warnings:o.warnings,logs:o.logs,metadata:n.metadata,timings:o.timings,bundler:n.bundler};return{addMetric:()=>{throw new Error("AddMetric function called before it was initialized.")},auth:t.auth,pluginNames:[],bundler:{...i.bundler,outDir:r},build:i,buildRoot:r,env:n.env,getLogger:pe(n,o,t.logLevel),asyncHook:()=>{throw new Error("AsyncHook function called before it was initialized.")},hook:()=>{throw new Error("Hook function called before it was initialized.")},inject:()=>{throw new Error("Inject function called before it was initialized.")},plugins:[],queue:()=>{throw new Error("Queue function called before it was initialized.")},sendLog:Z(n),start:e,version:n.version}})({start:o,options:s,data:l,stores:p}),m=f.getLogger("factory"),h=m.time("Plugins initialization",{start:i});f.pluginNames.push(z);const g=[];g.push(["analytics",Oi],["async-queue",Ri],["build-report",Yi],["bundler-report",ns],["custom-hooks",rs],["git",ms],["injection",Ns],["true-end",_s]),s.customPlugins&&g.push(["custom",s.customPlugins]);const y=[["apps",be,Eo],["error-tracking",Io,Ko],["live-debugger",Wo,Nr],["metrics",_r,fi],["output",mi,vi],["rum",$i,Ti]];for(const[e,t,n]of y)ye(s,t,m)&&g.push([e,n]);for(const[e,n]of g)f.plugins.push(...he(f,n,e)({bundler:t,context:f,options:s,data:l,stores:p}));return(e=>{const t=[];for(const n of B){const o=H(n);if(o.length>1&&!o.every((e=>process.env[e]===process.env[o[0]]))){const r=o.map((e=>U(e))).join(" and "),i=U(`DATADOG_${n}`);e.warn(`Conflicting keys ${r}, will use ${i}`),t.push(`${r} (using ${i})`)}else if(o.length){const e=o.map((e=>L(e))).join(" and ");t.push(`${e} (same value)`)}}t.length&&e.info(`Overrides from environment:\n - ${t.join("\n - ")}`)})(m),f.pluginNames.push(...f.plugins.map((e=>e.name))),(e=>{const t=new Set(e.filter((t=>e.filter((e=>e===t)).length>1)));if(t.size>0)throw new Error(`Duplicate plugin names: ${zs(Array.from(t).join(", "))}`)})(f.pluginNames),f.hook("init",f),h.end(),f.plugins}))})({bundler:D,version:Ls}).vite,Bs=Ls,qs=Fs;export{Us as datadogVitePlugin,qs as helpers,Bs as version};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|