@datadog/esbuild-plugin 2.5.4-dev-1 → 2.6.1

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.
@@ -12,16 +12,6 @@ declare class TrackedFilesMatcher {
12
12
  private getFilename;
13
13
  }
14
14
 
15
- declare const CONFIG_KEY$3: "ciVisibility";
16
-
17
- type CiVisibilityOptions = {
18
- disabled?: boolean;
19
- };
20
-
21
- type types$3 = {
22
- CiVisibilityOptions: CiVisibilityOptions;
23
- };
24
-
25
15
  type MinifiedPathPrefix = `http://${string}` | `https://${string}` | `/${string}`;
26
16
  type SourcemapsOptions = {
27
17
  bailOnError?: boolean;
@@ -90,6 +80,7 @@ interface RepositoryData {
90
80
  date: string;
91
81
  };
92
82
  };
83
+ hash: string;
93
84
  branch: string;
94
85
  remote: string;
95
86
  trackedFilesMatcher: TrackedFilesMatcher;
@@ -196,18 +187,18 @@ type Logger = {
196
187
  type Env = (typeof ALL_ENVS)[number];
197
188
  type TriggerHook<R> = <K extends keyof CustomHooks>(name: K, ...args: Parameters<NonNullable<CustomHooks[K]>>) => R;
198
189
  type GlobalContext = {
190
+ asyncHook: TriggerHook<Promise<void[]>>;
199
191
  auth?: AuthOptions;
200
- inject: (item: ToInjectItem) => void;
201
- bundler: BundlerReport;
202
192
  build: BuildReport;
193
+ bundler: BundlerReport;
203
194
  cwd: string;
204
195
  env: Env;
205
196
  getLogger: GetLogger;
206
197
  git?: RepositoryData;
207
- asyncHook: TriggerHook<Promise<void[]>>;
208
198
  hook: TriggerHook<void>;
209
- plugins: (PluginOptions | CustomPluginOptions)[];
199
+ inject: (item: ToInjectItem) => void;
210
200
  pluginNames: string[];
201
+ plugins: (PluginOptions | CustomPluginOptions)[];
211
202
  sendLog: (message: string, ctx?: any) => Promise<void>;
212
203
  start: number;
213
204
  version: string;
@@ -247,7 +238,6 @@ interface BaseOptions {
247
238
  logLevel?: LogLevel;
248
239
  }
249
240
  interface Options extends BaseOptions {
250
- [CONFIG_KEY$3]?: CiVisibilityOptions;
251
241
  [CONFIG_KEY$2]?: ErrorTrackingOptions;
252
242
  [CONFIG_KEY$1]?: RumOptions;
253
243
  [CONFIG_KEY]?: TelemetryOptions;
@@ -289,4 +279,4 @@ declare const helpers: {
289
279
  };
290
280
  };
291
281
 
292
- export { type types$3 as CiVisibilityTypes, type types$2 as ErrorTrackingTypes, type EsbuildPluginOptions, type types$1 as RumTypes, type types as TelemetryTypes, datadogEsbuildPlugin, helpers, version };
282
+ export { type types$2 as ErrorTrackingTypes, type EsbuildPluginOptions, type types$1 as RumTypes, type types as TelemetryTypes, datadogEsbuildPlugin, helpers, version };
package/dist/src/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var e=require("unplugin"),t=require("chalk"),n=require("fs/promises"),s=require("fs"),o=require("path"),i=require("glob"),r=require("crypto"),a=require("async-retry"),u=require("p-queue"),c=require("outdent"),p=require("buffer"),l=require("stream"),d=require("zlib"),m=require("pretty-bytes"),f=require("perf_hooks"),h=require("simple-git"),g=require("os"),I=require("module"),_=require("esbuild");const E="__datadog-helper-file",b=["development","production","test"],y="datadog-build-plugins",w=async(e,t)=>{await(async e=>n.mkdir(e,{recursive:!0}))(o.dirname(e)),await n.writeFile(e,t,{encoding:"utf-8"})},T=(e,t)=>{var n;n=o.dirname(e),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t,{encoding:"utf-8"})},D=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),R=e=>e.includes(E),S=e=>!!e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit,O=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),s=n.getUTCHours(),o=n.getUTCMinutes(),i=n.getUTCSeconds(),r=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||r?` ${r}ms`:""}`.trim()},v=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const s=Math.max(4,t-n.length),o=Math.min(10,Math.floor(s/2)),i=s-o;return`${e.slice(0,o)}${n}${e.slice(-i)}`},$=(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}},U=e=>e.split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(" ");let C=0;const N=()=>`${Date.now()}.${performance.now()}.${++C}`,M={debug:0,info:1,warn:2,error:3,none:4},B=(e,n="warn")=>s=>{const o=(e=>e.split(">").map(D).join(">"))(s),i=(i,r="debug")=>{let a=t.dim,u=console.log;"error"===r?(a=t.red,u=console.error):"warn"===r?(a=t.yellow,u=console.warn):"info"===r&&(a=t.cyan,u=console.log);const c=`[${e.metadata?.name?`${e.metadata.name}|`:""}${r}|${e.bundler.fullName}|${o}]`,p="string"==typeof i?i:JSON.stringify(i,null,2);e.logs.push({bundler:e.bundler.fullName,pluginName:s,type:r,message:p,time:Date.now()}),"error"===r&&e.errors.push(p),"warn"===r&&e.warnings.push(p),M[r]>=M[n]&&u(`${a(c)} ${p}`)};return{getLogger:t=>B(e,n)(`${o}>${t}`),time:(n,o={})=>{const{level:r="debug",start:a=!0,log:u=!0,tags:c=[]}=o,p={pluginName:s,label:n,spans:[],tags:[...c,`plugin:${s}`,`level:${r}`],logLevel:r,total:0};e.timings.push(p);const l=()=>p.spans.filter((e=>!e.end)),d=e=>{l().length||(!p.spans.length&&u&&i(t.dim(`[${t.cyan(n)}] : start`),"debug"),p.spans.push({start:e||Date.now(),tags:[`plugin:${s}`]}))},m=e=>{const s=l();if(s?.length){s.length>1&&i(`Timer ${t.cyan(n)} has more than one ongoing span.`,"debug");for(const t of s)t.end=e||Date.now()}else i(`Timer ${t.cyan(n)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),d(e)}return{timer:p,resume:d,end:e=>{m(e);const s=p.spans.reduce(((e,t)=>e+(t.end-t.start)),0);p.total=s,u&&i(`[${t.cyan(n)}] : ${t.cyan(O(s))}`,r)},pause:m,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else p.tags.push(...e)}}},error:e=>i(e,"error"),warn:e=>i(e,"warn"),info:e=>i(e,"info"),debug:e=>i(e,"debug")}},A=["buildEnd","buildStart","load","loadInclude","resolveId","transform","transformInclude","watchChange","writeBundle","cwd","init","buildReport","bundlerReport","git"],L=(e,t,n,s)=>(...o)=>{const i=s.time(`hook | ${e} | ${t}`,{log:!1}),r=n(...o);return r instanceof Promise?r.finally((()=>{i.end()})):(i.end(),r)},k=(e,t,n)=>{const s=e.getLogger(y);return e=>{const o=s.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},s=D(e.name);for(const o of A){const i=e[o];i&&(n[o]=L(s,o,i,t))}return n})(e,s))),r=i.map((e=>`plugin:${e.name}`));return o.tag(r),o.end(),i}},P="ciVisibility",j="datadog-ci-visibility-plugin",x="appveyor",G="awscodepipeline",H="azurepipelines",F="bitbucket",z="bitrise",K="buddy",Y="buildkite",V="circleci",J="codefresh",q="github",W="gitlab",X="jenkins",Q="travisci",Z="teamcity",ee="unknown",te=[q,W,X,V,G,H,Y],ne="ci.pipeline.url",se="ci.provider.name",oe="ci.pipeline.id",ie="ci.pipeline.name",re="ci.pipeline.number",ae="ci.workspace_path",ue="git.repository_url",ce="ci.job.url",pe="ci.job.name",le="ci.stage.name",de="ci.node.name",me="ci.node.labels",fe="_dd.ci.env_vars",he="git.branch",ge="git.commit.author.date",Ie="git.commit.author.email",_e="git.commit.author.name",Ee="git.commit.committer.email",be="git.commit.committer.name",ye="git.commit.message",we="git.commit.sha",Te="git.tag",De="build.span",Re=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,r=[],a=[];if(Array.isArray(o))for(const e of o){const t=e&&"object"==typeof e?e.in:e;r.push({path:t})}else o&&"object"==typeof o&&r.push(...Object.entries(o).map((([e,t])=>({name:e,path:t}))));const u=r.flatMap((e=>{return(t=e.path,t.includes("*")?i.glob.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const i=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});i.errors.length&&a.push(...i.errors.map((e=>e.text))),i.path&&s.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of a)n.error(e);return await Promise.all(u),s},Se=(e,t)=>R(t)?E:t.startsWith(e)||o.isAbsolute(t)?t:o.resolve(e,t),Oe=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,ve=/(\?|%3F|\|)+/gi,$e=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=Ne(e),Oe.lastIndex=0,Oe.exec(t)?.[1]||"unknown");var t},Ue=["unknown","commonjsHelpers.js","vite/preload-helper.js"],Ce=(e,t,n)=>{const s=new Set;for(const n of e){const e=Ne(n);R(n)||e===t||Ue.includes(e)||s.add(e)}return s},Ne=e=>e.split("!").pop().split(ve).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/]+/,""),Me=(e,t)=>R(t)?E:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):t.split("!").pop().replace(Se(e.cwd,e.bundler.outDir),"").replace(e.cwd,"").split("node_modules").pop().split(ve).shift().replace(/^((\.\.?)?\/)+/,""),Be=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Se(t,e),n]))),Ae=(e,t)=>({setup(n){const s=new Map;let i=[];const r=t.time("build report",{start:!1});n.onStart((async()=>{s.clear(),i=[],r.resume();const o=t.time("process entries");i.push(...await Re(n,e,t));for(const t of i){const n=Me(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}o.end(),r.pause()})),n.onEnd((n=>{r.resume();const i=t.time("collecting errors and warnings"),a=e.cwd;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(i.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const u=[],c=[],p=[],l=[],d=[],m={},f={},h=t.time("indexing metafile data"),g=Be(n.metafile.inputs,a),I=Be(n.metafile.outputs,a);h.end();const _=e=>{if(!R(e))return e;const t=g[Se(a,e)];if(!t)return e;const n=t.imports.find((e=>!R(e.path)));return n?n.path:e},E=t.time("looping through inputs");for(const[t,s]of Object.entries(n.metafile.inputs)){if(R(t))continue;const n=Se(a,t),o={name:Me(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:$e(t)};m[n]=o,u.push(o)}E.end();const b=t.time("looping through outputs");for(const[o,i]of Object.entries(n.metafile.outputs)){const n=Se(a,o),r=Me(e,n),u=[];for(const e of Object.keys(i.inputs)){if(R(e))continue;const n=m[Se(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${r}`)}if(i.entryPoint&&!u.length){const e=m[Se(a,i.entryPoint)];if(!e){t.debug(`Input ${i.entryPoint} not found for output ${r}`);continue}u.push(e)}const d={name:r,filepath:n,inputs:u,size:i.bytes,type:$e(n)};if(f[n]=d,"map"===d.type&&l.push(d),c.push(d),!i.entryPoint)continue;const h=m[Se(a,_(i.entryPoint))];if(h){if(!s.get(h.name))continue;const e={...d,name:s.get(h.name)||h.name,outputs:[d],size:d.size};p.push(e)}}b.end();const y=t.time("looping through sourcemaps");for(const e of l){const n=f[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}y.end();const w={inputs:{report:m,meta:g},outputs:{report:f,meta:I}},T=/(<runtime>|https:|file:|data:|#)/g,D=e=>!R(e)&&!e.match(T),S=(n,s,i={})=>{if(!D(n))return i;const r=s.report[n];if(!r)return t.debug(`Could not find report's ${n}`),i;if(i[r.filepath])return i;i[r.filepath]=r;const c=s.meta[n];if(!c)return t.debug(`Could not find metafile's ${n}`),i;if(!c.imports||!c.imports.length)return i;for(const t of c.imports){const c=t.path.match(/^\.\.?\//),p=c?o.dirname(n):a,l=Se(p,t.path);if(t.external){if(D(t.path)){const n=c?l:t.path,s=w.inputs.report[n]||{filepath:n,name:Me(e,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(s.dependents.add(r),r.dependencies.add(s)),"inputs"in r&&!r.inputs.includes(s)&&r.inputs.push(s),u.includes(s)||u.push(s),w.inputs.report[n]=s,i[s.filepath]=s}}else S(l,s,i)}return i},O=t.time("looping through entries");for(const e of p){const t={},n={};for(const n of e.inputs)S(n.filepath,w.inputs,t);for(const t of e.outputs)S(t.filepath,w.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),d.push(e)}O.end();const v=t.time("aggregate dependencies and dependents");for(const e of u){if("external"===e.type)continue;const n=w.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!D(s.path))continue;const n=s.path.match(/^\.?\.\//),i=n?o.dirname(e.filepath):a,r=Se(i,s.path);let u;if(s.external){const e=n?r:s.path;u=w.inputs.report[e]}else u=w.inputs.report[r];u?(e.dependencies.add(u),u.dependents.add(e)):t.debug(`Could not find input file of ${s.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}v.end(),e.build.outputs=c,e.build.inputs=u,e.build.entries=d,r.end(),e.hook("buildReport",e.build)}))}}),Le=(e,t)=>{const n=t.time("module parsing",{start:!1});let s={};return{buildStart(){s={}},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=Ne(e.id),o=s[t]||{dependencies:new Set,dependents:new Set},i=Ce(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Ce(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)o.dependents.add(e);for(const e of i)o.dependencies.add(e);s[t]=o,n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,o){const i=t.time("build report"),r=[],a=[],u=[],c=[],p={},l=[],d={},m={},f=t.time("completing dependencies and dependents");for(const[e,{dependencies:t,dependents:n}]of Object.entries(s)){for(const n of t){const t=Ne(n);s[t]||(s[t]={dependencies:new Set,dependents:new Set}),s[t].dependents.has(e)||s[t].dependents.add(e)}for(const t of n){const n=Ne(t);s[n]||(s[n]={dependencies:new Set,dependents:new Set}),s[n].dependencies.has(e)||s[n].dependencies.add(e)}}f.end();const h=t.time("filling inputs and outputs");for(const[n,i]of Object.entries(o)){const o={name:n,filepath:Se(e.bundler.outDir,n),inputs:[],size:"code"in i?Buffer.byteLength(i.code,"utf8"):Buffer.byteLength(i.source,"utf8"),type:$e(n)};if("map"===o.type&&c.push(o),"modules"in i)for(const[t,n]of Object.entries(i.modules)){if(Ne(t)!==t)continue;const s={name:Me(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:n.originalLength,type:$e(t)};o.inputs.push(s),d[s.filepath]=s,r.push(s)}if("imports"in i)for(const n of i.imports){const i=Ne(n);if(!s[i]){p[Se(e.bundler.outDir,i)]=o;continue}if(d[i]){t.debug(`Input report already there for ${i} from ${o.name}.`);continue}const a={name:Me(e,n),dependencies:new Set,dependents:new Set,filepath:i,size:0,type:"external"};o.inputs.push(a),d[a.filepath]=a,r.push(a)}"isEntry"in i&&i.isEntry&&u.push({...o,name:i.name,size:0,outputs:[o]}),m[o.filepath]=o,a.push(o)}h.end();for(const[e,n]of Object.entries(p)){const s=m[e];s?n.inputs.includes(s)||n.inputs.push(s):t.debug(`Could not find the output report for ${e}.`)}const g=t.time("filling dependencies and dependents");for(const n of r){const o=s[n.filepath];if(o){for(const s of o.dependencies){const o=d[s];o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${Me(e,s)} of ${n.name}`)}for(const s of o.dependents){const o=d[s];o?n.dependents.add(o):t.debug(`Could not find input for dependent ${Me(e,s)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(g.end(),c.length){const e=t.time("filling sourcemaps inputs");for(const e of c){const n=e.filepath.replace(/\.map$/,""),s=m[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}e.end()}const I=(n,s={})=>{if(s[n])return s;const i=Me(e,n),r=m[n];if(!r){return!!d[i]||t.debug(`Could not find output for ${i}`),s}s[n]=r;const a=o[Me(e,n)];if(!a)return t.debug(`Could not find asset for ${i}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)I(Se(e.bundler.outDir,t),s);return s},_=t.time("filling entries");for(const e of u){const t=I(e.filepath);e.outputs=Object.values(t),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),l.push(e)}_.end(),e.build.inputs=r,e.build.outputs=a,e.build.entries=l,i.end(),e.hook("buildReport",e.build)}}},ke=(e,t,n)=>s=>{let o=[],i=[],r=[];const a=new Map,u=new Map,c=new Map,p=new Map,l=[],d=new Map,m=n.time("build report",{start:!1}),f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||R(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"],s=e=>{const n=Ne(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};s(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&s(n)}return t})(e);for(const e of n)if(p.has(e)){const n=p.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else p.set(e,t)},I=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),I(n,t);if("blocks"in e)for(const n of e.blocks)I(n,t);return t},_=(e,t)=>{if("request"in t&&t.request){const n=Ne(t.request);if(p.has(n))return p.get(n);if(e.context){const t=Se(Ne(e.context),n);if(p.has(t))return p.get(t)}}},E=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));s.hooks.thisCompilation.tap(t,(s=>{o=[],i=[],r=[],a.clear(),u.clear(),p.clear(),d.clear(),s.hooks.finishModules.tap(t,(t=>{m.resume();const s=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const r=n.time("building inputs");for(const n of t){const t=n.identifier(),s=Me(e,t),i=new Set(I(n).map((e=>{const s=_(n,e);if(!s?.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&(E(s)?h(o):o))})).filter(Boolean));if(!f(t))continue;const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),r.dependencies.add(e),d.set(e,n)}d.set(t,r);const u=E(n)?{size:0,name:h(s),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:s,dependencies:new Set,dependents:new Set,filepath:t,type:$e(t)};o.push(u),a.set(t,u),E(n)&&a.set(h(t),u)}r.end();const u=n.time("assigning dependencies and dependents");for(const e of o){const t=d.get(e.filepath);if(t){for(const s of t.dependencies){const t=a.get(s);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${s}`)}for(const s of t.dependents){const t=a.get(s);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${s}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),s.end(),m.pause()}))})),s.hooks.afterEmit.tap(t,(t=>{m.resume();const s=t.chunks,p=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Se(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of s){const t=d(e),n=(g?g?.getChunkModules(e):"getModules"in e&&"function"==typeof e.getModules?e.getModules():[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(f);for(const e of t){if("map"===$e(e))continue;const t=c.get(e)||new Set;for(const e of n)t.add(e);c.set(e,t)}}h.end();const I=n.time("building outputs");for(const t of p){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Se(e.bundler.outDir,t.name),type:$e(t.name)};if(u.set(s.filepath,s),i.push(s),"map"===s.type){l.push(s);continue}const o=c.get(s.filepath);if(o)for(const e of o){const t=a.get(e);t?s.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${s.name}`)}I.end();const _=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}`)}_.end();const E=n.time("building entries");for(const[s,o]of t.entrypoints){const t=new Map,i=new Map;let a=0;const c=o.chunks.flatMap(d),p=o.chunks.filter((e=>g?g.getChunkEntryModulesIterable(e):"hasEntryModule"in e&&"function"==typeof e.hasEntryModule&&e.hasEntryModule())).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(s)||o.name&&e.includes(o.name))).find((e=>"js"===$e(e)));for(const e of c){const s=u.get(e);if(e&&s){if("map"!==s.type&&!t.has(s.name)){t.set(s.name,s);for(const e of s.inputs)i.has(e.filepath)||i.set(e.filepath,e);a+=s.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:p?Se(e.bundler.outDir,p):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:p?$e(p):"unknown"};r.push(l)}E.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=o,e.build.outputs=i,e.build.entries=r,m.end(),e.hook("buildReport",e.build)}))},Pe="datadog-build-report-plugin",je=e=>{const{context:t}=e,n=t.getLogger(Pe);return[{name:Pe,enforce:"post",esbuild:Ae(t,n),rspack:ke(t,Pe,n),webpack:ke(t,Pe,n),vite:Le(t,n),rollup:Le(t,n)}]},xe="datadog-ci-visibility-build-spans-plugin",Ge=(e,t)=>{const n=e.getLogger(xe),s=n.time("Build report",{start:!1}),o=n.time("Git",{start:!1}),i=n.time("Hold",{start:e.start}),r=n.time("Total time",{start:e.start}),a=n.time("Datadog plugins initialization",{start:e.start}),u=n.time("Build",{start:!1}),c=n.time("Write",{start:!1}),p=n.time("Load",{start:!1}),l=n.time("Transform",{start:!1});let d=e.start,m=e.start;return{name:xe,enforce:"pre",init(){a.end()},buildStart(){i.end(),u.resume(),S(t)&&o.resume()},git(){o.end()},loadInclude:()=>!0,load:()=>(p.resume(),null),transformInclude:()=>!0,transform:()=>(l.resume(),d=Date.now(),null),buildEnd(){p.end(),l.end(),u.end(),c.resume()},writeBundle(){m=Date.now()},buildReport(){for(const t of e.build.timings)if(t.pluginName===Pe&&"build report"===t.label)for(const e of t.spans){const t=e.end||Date.now();s.resume(e.start),s.pause(t)}},asyncTrueEnd(){"esbuild"===e.bundler.fullName&&(c.timer.spans.length||c.resume(d))},syncTrueEnd(){c.end(m),r.end()}}},He=()=>{if(process.env.GITHUB_EVENT_PATH)return(e=>{const t=s.readFileSync(e,{encoding:"utf-8"});return JSON.parse(t)})(process.env.GITHUB_EVENT_PATH)},Fe=e=>e?e.replace(/origin\/|refs\/heads\/|tags\//gm,""):e,ze=()=>{const e=process.env;let t={};if(e.DRONE){const{DRONE_BUILD_NUMBER:n,DRONE_BUILD_LINK:s,DRONE_STEP_NAME:o,DRONE_STAGE_NAME:i,DRONE_WORKSPACE:r,DRONE_GIT_HTTP_URL:a,DRONE_COMMIT_SHA:u,DRONE_BRANCH:c,DRONE_TAG:p,DRONE_COMMIT_AUTHOR_NAME:l,DRONE_COMMIT_AUTHOR_EMAIL:d,DRONE_COMMIT_MESSAGE:m}=e;t={[se]:"drone",[re]:n,[ne]:s,[pe]:o,[le]:i,[ae]:r,[ue]:a,[we]:u,[he]:c,[Te]:p,[_e]:l,[Ie]:d,[ye]:m}}if(e.CIRCLECI){const{CIRCLE_BUILD_NUM:n,CIRCLE_WORKFLOW_ID:s,CIRCLE_PROJECT_REPONAME:o,CIRCLE_BUILD_URL:i,CIRCLE_WORKING_DIRECTORY:r,CIRCLE_BRANCH:a,CIRCLE_TAG:u,CIRCLE_SHA1:c,CIRCLE_REPOSITORY_URL:p,CIRCLE_JOB:l}=e,d=`https://app.circleci.com/pipelines/workflows/${s}`;t={[ce]:i,[oe]:s,[ie]:o,[ne]:d,[pe]:l,[se]:V,[ae]:r,[we]:c,[ue]:p,[Te]:u,[he]:a,[fe]:JSON.stringify({CIRCLE_WORKFLOW_ID:s,CIRCLE_BUILD_NUM:n})}}if(e.TRAVIS){const{TRAVIS_PULL_REQUEST_BRANCH:n,TRAVIS_BRANCH:s,TRAVIS_COMMIT:o,TRAVIS_REPO_SLUG:i,TRAVIS_TAG:r,TRAVIS_JOB_WEB_URL:a,TRAVIS_BUILD_ID:u,TRAVIS_BUILD_NUMBER:c,TRAVIS_BUILD_WEB_URL:p,TRAVIS_BUILD_DIR:l,TRAVIS_COMMIT_MESSAGE:d}=e;t={[ce]:a,[oe]:u,[ie]:i,[re]:c,[ne]:p,[se]:Q,[ae]:l,[we]:o,[Te]:r,[he]:n||s,[ue]:`https://github.com/${i}.git`,[ye]:d}}if(e.GITLAB_CI){const{CI_PIPELINE_ID:n,CI_PROJECT_PATH:s,CI_PIPELINE_IID:o,CI_PIPELINE_URL:i,CI_PROJECT_DIR:r,CI_COMMIT_REF_NAME:a,CI_COMMIT_TAG:u,CI_COMMIT_SHA:c,CI_REPOSITORY_URL:p,CI_JOB_URL:l,CI_JOB_STAGE:d,CI_JOB_NAME:m,CI_COMMIT_MESSAGE:f,CI_COMMIT_TIMESTAMP:h,CI_COMMIT_AUTHOR:g,CI_JOB_ID:I,CI_PROJECT_URL:_,CI_RUNNER_ID:E,CI_RUNNER_TAGS:b}=e,{name:y,email:w}=(e=>{if(!e)return{name:"",email:""};let t="",n="";const s=e.match(/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/);return s&&(t=s[1],n=s[2]),{name:t,email:n}})(g);t={[pe]:m,[ce]:l,[oe]:n,[ie]:s,[re]:o,[ne]:i,[se]:W,[ae]:r,[le]:d,[he]:a,[we]:c,[ue]:p,[Te]:u,[ye]:f,[_e]:y,[Ie]:w,[ge]:h,[fe]:JSON.stringify({CI_PROJECT_URL:_,CI_PIPELINE_ID:n,CI_JOB_ID:I}),[me]:b,[de]:E}}if(e.GITHUB_ACTIONS||e.GITHUB_ACTION){const{GITHUB_RUN_ID:n,GITHUB_WORKFLOW:s,GITHUB_RUN_NUMBER:o,GITHUB_WORKSPACE:i,GITHUB_HEAD_REF:r,GITHUB_JOB:a,GITHUB_REF:u,GITHUB_SHA:c,GITHUB_REPOSITORY:p,GITHUB_SERVER_URL:l,GITHUB_RUN_ATTEMPT:d,DD_GITHUB_JOB_NAME:m,GITHUB_BASE_REF:f}=e,h=`${l}/${p}.git`;let g=`${l}/${p}/actions/runs/${n}`;if(d&&(g+=`/attempts/${d}`),t={[pe]:a,[ce]:$(`${l}/${p}/commit/${c}/checks`),[oe]:n,[ie]:s,[re]:o,[ne]:$(g),[se]:q,[ae]:i,[we]:c,[ue]:h,[he]:r||u||"",[fe]:JSON.stringify({GITHUB_SERVER_URL:$(l),GITHUB_REPOSITORY:p,GITHUB_RUN_ID:n,GITHUB_RUN_ATTEMPT:d,DD_GITHUB_JOB_NAME:m})},f){t["git.commit.base_ref"]=f,t["git.pull_request.base_branch"]=f;try{const e=He();t["git.commit.head_sha"]=e?.pull_request?.head?.sha,t["git.pull_request.base_branch_sha"]=e?.pull_request?.base?.sha}catch(e){}}}if(e.JENKINS_URL){const{WORKSPACE:n,BUILD_TAG:s,JOB_NAME:o,BUILD_NUMBER:i,BUILD_URL:r,GIT_BRANCH:a,GIT_COMMIT:u,GIT_URL:c,GIT_URL_1:p,DD_CUSTOM_TRACE_ID:l,DD_CUSTOM_PARENT_ID:d,NODE_NAME:m,NODE_LABELS:f}=e;if(t={[oe]:s,[re]:i,[ne]:r,[se]:X,[ae]:n,[we]:u,[ue]:c||p,[he]:a,[de]:m,[fe]:JSON.stringify({DD_CUSTOM_TRACE_ID:l,DD_CUSTOM_PARENT_ID:d})},f){let e;try{e=JSON.stringify(f.split(" ")),t[me]=e}catch(e){}}let h="";if(o){const e=o.split("/");if(e.length>1&&e[1].includes("="))h=e[0];else{const e=Fe(a);h=o.replace(`/${e}`,"")}t[ie]=h}}if(e.BUILDKITE){const{BUILDKITE_AGENT_ID:n,BUILDKITE_BRANCH:s,BUILDKITE_COMMIT:o,BUILDKITE_REPO:i,BUILDKITE_TAG:r,BUILDKITE_BUILD_ID:a,BUILDKITE_PIPELINE_SLUG:u,BUILDKITE_BUILD_NUMBER:c,BUILDKITE_BUILD_URL:p,BUILDKITE_JOB_ID:l,BUILDKITE_BUILD_CHECKOUT_PATH:d,BUILDKITE_BUILD_AUTHOR:m,BUILDKITE_BUILD_AUTHOR_EMAIL:f,BUILDKITE_MESSAGE:h}=e,g=Object.keys(e).filter((e=>e.startsWith("BUILDKITE_AGENT_META_DATA_"))).map((t=>`${t.replace("BUILDKITE_AGENT_META_DATA_","").toLowerCase()}:${e[t]}`));t={[de]:n,[se]:Y,[oe]:a,[ie]:u,[re]:c,[ne]:p,[ce]:`${p}#${l}`,[we]:o,[ae]:d,[ue]:i,[Te]:r,[he]:s,[_e]:m,[Ie]:f,[ye]:h,[fe]:JSON.stringify({BUILDKITE_BUILD_ID:a,BUILDKITE_JOB_ID:l})},g.length&&(t[me]=JSON.stringify(g))}if(e.BITRISE_BUILD_SLUG){const{BITRISE_GIT_COMMIT:n,GIT_CLONE_COMMIT_HASH:s,BITRISEIO_GIT_BRANCH_DEST:o,BITRISE_GIT_BRANCH:i,BITRISE_BUILD_SLUG:r,BITRISE_TRIGGERED_WORKFLOW_ID:a,BITRISE_BUILD_NUMBER:u,BITRISE_BUILD_URL:c,BITRISE_SOURCE_DIR:p,GIT_REPOSITORY_URL:l,BITRISE_GIT_TAG:d,BITRISE_GIT_MESSAGE:m}=e;t={[se]:z,[oe]:r,[ie]:a,[re]:u,[ne]:c,[we]:n||s,[ue]:l,[ae]:p,[Te]:d,[he]:o||i,[ye]:m}}if(e.BITBUCKET_COMMIT){const{BITBUCKET_REPO_FULL_NAME:n,BITBUCKET_BUILD_NUMBER:s,BITBUCKET_BRANCH:o,BITBUCKET_COMMIT:i,BITBUCKET_GIT_SSH_ORIGIN:r,BITBUCKET_GIT_HTTP_ORIGIN:a,BITBUCKET_TAG:u,BITBUCKET_PIPELINE_UUID:c,BITBUCKET_CLONE_DIR:p}=e,l=`https://bitbucket.org/${n}/addon/pipelines/home#!/results/${s}`;t={[se]:F,[we]:i,[re]:s,[ie]:n,[ce]:l,[ne]:l,[he]:o,[Te]:u,[ue]:r||a,[ae]:p,[oe]:c&&c.replace(/{|}/gm,"")}}if(e.CF_BUILD_ID){const{CF_BUILD_ID:n,CF_PIPELINE_NAME:s,CF_BUILD_URL:o,CF_STEP_NAME:i,CF_BRANCH:r}=e;t={[se]:J,[oe]:n,[ne]:o,[ie]:s,[pe]:i,[he]:r,[fe]:JSON.stringify({CF_BUILD_ID:n})}}if(e.TEAMCITY_VERSION){const{BUILD_URL:n,TEAMCITY_BUILDCONF_NAME:s}=e;t={[se]:Z,[ce]:n,[pe]:s}}if(e.TF_BUILD){const{BUILD_SOURCESDIRECTORY:n,BUILD_BUILDID:s,BUILD_DEFINITIONNAME:o,SYSTEM_TEAMFOUNDATIONSERVERURI:i,SYSTEM_TEAMPROJECTID:r,SYSTEM_JOBID:a,SYSTEM_TASKINSTANCEID:u,SYSTEM_PULLREQUEST_SOURCEBRANCH:c,BUILD_SOURCEBRANCH:p,BUILD_SOURCEBRANCHNAME:l,SYSTEM_PULLREQUEST_SOURCECOMMITID:d,SYSTEM_PULLREQUEST_SOURCEREPOSITORYURI:m,BUILD_REPOSITORY_URI:f,BUILD_SOURCEVERSION:h,BUILD_REQUESTEDFORID:g,BUILD_REQUESTEDFOREMAIL:I,BUILD_SOURCEVERSIONMESSAGE:_,SYSTEM_STAGEDISPLAYNAME:E,SYSTEM_JOBDISPLAYNAME:b}=e;if(t={[se]:H,[oe]:s,[ie]:o,[re]:s,[we]:d||h,[ae]:n,[ue]:m||f,[he]:c||p||l,[_e]:g,[Ie]:I,[ye]:_,[le]:E,[pe]:b,[fe]:JSON.stringify({SYSTEM_TEAMPROJECTID:r,BUILD_BUILDID:s,SYSTEM_JOBID:a})},i&&r&&s){const e=`${i}${r}/_build/results?buildId=${s}`,n=e,o=`${e}&view=logs&j=${a}&t=${u}`;t={...t,[ne]:n,[ce]:o}}}if(e.APPVEYOR){const{APPVEYOR_REPO_NAME:n,APPVEYOR_REPO_PROVIDER:s,APPVEYOR_BUILD_FOLDER:o,APPVEYOR_BUILD_ID:i,APPVEYOR_BUILD_NUMBER:r,APPVEYOR_REPO_COMMIT:a,APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH:u,APPVEYOR_REPO_BRANCH:c,APPVEYOR_REPO_TAG_NAME:p,APPVEYOR_REPO_COMMIT_AUTHOR:l,APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL:d,APPVEYOR_REPO_COMMIT_MESSAGE:m,APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED:f}=e,h=`https://ci.appveyor.com/project/${n}/builds/${i}`;t={[se]:x,[ne]:h,[oe]:i,[ie]:n,[re]:r,[ce]:h,[ae]:o,[_e]:l,[Ie]:d,[ye]:`${m||""}\n${f||""}`},"github"===s&&(t={...t,[ue]:`https://github.com/${n}.git`,[we]:a,[Te]:p,[he]:u||c})}if(e.BUDDY){const{BUDDY_PIPELINE_NAME:n,BUDDY_PIPELINE_ID:s,BUDDY_EXECUTION_ID:o,BUDDY_SCM_URL:i,BUDDY_EXECUTION_BRANCH:r,BUDDY_EXECUTION_TAG:a,BUDDY_EXECUTION_REVISION:u,BUDDY_EXECUTION_URL:c,BUDDY_EXECUTION_REVISION_MESSAGE:p,BUDDY_EXECUTION_REVISION_COMMITTER_NAME:l,BUDDY_EXECUTION_REVISION_COMMITTER_EMAIL:d}=e;t={[se]:K,[oe]:`${s||""}/${o||""}`,[ie]:n,[re]:`${o||""}`,[ne]:c,[we]:u,[he]:r,[Te]:a,[ue]:i,[ye]:p,[Ee]:d,[be]:l}}if(e.CF_BUILD_ID){const{CF_BUILD_ID:n,CF_PIPELINE_NAME:s,CF_BUILD_URL:o,CF_STEP_NAME:i,CF_BRANCH:r}=e;t={[se]:"codefresh",[oe]:n,[ie]:s,[ne]:o,[pe]:i,[fe]:JSON.stringify({CF_BUILD_ID:n})};const a=r&&r.includes("tags/")?Te:he,u=Fe(r);t[a]=u}if(e.CODEBUILD_INITIATOR?.startsWith("codepipeline")){const{CODEBUILD_BUILD_ARN:n,DD_ACTION_EXECUTION_ID:s,DD_PIPELINE_EXECUTION_ID:o}=e;t={[se]:G,[oe]:o,[fe]:JSON.stringify({CODEBUILD_BUILD_ARN:n,DD_PIPELINE_EXECUTION_ID:o,DD_ACTION_EXECUTION_ID:s})}}var n;if(t[ae]&&(t[ae]=(n=t[ae])&&"string"==typeof n?"~"!==n[0]||"/"!==n[1]&&1!==n.length?n:n.replace("~",process.env.HOME??""):""),t[ue]&&(t[ue]=$(t[ue])),t[Te]&&(t[Te]=Fe(t[Te])),t[he]){const e=t[he]||"";e.startsWith("tags/")||e.includes("/tags/")?(t[Te]||(t[Te]=Fe(e)),t[he]=""):t[he]=Fe(e)}return(e=>Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t&&""!==t))))(t)},Ke=(e,t)=>{const n=(e=>e.build.metadata?.name?`"${e.build.metadata.name}"`:'"unknown build"')(t),s=`Build of ${n} with ${U(t.bundler.fullName)}`,o=[];for(const e of t.build.timings)if(e.pluginName===xe)for(const t of e.spans){const i=t.end||Date.now();o.push({command:`${s} | ${e.pluginName} | ${U(e.label)}`,name:`${U(e.label)}`,start_time:new Date(t.start).toISOString(),end_time:new Date(i).toISOString(),tags:[`buildName:${n}`,...e.tags,...t.tags]})}return o.map((t=>((e,t)=>({ci_provider:e,span_id:r.randomBytes(5).toString("hex"),error_message:"",exit_code:0,measures:{},...t}))(e,t)))},Ye=[400,403,413],Ve=e=>{const{auth:t,url:n,method:s="GET",getData:o,type:i="text"}=e,r={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return a((async(e,r)=>{let a;try{const e={method:s,duplex:"half"};let i={};if(t?.apiKey&&(i["DD-API-KEY"]=t.apiKey),t?.appKey&&(i["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof o){const{data:t,headers:n}=await o();e.body=t,i={...i,...n}}a=await fetch(n,{...e,headers:i})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(Ye.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),{}}}),r)},Je=(e,t)=>{const n={},s={};for(const[t,n]of Object.entries(e))n&&(s[t]=new Set(n.split(/ *, */g)));for(const e of t){const[t,...n]=e.split(/ *: */g),o=t.startsWith(De)||s[t]?t:`${De}.${t}`,i=n.join(":");s[o]?.has(i)||(s[o]||(s[o]=new Set),s[o].add(i))}for(const[e,t]of Object.entries(s)){const s=Array.from(t).join(",");s&&(n[e]=s)}return n},qe=t.green.bold,We=t.yellow.bold,Xe=({options:e,context:t})=>{const n=t.getLogger(j),s=(e=>({disabled:!e[P],...e[P]}))(e);if(s.disabled)return[];const o=ze();return o["build.plugin.version"]=t.version,o["build.plugin.env"]=t.env,[Ge(t,e),{name:j,enforce:"post",git:e=>{o[ue]=e.remote,o[he]=e.branch,o[we]=e.commit.hash,o[ye]=e.commit.message,o[_e]=e.commit.author.name,o[Ie]=e.commit.author.email,o[ge]=e.commit.author.date,o[be]=e.commit.committer.name,o[Ee]=e.commit.committer.email,o["git.commit.committer.date"]=e.commit.committer.date},bundlerReport:e=>{o["build.bundler.name"]=e.name,o["build.bundler.version"]=e.version},async asyncTrueEnd(){if(!e.auth?.apiKey)return void n.info("No auth options, skipping.");const s=process.env.CIRCLECI?V:process.env.GITLAB_CI?W:process.env.GITHUB_ACTIONS||process.env.GITHUB_ACTION?q:process.env.BUILDKITE?Y:process.env.BUDDY?K:process.env.TEAMCITY_VERSION?Z:process.env.JENKINS_URL?X:process.env.TF_BUILD?H:process.env.CF_BUILD_ID?J:process.env.APPVEYOR?x:process.env.BITBUCKET_COMMIT?F:process.env.BITRISE_BUILD_SLUG?z:process.env.CODEBUILD_INITIATOR?.startsWith("codepipeline")?G:ee;if(!te.includes(s))return void n.info(`"${s}" is not a supported provider, skipping spans submission`);const i=Ke(s,t);try{const{errors:t,warnings:s}=await(async(e,t,n,s)=>{const o=[],i=[];if(!e.apiKey)return o.push("No authentication token provided."),{errors:o,warnings:i};if(0===t.length)return i.push("No spans to submit."),{errors:o,warnings:i};const r=new(u.default?u.default:u)({concurrency:20}),a=[];s.debug(`Submitting ${qe(t.length.toString())} span${t.length<=1?"":"s"}.`);for(const u of t){s.debug(`Queuing span ${qe(u.name)}.`);const t={...u,tags:Je(n,u.tags)};a.push(r.add((async()=>{try{await Ve({url:"https://app.datadoghq.com/api/intake/ci/custom_spans",auth:{apiKey:e.apiKey},method:"POST",getData:()=>{const e={data:{type:"ci_app_custom_span",attributes:t}};return{data:JSON.stringify(e),headers:{"Content-Type":"application/json"}}},onRetry:(e,t)=>{const n=`Failed to submit span ${We(u.name)}:\n ${e.message}\nRetrying ${t}/5`;i.push(n)}}),s.debug(`Submitted span ${qe(u.name)}.`)}catch(e){o.push(`Failed to submit span ${We(u.name)}:\n ${e.message}`)}})))}return await Promise.all(a),await r.onIdle(),{warnings:i,errors:o}})(e.auth,i,o,n);s.length>0&&n.warn(`Warnings while submitting spans:\n - ${s.join("\n - ")}`),t.length&&n.warn(`Error submitting some spans:\n - ${t.join("\n - ")}`)}catch(e){n.warn(`Error submitting spans: ${e}`)}}}]},Qe="errorTracking",Ze="datadog-error-tracking-plugin",et=(e,n,s)=>{if(".map"!==o.extname(s))throw new Error(`The file ${t.green.bold(s)} is not a sourcemap.`);const i=s.replace(/\.map$/,""),r=i.replace(n.bundler.outDir,"");return{minifiedFilePath:i,minifiedUrl:e.minifiedPathPrefix?o.join(e.minifiedPathPrefix,r):r,relativePath:r}},tt=/[/]+|[\\]+/g,nt=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,st=(e,t)=>{const n=e.replace(nt,"").split(tt),s=t.replace(nt,"").split(tt),o=n.join("/");let i="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(i=t)}return i},ot=async e=>{const t={empty:!1,exists:!0};try{0===(await s.promises.stat(e)).size&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},it=async(e,t,n,s)=>{const i=await(async(e,t)=>{const[n,s]=await Promise.all([ot(e.minifiedFilePath),ot(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:st(e.relativePath,t)}})(e,n),r=[],a=[],u=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(s)try{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:s.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${o.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:s.commit.hash,repository_url:s.remote}],version:1})})}catch(t){a.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return i.file.empty&&r.push(`Minified file is empty: ${e.minifiedFilePath}`),i.file.exists||r.push(`Minified file not found: ${e.minifiedFilePath}`),i.sourcemap.empty&&r.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),i.sourcemap.exists||r.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),i.repeatedPrefix&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${i.repeatedPrefix}`),{content:u,errors:r,warnings:a}},rt=t.green.bold,at=t.yellow.bold,ut=t.red.bold,ct=async(e,t)=>{if("function"==typeof s.openAsBlob){const n=await s.openAsBlob(e,{type:t.contentType});return new p.File([n],t.filename)}{const n=l.Readable.toWeb(s.createReadStream(e)),o=await new Response(n).blob();return new p.File([o],t.filename,{type:t.contentType})}},pt=(e,t={})=>async()=>{const n=new FormData,s=d.createGzip();for(const[t,s]of e.content){const e="file"===s.type?await ct(s.path,s.options):new Blob([s.value],{type:s.options.contentType});n.append(t,e,s.options.filename)}const o=new Request("fake://url",{method:"POST",body:n});return{data:l.Readable.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},lt=async(e,t,n,s)=>{const o=Date.now(),i=t.minifiedPathPrefix,r={git_repository_url:n.git?.remote,git_commit_sha:n.git?.commit?.hash,plugin_version:n.version,project_path:n.bundler.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=await Promise.all(e.map((e=>it(e,r,i,n.git)))),c=a.map((e=>e.errors)).flat(),p=a.map((e=>e.warnings)).flat();if(p.length>0&&s.warn(`Warnings while preparing payloads:\n - ${p.join("\n - ")}`),c.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${c.join("\n - ")}`;if(s.error(e),!0===t.bailOnError)throw new Error(e);return}const{errors:l,warnings:d}=await(async(e,t,n,s)=>{const o=[],i=[];if(!n.auth?.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:o,warnings:i};const r=new(u.default?u.default:u)({concurrency:t.maxConcurrency}),a={"DD-EVP-ORIGIN":`${n.bundler.fullName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},c=[];for(const u of e){const e={sourcemap:u.content.get("source_map")?.path.replace(n.bundler.outDir,"."),file:u.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${rt(e.sourcemap)} | ${rt(e.file)}`),c.push(r.add((async()=>{try{await Ve({auth:{apiKey:n.auth.apiKey},url:t.intakeUrl,method:"POST",getData:pt(u,a),onRetry:(t,n)=>{const o=`Failed to upload ${at(e.sourcemap)} | ${at(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(o),s.debug(o)}}),s.debug(`Sent ${rt(e.sourcemap)} | ${rt(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(c),await r.onIdle(),{warnings:i,errors:o}})(a,t,n,s);if(s.info(`Done uploading ${rt(e.length.toString())} sourcemaps in ${rt(O(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${ut(e.file)} | ${ut(e.sourcemap)} : ${t.message}`:t.message)).join("\n - ")}`}`;if(s.error(e),!0===t.bailOnError)throw new Error(e)}d.length>0&&s.warn(`Warnings while uploading sourcemaps:\n - ${d.join("\n - ")}`)},dt=async(e,n,s)=>{const o=t.green.bold,i=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${o(t.toString())}`)).join("\n"),r=s.time("get sourcemaps files"),a=((e,t)=>{if(!t.build.outputs||0===t.build.outputs.length)throw new Error("No output files found.");return t.build.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...et(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,n);r.end();const u=c.outdent`
2
- Uploading ${o(a.length.toString())} sourcemaps with configuration:
3
- ${i}
4
- `;s.info(u);const p=s.time("send sourcemaps");await lt(a,e.sourcemaps,n,s),p.end()},mt=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,ft=e=>{const n=t.bold.red,s=e[Qe]||{},o={errors:[]};if(s.sourcemaps){s.sourcemaps.releaseVersion||o.errors.push(`${n("sourcemaps.releaseVersion")} is required.`),s.sourcemaps.service||o.errors.push(`${n("sourcemaps.service")} is required.`),s.sourcemaps.minifiedPathPrefix||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),s.sourcemaps.minifiedPathPrefix&&((e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(s.sourcemaps.minifiedPathPrefix)||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`));const e={bailOnError:!1,disableGit:!1,dryRun:!1,maxConcurrency:20,intakeUrl:process.env.DATADOG_SOURCEMAP_INTAKE_URL||s.sourcemaps.intakeUrl||mt,...s.sourcemaps};o.config=e}return o},ht=({options:e,context:t})=>{const n=t.getLogger(Ze),s=n.time("validate options"),o=((e,t)=>{const n=[],s=ft(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${Ze}.`);const o={disabled:!e[Qe],...e[Qe],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return s.end(),o.disabled?[]:[{name:Ze,enforce:"post",async writeBundle(){if(!o.disabled&&o.sourcemaps){const e=n.time("sourcemaps process");await dt(o,t,n),e.end()}}}]};var gt=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(gt||{});const It="rum",_t="datadog-rum-plugin",Et=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,bt=(e,t)=>{const n=e.sdk;if(n.clientToken)return Et(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 s;try{const e=await Ve({url:`https://api.datadoghq.com/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});s=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!s)throw new Error("Missing clientToken in the API response.");return Et({...e,sdk:{clientToken:s,...n}})}},yt=e=>{const n=t.bold.red,s=e[It]||{},o={errors:[]};if(s.sdk){s.sdk.applicationId||o.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth?.apiKey&&e.auth?.appKey||s.sdk.clientToken||o.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const t={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};o.config={...t,...s.sdk}}return o},wt=({options:e,context:t})=>{const n=((e,t)=>{const n=[],s=yt(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${_t}.`);const o={disabled:!e[It],...e[It],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(_t)),s=[];return n.disabled||n.sdk&&(t.inject({type:"file",position:gt.MIDDLE,value:o.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:gt.MIDDLE,value:bt(n,t)})),s},Tt="telemetry",Dt="datadog-telemetry-plugin",Rt=[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};return/(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),e.value>t[e.type]?e:null}],St=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),Ot=(e="")=>e.endsWith("/")?e:`${e}/`,vt=(e,t)=>{let n=e;return e.split(Ot(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},$t=(e,t)=>e.split("!").pop().replace(Ot(t),"./"),Ut=(e,t,n)=>{let s=e.name||e.userRequest;return s||(s=((e,t)=>{let n=e.userRequest;if(!n){let s;s=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=s?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),$t(s||"no-name",n)},Ct=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),Nt=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),Mt=(e,t,n,s)=>{const o=new Set;if(s){const{timings:e}=s;e&&(e.tapables&&((e,t)=>{t.add({metric:"plugins.count",type:"count",value:e.size,tags:[]});for(const n of e.values()){let e=0,s=0;for(const o of Object.values(n.events)){let i=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;i+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:i,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]}).add({metric:"plugins.hooks.increment",type:"count",value:o.values.length,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]})}t.add({metric:"plugins.duration",type:"duration",value:e,tags:[`pluginName:${n.name}`]}).add({metric:"plugins.increment",type:"count",value:s,tags:[`pluginName:${n.name}`]})}})(e.tapables,o),e.loaders&&((e,t)=>{t.add({metric:"loaders.count",type:"count",value:e.size,tags:[]});for(const n of e.values())t.add({metric:"loaders.duration",type:"duration",value:n.duration,tags:[`loaderName:${n.name}`]}).add({metric:"loaders.increment",type:"count",value:n.increment,tags:[`loaderName:${n.name}`]})})(e.loaders,o))}((e,t)=>{const n=e.build.inputs||[],s=e.build.outputs||[],o=e.build.entries||[],i=e.build.warnings.length,r=e.build.errors.length,a=e.build.duration,u=new Map,c=new Map,p=new Map;for(const e of o){for(const t of e.inputs)u.has(t.filepath)||u.set(t.filepath,[]),u.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");p.has(n)||p.set(n,[]),p.get(n).push(e.name)}}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);t.add({metric:"assets.count",type:"count",value:s.length,tags:[]}).add({metric:"entries.count",type:"count",value:o.length,tags:[]}).add({metric:"errors.count",type:"count",value:r,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:i,tags:[]}),a&&t.add({metric:"compilation.duration",type:"duration",value:a,tags:[]});for(const e of n){const n=[`moduleName:${e.name}`,`moduleType:${e.type}`];u.has(e.filepath)&&n.push(...u.get(e.filepath).map((e=>`entryName:${e}`))),c.has(e.filepath)&&n.push(...c.get(e.filepath).map((e=>`assetName:${e}`))),t.add({metric:"modules.size",type:"size",value:e.size,tags:n}).add({metric:"modules.dependencies",type:"count",value:e.dependencies.size,tags:n}).add({metric:"modules.dependents",type:"count",value:e.dependents.size,tags:n})}for(const e of s){const n=[`assetName:${e.name}`,`assetType:${e.type}`],s=e.filepath.replace(/\.map$/,"");p.has(s)&&n.push(...p.get(s).map((e=>`entryName:${e}`))),t.add({metric:"assets.size",type:"size",value:e.size,tags:n}).add({metric:"assets.modules.count",type:"count",value:e.inputs.length,tags:n})}for(const e of o){const n=[`entryName:${e.name}`];t.add({metric:"entries.size",type:"size",value:e.size,tags:n}).add({metric:"entries.modules.count",type:"count",value:e.inputs.length,tags:n}).add({metric:"entries.assets.count",type:"count",value:e.outputs.length,tags:n})}})(e,o);for(const e of o)if(t.filters?.length){let s=e;for(const n of t.filters){if(!s)break;s=n(e)}s&&n.add(St(s,t))}else n.add(St(e,t))},Bt=async(e,t,n,s)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:i,metrics:r}=e,a=Date.now();let u="";const c={timings:!0,metrics:!0};"object"==typeof t?(u=t.destination,c.timings=t.timings||!1,c.metrics=t.metrics||!1):"string"==typeof t&&(u=t);const p=o.resolve(s,u);try{const e={},t={};c.timings&&i?.timings&&(t.timings={content:{tapables:i.timings.tapables?Array.from(i.timings.tapables.values()):null,loaders:i.timings.loaders?Array.from(i.timings.loaders.values()):null,modules:i.timings.modules?Array.from(i.timings.modules.values()):null}}),c.metrics&&(t.metrics={content:Array.from(r)});const s=Object.entries(t).map((async([t,s])=>{const i=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return w(e,n)})(o.join(p,`${t}.json`),s.content),n.debug(`Wrote ${t}.json in ${O(Date.now()-i)}`)}catch(s){n.error(`Failed to write ${t}.json in ${O(Date.now()-i)}`),e[t]=s}}));await Promise.all(s),n.debug(`Wrote files in ${O(Date.now()-a)}.`);const u=Object.keys(e);u.length&&n.error(`Couldn't write files.\n${u.map((t=>` - ${t}: ${e[t].toString()}`))}`)}catch(e){n.error(`Couldn't write files. ${e}`)}},At=t.bold.red,Lt=t.bold.cyan,kt=e=>(t,n)=>{let s,o;return"function"==typeof e?(s=e(t),o=e(n)):(s=t[e],o=n[e]),s>o?-1:s<o?1:0},Pt=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(kt("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:O(e.duration)}))),top:!0};n.sort(kt("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},jt=(e,t,n)=>{const s=[];var o;n&&(s.push(...Pt("Loader",n.timings.loaders)),s.push(...Pt("Tapable",n.timings.tapables)),s.push(...Pt("Module",n.timings.modules))),s.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},s={name:"Module size",values:[],top:!0},o={name:"Module aggregated size",values:[],top:!0},i=new Set,r=(e=>{const t={bundler:e.bundler,errors:e.errors,warnings:e.warnings,logs:e.logs,metadata:e.metadata,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})(e.build),a=new Map,u=new Map,c=new Map;for(const e of r.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,s=c.get(e)||new Set;let o=t.size;for(const e of n)o+=a.get(e)?.size||0;i.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!i.size)return[t,n,s];const p=Array.from(i);return p.sort(kt((e=>e.dependents.size))),t.values=p.map((e=>({name:e.name,value:e.dependents.size.toString()}))),p.sort(kt((e=>e.dependencies.size))),n.values=p.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),p.sort(kt("size")),s.values=p.map((e=>({name:e.name,value:m(e.size)}))),p.sort(kt("aggregatedSize")),o.values=p.map((e=>({name:e.name,value:m(e.aggregatedSize||e.size)}))),[t,n,s,o]})(e)),s.push(...(o=e,[{name:"Asset size",values:(o.build.outputs||[]).filter((e=>"map"!==e.type)).sort(kt((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(kt((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(kt((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),s.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,s=e.build.outputs?e.build.outputs.length:0,o=e.build.warnings.length,i=e.build.errors.length,r=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:O(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:O(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:O(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:s.toString()},{name:"Number of entries",value:r.toString()},{name:"Number of warnings",value:o.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=v(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),s=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),i=Math.max(n+4,s+o+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=o-e.value.length;t+=` [${At(e.value)}] ${" ".repeat(n)}${Lt(e.name)}\n`}}return t})(s);t.info(i)},xt=["onStart","onLoad","onResolve","onEnd"],Gt=new Map,Ht=new Map,Ft=(e,t,n)=>{const s=Object.assign({},e);for(const o of xt)s[o]=async(s,i)=>{const r=Gt.get(t)||{name:t,increment:0,duration:0,events:{}};r.events[o]=r.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=$t(e[0].path,n),a=Ht.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=f.performance.now();try{return await i(...e)}finally{const n=f.performance.now(),i=n-u,c={start:u,end:n,duration:i,context:Nt(e)};r.events[o].values.push(c),r.duration+=i,r.increment+=1,Gt.set(t,r),a.events[o].values.push(c),a.duration+=i,a.increment+=1,Ht.set(s,a)}}))};return s},zt=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0;const o=n.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(Dt))continue;const n=s.setup;s.setup=async o=>{const i=Ft(o,s.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(s,t.cwd),o.end(),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const s=n.time("getting plugins results"),{plugins:o,modules:i}={plugins:Gt,modules:Ht};s.end(),e.report={timings:{tapables:o,modules:i}}}))}});class Kt{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=Ut(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(Ct))(e);s.length||s.push("no-loader"),this.started[n]={module:vt(n),timings:{start:f.performance.now(),duration:0,end:0},loaders:s}}doneModule(e,t){const n=Ut(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=f.performance.now(),s.timings.duration=s.timings.end-s.timings.start,this.finished.push(s),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const s=n.timings.end-n.timings.start,o=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},i=n.loaders.join(",");o.events[i]=o.events[i]||{name:i,values:[]},o.events[i].values.push(n.timings),o.increment+=1,o.duration+=s,t.set(n.module,o);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=s,e.set(t,n)}}return{loaders:e,modules:t}}}class Yt{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,i){const r=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};r.events[n]||(r.events[n]={name:n,values:[]}),r.events[n].values.push({start:o,end:i,duration:i-o,context:s,type:e}),r.duration+=i-o,r.increment+=1,this.timings.set(t,r)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const s=n;s.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,s)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=f.performance.now(),r=t.apply(this,o),a=()=>{this.saveResult(e,n,s,Nt(o),i,f.performance.now())};return r.then(a,a),r}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=f.performance.now(),r=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,Nt(o),i,f.performance.now()),r(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=f.performance.now(),r=t.apply(this,o);return this.saveResult(e,n,s,Nt(o),i,f.performance.now()),r}}getTapPatch(e,t,n,s){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,s);case"async":return this.getAsyncTapPatch(e,t,n,s);default:return this.getDefaultTapPatch(e,t,n,s)}}newTap(e,t,n,s){return(o,i)=>{const r="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${r}`;if(this.monitoredTaps[u])return n.call(s,o,i);this.monitoredTaps[u]=!0;const c=this.getTapPatch(e,i,r,t);return n.call(s,o,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(Dt)||(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 s of n)this.patchHook(t,s,e.hooks[s])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const Vt=(e,t)=>async n=>{const s=t.getLogger(Dt);t.build.start=Date.now();const o={name:Dt},i=new Yt(t.cwd),r=new Kt(t.cwd),a=s.time("parse compiler hooks");i.throughHooks(n),a.end(),n.hooks.thisCompilation.tap(o,(e=>{const t=s.time("parse compilation hooks");i.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{r.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{r.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{r.doneModule(t,e)}))})),n.hooks.afterEmit.tapPromise(o,(async t=>{const{timings:n}=i.getResults(),{loaders:s,modules:o}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:o}}}))},Jt={filters:Rt},qt=({options:e,context:t})=>{const n=t.getLogger(Dt);let s=0;const o={start:Date.now()},i=(e=>{const t=e[Tt]?.endPoint||"https://app.datadoghq.com";return{disabled:!e[Tt],enableTracing:!1,filters:Rt,output:!1,prefix:"",tags:[],...e[Tt],endPoint:t.startsWith("http")?t:`https://${t}`}})(e),r=[];if(i.disabled)return r;const a={name:Dt,enforce:"pre",esbuild:zt(o,t,n),webpack:Vt(o,t),rspack:Vt(o,t)},u=n.time("build",{start:!1}),c={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now()},buildEnd(){u.end(),s=Date.now()},async writeBundle(){t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-s;const e=new Set,r=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(i),a=n.time("aggregating metrics");Mt(t,r,e,o.report),a.end();const u=n.time("writing to files");await Bt({report:o.report,metrics:e},i.output,n,t.bundler.outDir),u.end();const c=n.time("outputing report");jt(t,n,o.report),c.end();const p=n.time("sending metrics to Datadog");await((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.info("No metrics to send.");const s=new Map;for(const t of e)s.has(t.metric)||s.set(t.metric,0),s.set(t.metric,s.get(t.metric)+1);const o=Array.from(s.entries()).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${o.join("\n - ")}`),Ve({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:i.endPoint},n),p.end()}};return i.enableTracing&&r.push(a),r.push(c),r},Wt="datadog-analytics-plugin",Xt=e=>{const{context:t}=e,n=e.context.getLogger(Wt);return t.sendLog=async(e,s={})=>{if("production"===t.env)try{const n={name:t.bundler.name,version:t.bundler.version};await Ve({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:`@datadog/${n.name}-plugin`,env:t.env,message:e,service:"build-plugins",bundler:n,plugins:t.pluginNames,version:t.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){n.debug(`Could not submit data to Datadog: ${e}`)}},[{name:Wt,async buildStart(){await t.sendLog("Build started")}}]},Qt=(e,t)=>{const n=(e=>{let t,n=Se(process.cwd(),e),i=n.split(o.sep).length;for(;i>0;){const e=o.resolve(n,"package.json");s.existsSync(e)&&(t=n),n=n.split(o.sep).slice(0,-1).join(o.sep),i--}return t})(t);if(n)return n;const i=(e=>{const t=[...e].map((e=>Se(process.cwd(),e).split(o.sep))),n=Math.min(...t.map((e=>e.length))),s=[];for(let e=0;e<n;e++){const n=t[0][e];if(!t.every((t=>t[e]===n)))break;s.push(n)}return s.length>0&&s.join(o.sep)||o.sep})(Array.from(e));return i!==o.sep?i:void 0},Zt=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),e.hook("bundlerReport",e.bundler),t.options.context&&(e.cwd=t.options.context),e.hook("cwd",e.cwd)},en=e=>{const{context:t}=e,n=new Set,s=e=>{e&&(e.dir?(t.bundler.outDir=e.dir,n.add(e.dir)):e.file&&(t.bundler.outDir=o.dirname(e.file),n.add(t.bundler.outDir)),t.bundler.outDir=Se(process.cwd(),t.bundler.outDir),"vite"!==t.bundler.name&&(t.cwd=Qt(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)))},i=()=>({options(e){if(t.bundler.rawConfig=e,e.input)if(Array.isArray(e.input))for(const t of e.input)n.add(o.dirname(t));else if("object"==typeof e.input)for(const t of Object.values(e.input))n.add(o.dirname(t));else{if("string"!=typeof e.input)throw new Error("Invalid input type");n.add(o.dirname(e.input))}if("output"in e){const t=Array.isArray(e.output)?e.output:[e.output];for(const e of t)s(e)}t.hook("bundlerReport",t.bundler)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.outdir&&(t.bundler.outDir=e.initialOptions.outdir),e.initialOptions.outfile&&(t.bundler.outDir=o.dirname(e.initialOptions.outfile)),t.hook("bundlerReport",t.bundler),e.initialOptions.absWorkingDir&&(t.cwd=e.initialOptions.absWorkingDir),t.hook("cwd",t.cwd),e.initialOptions.metafile=!0}},webpack:Zt(t),rspack:Zt(t),vite:{...i(),config(e){e.root?t.cwd=e.root:t.cwd=Qt(n,t.bundler.outDir)||t.cwd,e.build?.outDir&&(t.bundler.outDir=e.build.outDir),t.hook("cwd",t.cwd)}},rollup:i()}]},tn="datadog-custom-hooks-plugin",nn=e=>{const{context:t}=e,n=t.getLogger(tn),s=e=>(s,...o)=>{const i=n.time(`execution | ${s}`),r=[],a=[];for(const n of t.plugins){if(!(s in n))continue;const t=n[s];if("function"==typeof t)try{const i=t(...o);i instanceof Promise&&(e||r.push(`Plugin "${n.name}" returned a promise on the non async hook "${s}".`),a.push(i))}catch(e){r.push(`Plugin "${n.name}" errored on hook "${s}". [${e}]`)}else r.push(`Plugin "${n.name}" has an invalid hook type for "${s}". [${typeof t}]`)}if(r.length>0){for(const e of r)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=s(!1),t.asyncHook=s(!0),[{name:tn,enforce:"pre"}]};class sn{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=s.readFileSync(e,"utf8"),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const i=o.sources;if(0===i.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(i);if(0!==r.length)return r;t(`${i.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const s of e){const e=this.getFilename(s);if(n.has(e))continue;n.add(e);const o=this.trackedFilenames.get(e);o&&(t=t.concat(o))}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 on=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await rn(e);for(const e of t)if(e.name===n)return $(e.refs.push);return $(t[0].refs.push)},rn=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},an=async e=>e.revparse("HEAD"),un=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),cn=async e=>e.branch(),pn=async e=>e.show(["-s","--format=%s"]),ln=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),dn="datadog-git-plugin",mn=e=>{const{options:t,context:n}=e,s=n.getLogger(dn);return[{name:dn,enforce:"pre",async buildStart(){if(S(t))try{const e=s.time("get git information"),t=await(async e=>{const t=[an(e),cn(e),pn(e),ln(e),un(e),on(e)],[n,s,o,i,r,a]=await Promise.all(t),[u,c,p,l,d,m]=i.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:c,date:p},committer:{name:l,email:d,date:m},message:o.trim(),hash:n},branch:s.current,remote:a.trim(),trackedFilesMatcher:new sn(r)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=h.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return h.simpleGit(t)})(n.cwd));n.git=t,e.end(),await n.asyncHook("git",n.git)}catch(e){s.error(`Could not get git information: ${e.message}`)}}}]},fn="datadog-injection-plugin",hn=/^https?:\/\//,gn=async(e,t,s=process.cwd())=>{let o;const i=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)o=i.match(hn)?await(async(e,t=5e3)=>{let n;return Promise.race([Ve({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(i):await(async(e,t=process.cwd())=>{const s=Se(t,e);return n.readFile(s,{encoding:"utf-8"})})(i,s);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);o=i}}catch(n){const s=`${e.type} - ${v(i)}`;e.fallback?(t.info(`Fallback for "${s}": ${n.toString()}`),o=await gn(e.fallback,t)):(t.warn(`Failed "${s}": ${n.toString()}`),o="")}return o},In=e=>{if(0===e.size)return"";return`// begin injection by Datadog build plugins\n${Array.from(e.values()).map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},_n=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,i]of e.entries()){const e=await gn(i,t,n);e&&s.set(o,{value:e,position:i.position||gt.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},En=s.promises,bn=(e,t,n)=>({setup(i){const{onStart:r,onResolve:a,onLoad:u,onEnd:c,esbuild:p,initialOptions:l}=i,d=[],m=`${N()}.${gt.MIDDLE}.${E}.js`,f=s.realpathSync(g.tmpdir()),h=o.resolve(f,m),I=new RegExp(`${m}$`),_=l.inject;l.inject=_?[..._]:[],l.inject.push(h),r((async()=>{d.push(...await Re(i,t,e)),i.initialOptions.inject=_;try{await w(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:I},(async e=>({path:e.path,namespace:fn}))),u({filter:I,namespace:fn},(async()=>({contents:In(n[gt.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),c((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=In(n[gt.BEFORE]),i=In(n[gt.AFTER]);if(!o&&!i)return;const r=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?Se(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await En.readFile(e,"utf-8"),n=await p.transform(t,{loader:"default",banner:o,footer:i});await En.writeFile(e,n.code)}));await Promise.all(r)}))}}),yn=E,wn="?inject-proxy",Tn=e=>({banner:t=>t.isEntry?In(e[gt.BEFORE]):"",async resolveId(t,n,s){if(R(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&In(e[gt.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${wn}`}return null},load(t){if(R(t))return In(e[gt.MIDDLE]);if(t.endsWith(wn)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(yn)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?In(e[gt.AFTER]):""}),Dn=(e,t,n,i,r)=>a=>{const u=new WeakMap,c=(e=>{if(!e?.sources?.ConcatSource)return I.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),p=o.resolve(n.bundler.outDir,`${N()}.${gt.MIDDLE}.${E}.js`);T(p,"");const l=()=>{var e;e=p,s.rmSync(e,{force:!0,maxRetries:3,recursive:!0})};a.hooks.shutdown?a.hooks.shutdown.tap(fn,l):(a.hooks.done.tap(fn,l),a.hooks.failed.tap(fn,l));a.hooks.beforeRun.tapPromise(fn,(async()=>{await _n(t,i,r,n.cwd)})),a.hooks.compilation.tap(fn,(t=>{const n=()=>{const e=In(r[gt.BEFORE]),n=In(r[gt.AFTER]);for(const s of t.chunks)if(s.canBeInitial())for(const o of s.files)t.updateAsset(o,(t=>{const s=u.get(t);if(!s||s.banner!==e||s.footer!==n){const s=new c(e,"\n",t,"\n",n);return u.set(t,{source:s,banner:e,footer:n}),s}return s.source}))};if(t.hooks.processAssets){const s=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;t.hooks.processAssets.tap({name:fn,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:fn},n)}));const d=(e=>{const s="webpack4"===n.bundler.fullName?p:{import:[p]},o=e=>{for(const[n,s]of Object.entries(e))"object"==typeof s?(s.import=s.import||[],s.import.unshift(p)):"string"==typeof s?e[n]=[p,s]:Array.isArray(s)?s.unshift(p):t.error("Invalid entry type: "+typeof s)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[s,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:s}})(a.options.entry);a.options.entry=d},Rn=e=>{const{bundler:t,context:n}=e,s=n.getLogger(fn),o=new Map,i={[gt.BEFORE]:new Map,[gt.MIDDLE]:new Map,[gt.AFTER]:new Map};n.inject=e=>{o.set(N(),e)};const r={name:fn,enforce:"post",esbuild:bn(s,n,i),webpack:Dn(t,s,n,o,i),rspack:Dn(t,s,n,o,i),rollup:Tn(i),vite:{...Tn(i),enforce:"pre"}};var a;return a=n.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(a)?(r.loadInclude=e=>!!R(e)||null,r.load=e=>R(e)?{code:In(i[gt.MIDDLE])}:null):r.buildStart=async()=>{await _n(s,o,i,n.cwd)},[r]},Sn="datadog-true-end-plugin",On=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},s=()=>{t.hook("syncTrueEnd")},o=async()=>{s(),await n()},i=e=>{e.hooks.shutdown?e.hooks.shutdown.tapPromise(Sn,o):(e.hooks.done.tapPromise(Sn,o),e.hooks.failed.tap(Sn,s))},r={async writeBundle(){},async closeBundle(){await o()}};return[{name:Sn,enforce:"post",webpack:i,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{s()}))}},vite:r,rollup:r,rspack:i}]},vn={[Tt]:Jt};var $n="2.5.4-dev-1";const Un=(({bundler:n,version:s})=>{const o=Date.now();return e.createUnplugin(((e,i)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",metadata:{},...e}))(e);"esbuild"===i.framework&&(i.esbuildHostName=y);const a=(({start:e,options:t,bundlerName:n,bundlerVersion:s,version:o})=>{const i=process.cwd(),r="webpack"===n?s.split(".")[0]:"",a={errors:[],warnings:[],logs:[],metadata:t.metadata||{},timings:[],bundler:{name:n,fullName:`${n}${r}`,variant:r,version:s}},u=process.env.BUILD_PLUGINS_ENV||"production",c=b.includes(u)?u:"development";return{auth:t.auth,pluginNames:[],bundler:{...a.bundler,outDir:i},build:a,cwd:i,env:c,getLogger:B(a,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.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},plugins:[],start:e,version:o}})({start:o,options:r,bundlerVersion:n.version||n.VERSION,bundlerName:i.framework,version:s}),u=a.getLogger("factory").time("Plugins initialization",{start:o});a.pluginNames.push(y);const c=[];c.push(["analytics",Xt],["build-report",je],["bundler-report",en],["custom-hooks",nn],["git",mn],["injection",Rn],["true-end",On]),r.customPlugins&&c.push(["custom",r.customPlugins]),c.push(["ci-visibility",Xe],["error-tracking",ht],["rum",wt],["telemetry",qt]);for(const[e,t]of c)a.plugins.push(...k(a,t,e)({bundler:n,context:a,options:r}));a.pluginNames.push(...a.plugins.map((e=>e.name)));const p=new Set(a.pluginNames.filter((e=>a.pluginNames.filter((t=>t===e)).length>1)));if(p.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(p).join(", "))}`);return a.hook("init",a),u.end(),a.plugins}))})({bundler:_,version:$n}).esbuild,Cn=$n,Nn=vn;exports.datadogEsbuildPlugin=Un,exports.helpers=Nn,exports.version=Cn;
1
+ "use strict";var e=require("unplugin"),t=require("chalk"),n=require("fs/promises"),s=require("fs"),o=require("path"),i=require("outdent"),r=require("async-retry"),a=require("buffer"),u=require("p-queue"),p=require("stream"),c=require("zlib"),l=require("pretty-bytes"),d=require("perf_hooks"),m=require("glob"),f=require("simple-git"),h=require("os"),g=require("module"),w=require("esbuild");const y="__datadog-helper-file",b=["development","production","test"],v="datadog-build-plugins",$=async(e,t)=>{await(async e=>n.mkdir(e,{recursive:!0}))(o.dirname(e)),await n.writeFile(e,t,{encoding:"utf-8"})},k=(e,t)=>{var n;n=o.dirname(e),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(e,t,{encoding:"utf-8"})},S=e=>e.replace(/^@dd\/(datadog-|internal-)?|^datadog-|-plugin$/g,""),D=e=>e.includes(y),E=e=>{const t=Math.floor(e/1e3/60/60/24),n=new Date(e-24*t*60*60*1e3),s=n.getUTCHours(),o=n.getUTCMinutes(),i=n.getUTCSeconds(),r=n.getUTCMilliseconds(),a=`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${i?`${i}s`:""}`.trim();return`${a}${!a||r?` ${r}ms`:""}`.trim()},P=(e,t=60,n="[...]")=>{if(e.length<=t)return e;const s=Math.max(4,t-n.length),o=Math.min(10,Math.floor(s/2)),i=s-o;return`${e.slice(0,o)}${n}${e.slice(-i)}`},M=(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}};let x=0;const T=()=>`${Date.now()}.${performance.now()}.${++x}`,j={debug:0,info:1,warn:2,error:3,none:4},z=(e,n="warn")=>s=>{const o=(e=>e.split(">").map(S).join(">"))(s),i=(i,r="debug")=>{let a=t.dim,u=console.log;"error"===r?(a=t.red,u=console.error):"warn"===r?(a=t.yellow,u=console.warn):"info"===r&&(a=t.cyan,u=console.log);const p=`[${e.metadata?.name?`${e.metadata.name}|`:""}${r}|${e.bundler.fullName}|${o}]`,c="string"==typeof i?i:JSON.stringify(i,null,2);e.logs.push({bundler:e.bundler.fullName,pluginName:s,type:r,message:c,time:Date.now()}),"error"===r&&e.errors.push(c),"warn"===r&&e.warnings.push(c),j[r]>=j[n]&&u(`${a(p)} ${c}`)};return{getLogger:t=>z(e,n)(`${o}>${t}`),time:(n,o={})=>{const{level:r="debug",start:a=!0,log:u=!0,tags:p=[]}=o,c={pluginName:s,label:n,spans:[],tags:[...p,`plugin:${s}`,`level:${r}`],logLevel:r,total:0};e.timings.push(c);const l=()=>c.spans.filter((e=>!e.end)),d=e=>{l().length||(!c.spans.length&&u&&i(t.dim(`[${t.cyan(n)}] : start`),"debug"),c.spans.push({start:e||Date.now(),tags:[`plugin:${s}`]}))},m=e=>{const s=l();if(s?.length){s.length>1&&i(`Timer ${t.cyan(n)} has more than one ongoing span.`,"debug");for(const t of s)t.end=e||Date.now()}else i(`Timer ${t.cyan(n)} cannot be paused, no ongoing span.`,"debug")};if(a){let e;"number"==typeof a&&(e=a),d(e)}return{timer:c,resume:d,end:e=>{m(e);const s=c.spans.reduce(((e,t)=>e+(t.end-t.start)),0);c.total=s,u&&i(`[${t.cyan(n)}] : ${t.cyan(E(s))}`,r)},pause:m,tag:(e,t={})=>{const{span:n=!1}=t;if(n){const t=l();for(const n of t)n.tags.push(...e)}else c.tags.push(...e)}}},error:e=>i(e,"error"),warn:e=>i(e,"warn"),info:e=>i(e,"info"),debug:e=>i(e,"debug")}},O=["buildEnd","buildStart","load","loadInclude","resolveId","transform","transformInclude","watchChange","writeBundle","cwd","init","buildReport","bundlerReport","git"],N=(e,t,n,s)=>(...o)=>{const i=s.time(`${e} | ${t}`,{log:!1,tags:["type:hook",`hook:${t}`]}),r=n(...o);return r instanceof Promise?r.finally((()=>{i.end()})):(i.end(),r)},R=(e,t,n)=>{const s=e.getLogger(v);return e=>{const o=s.time(`hook | init ${n}`,{log:!1}),i=t(e).map((e=>((e,t)=>{const n={...e},s=S(e.name);for(const o of O){const i=e[o];i&&(n[o]=N(s,o,i,t))}return n})(e,s))),r=i.map((e=>`plugin:${e.name}`));return o.tag(r),o.end(),i}},I="errorTracking",A="datadog-error-tracking-plugin",F=(e,n,s)=>{if(".map"!==o.extname(s))throw new Error(`The file ${t.green.bold(s)} is not a sourcemap.`);const i=s.replace(/\.map$/,""),r=i.replace(n.bundler.outDir,"");return{minifiedFilePath:i,minifiedUrl:e.minifiedPathPrefix?o.join(e.minifiedPathPrefix,r):r,relativePath:r}},C=[400,403,413],L=e=>{const{auth:t,url:n,method:s="GET",getData:o,type:i="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return r((async(e,r)=>{let a;try{const e={method:s,duplex:"half"};let i={"X-Datadog-Origin":"build-plugins"};if(t?.apiKey&&(i["DD-API-KEY"]=t.apiKey),t?.appKey&&(i["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof o){const{data:t,headers:n}=await o();e.body=t,i={...i,...n}}a=await fetch(n,{...e,headers:i})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(C.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)},_=/[/]+|[\\]+/g,q=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,H=(e,t)=>{const n=e.replace(q,"").split(_),s=t.replace(q,"").split(_),o=n.join("/");let i="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(i=t)}return i},B=async e=>{const t={empty:!1,exists:!0};try{0===(await s.promises.stat(e)).size&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},K=async(e,t,n,s)=>{const i=await(async(e,t)=>{const[n,s]=await Promise.all([B(e.minifiedFilePath),B(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:H(e.relativePath,t)}})(e,n),r=[],a=[],u=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(s)try{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:s.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${o.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:s.hash,repository_url:s.remote}],version:1})})}catch(t){a.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return i.file.empty&&r.push(`Minified file is empty: ${e.minifiedFilePath}`),i.file.exists||r.push(`Minified file not found: ${e.minifiedFilePath}`),i.sourcemap.empty&&r.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),i.sourcemap.exists||r.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),i.repeatedPrefix&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${i.repeatedPrefix}`),{content:u,errors:r,warnings:a}},W=t.green.bold,U=t.yellow.bold,G=t.red.bold,J=async(e,t)=>{if("function"==typeof s.openAsBlob){const n=await s.openAsBlob(e,{type:t.contentType});return new a.File([n],t.filename)}{const n=p.Readable.toWeb(s.createReadStream(e)),o=await new Response(n).blob();return new a.File([o],t.filename,{type:t.contentType})}},V=(e,t={})=>async()=>{const n=new FormData,s=c.createGzip();for(const[t,s]of e.content){const e="file"===s.type?await J(s.path,s.options):new Blob([s.value],{type:s.options.contentType});n.append(t,e,s.options.filename)}const o=new Request("fake://url",{method:"POST",body:n});return{data:p.Readable.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},Y=async(e,t,n,s)=>{const o=Date.now(),i=t.minifiedPathPrefix,r={git_repository_url:n.git?.remote,git_commit_sha:n.git?.hash,plugin_version:n.version,project_path:n.bundler.outDir,service:t.service,type:"js_sourcemap",version:t.releaseVersion},a=await Promise.all(e.map((e=>K(e,r,i,n.git)))),p=a.map((e=>e.errors)).flat(),c=a.map((e=>e.warnings)).flat();if(c.length>0&&s.warn(`Warnings while preparing payloads:\n - ${c.join("\n - ")}`),p.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${p.join("\n - ")}`;if(s.error(e),!0===t.bailOnError)throw new Error(e);return}const{errors:l,warnings:d}=await(async(e,t,n,s)=>{const o=[],i=[];if(!n.auth?.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:i};if(0===e.length)return i.push("No sourcemaps to upload"),{errors:o,warnings:i};const r=new(u.default?u.default:u)({concurrency:t.maxConcurrency}),a={"DD-EVP-ORIGIN":`${n.bundler.fullName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},p=[];for(const u of e){const e={sourcemap:u.content.get("source_map")?.path.replace(n.bundler.outDir,"."),file:u.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${W(e.sourcemap)} | ${W(e.file)}`),p.push(r.add((async()=>{try{await L({auth:{apiKey:n.auth.apiKey},url:t.intakeUrl,method:"POST",getData:V(u,a),onRetry:(t,n)=>{const o=`Failed to upload ${U(e.sourcemap)} | ${U(e.file)}:\n ${t.message}\nRetrying ${n}/5`;i.push(o),s.debug(o)}}),s.debug(`Sent ${W(e.sourcemap)} | ${W(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(p),await r.onIdle(),{warnings:i,errors:o}})(a,t,n,s);if(s.info(`Done uploading ${W(e.length.toString())} sourcemaps in ${W(E(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${G(e.file)} | ${G(e.sourcemap)} : ${t.message}`:t.message)).join("\n - ")}`}`;if(s.error(e),!0===t.bailOnError)throw new Error(e)}d.length>0&&s.warn(`Warnings while uploading sourcemaps:\n - ${d.join("\n - ")}`)},Q=async(e,n,s)=>{const o=t.green.bold,r=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${o(t.toString())}`)).join("\n"),a=s.time("get sourcemaps files"),u=((e,t)=>{if(!t.build.outputs||0===t.build.outputs.length)throw new Error("No output files found.");return t.build.outputs.filter((e=>e.filepath.endsWith(".map"))).map((e=>e.filepath)).map((n=>({...F(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,n);a.end();const p=i.outdent`
2
+ Uploading ${o(u.length.toString())} sourcemaps with configuration:
3
+ ${r}
4
+ `;s.info(p);const c=s.time("send sourcemaps");await Y(u,e.sourcemaps,n,s),c.end()},X=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,Z=e=>{const n=t.bold.red,s=e[I]||{},o={errors:[]};if(s.sourcemaps){s.sourcemaps.releaseVersion||o.errors.push(`${n("sourcemaps.releaseVersion")} is required.`),s.sourcemaps.service||o.errors.push(`${n("sourcemaps.service")} is required.`),s.sourcemaps.minifiedPathPrefix||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} is required.`),s.sourcemaps.minifiedPathPrefix&&((e=>{let t;try{t=new URL(e).host}catch{}return!(!t&&!e.startsWith("/"))})(s.sourcemaps.minifiedPathPrefix)||o.errors.push(`${n("sourcemaps.minifiedPathPrefix")} must be a valid URL or start with '/'.`));const e={bailOnError:!1,disableGit:!1,dryRun:!1,maxConcurrency:20,intakeUrl:process.env.DATADOG_SOURCEMAP_INTAKE_URL||s.sourcemaps.intakeUrl||X,...s.sourcemaps};o.config=e}return o},ee=({options:e,context:t})=>{const n=t.getLogger(A),s=n.time("validate options"),o=((e,t)=>{const n=[],s=Z(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${A}.`);const o={disabled:!e[I],...e[I],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return s.end(),o.disabled?[]:[{name:A,enforce:"post",async writeBundle(){if(!o.disabled&&o.sourcemaps){const e=n.time("sourcemaps process");await Q(o,t,n),e.end()}}}]};var te=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(te||{});const ne="rum",se="datadog-rum-plugin",oe=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,ie=(e,t)=>{const n=e.sdk;if(n.clientToken)return oe(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 s;try{const e=await L({url:`https://api.datadoghq.com/api/v2/rum/applications/${n.applicationId}`,type:"json",auth:t.auth});s=e.data?.attributes?.client_token}catch(e){throw new Error(`Could not fetch the clientToken: ${e.message}`)}if(!s)throw new Error("Missing clientToken in the API response.");return oe({...e,sdk:{clientToken:s,...n}})}},re=e=>{const n=t.bold.red,s=e[ne]||{},o={errors:[]};if(s.sdk){s.sdk.applicationId||o.errors.push(`Missing ${n("applicationId")} in the SDK configuration.`),e.auth?.apiKey&&e.auth?.appKey||s.sdk.clientToken||o.errors.push(`Missing ${n('"auth.apiKey"')} and/or ${n('"auth.appKey"')} to fetch missing client token.`);const t={applicationId:"unknown_application_id",allowUntrustedEvents:!1,compressIntakeRequests:!1,defaultPrivacyLevel:"mask",enablePrivacyForActionName:!1,sessionReplaySampleRate:0,sessionSampleRate:100,silentMultipleInit:!1,site:"datadoghq.com",startSessionReplayRecordingManually:!1,storeContextsAcrossPages:!1,telemetrySampleRate:20,traceSampleRate:100,trackingConsent:"granted",trackLongTasks:!1,trackResources:!1,trackUserInteractions:!1,trackViewsManually:!1};o.config={...t,...s.sdk}}return o},ae=({options:e,context:t})=>{const n=((e,t)=>{const n=[],s=re(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${se}.`);const o={disabled:!e[ne],...e[ne],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(se)),s=[];return n.disabled||n.sdk&&(t.inject({type:"file",position:te.MIDDLE,value:o.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:te.MIDDLE,value:ie(n,t)})),s},ue="telemetry",pe="datadog-telemetry-plugin",ce=[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};return/(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),e.value>t[e.type]?e:null}],le=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),de=(e="")=>e.endsWith("/")?e:`${e}/`,me=(e,t)=>{let n=e;return e.split(de(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},fe=(e,t)=>e.split("!").pop().replace(de(t),"./"),he=(e,t,n)=>{let s=e.name||e.userRequest;return s||(s=((e,t)=>{let n=e.userRequest;if(!n){let s;s=t.moduleGraph&&"function"==typeof t.moduleGraph.getIssuer?t.moduleGraph.getIssuer(e):e.issuer,n=s?.userRequest,n||(n=e._identifier?.split("!").pop())}return n||"unknown"})(e,t)),fe(s||"no-name",n)},ge=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),we=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),ye=(e,t,n,s)=>{const o=new Set;if(s){const{timings:e}=s;e&&(e.tapables&&((e,t)=>{t.add({metric:"plugins.count",type:"count",value:e.size,tags:[]});for(const n of e.values()){let e=0,s=0;for(const o of Object.values(n.events)){let i=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;i+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:i,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]}).add({metric:"plugins.hooks.increment",type:"count",value:o.values.length,tags:[`pluginName:${n.name}`,`hookName:${o.name}`]})}t.add({metric:"plugins.duration",type:"duration",value:e,tags:[`pluginName:${n.name}`]}).add({metric:"plugins.increment",type:"count",value:s,tags:[`pluginName:${n.name}`]})}})(e.tapables,o),e.loaders&&((e,t)=>{t.add({metric:"loaders.count",type:"count",value:e.size,tags:[]});for(const n of e.values())t.add({metric:"loaders.duration",type:"duration",value:n.duration,tags:[`loaderName:${n.name}`]}).add({metric:"loaders.increment",type:"count",value:n.increment,tags:[`loaderName:${n.name}`]})})(e.loaders,o))}((e,t)=>{const n=e.build.inputs||[],s=e.build.outputs||[],o=e.build.entries||[],i=e.build.warnings.length,r=e.build.errors.length,a=e.build.duration,u=new Map,p=new Map,c=new Map;for(const e of o){for(const t of e.inputs)u.has(t.filepath)||u.set(t.filepath,[]),u.get(t.filepath).push(e.name);for(const t of e.outputs){const n=t.filepath.replace(/\.map$/,"");c.has(n)||c.set(n,[]),c.get(n).push(e.name)}}for(const e of s)for(const t of e.inputs)p.has(t.filepath)||p.set(t.filepath,[]),p.get(t.filepath).push(e.name);t.add({metric:"assets.count",type:"count",value:s.length,tags:[]}).add({metric:"entries.count",type:"count",value:o.length,tags:[]}).add({metric:"errors.count",type:"count",value:r,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:i,tags:[]}),a&&t.add({metric:"compilation.duration",type:"duration",value:a,tags:[]});for(const e of n){const n=[`moduleName:${e.name}`,`moduleType:${e.type}`];u.has(e.filepath)&&n.push(...u.get(e.filepath).map((e=>`entryName:${e}`))),p.has(e.filepath)&&n.push(...p.get(e.filepath).map((e=>`assetName:${e}`))),t.add({metric:"modules.size",type:"size",value:e.size,tags:n}).add({metric:"modules.dependencies",type:"count",value:e.dependencies.size,tags:n}).add({metric:"modules.dependents",type:"count",value:e.dependents.size,tags:n})}for(const e of s){const n=[`assetName:${e.name}`,`assetType:${e.type}`],s=e.filepath.replace(/\.map$/,"");c.has(s)&&n.push(...c.get(s).map((e=>`entryName:${e}`))),t.add({metric:"assets.size",type:"size",value:e.size,tags:n}).add({metric:"assets.modules.count",type:"count",value:e.inputs.length,tags:n})}for(const e of o){const n=[`entryName:${e.name}`];t.add({metric:"entries.size",type:"size",value:e.size,tags:n}).add({metric:"entries.modules.count",type:"count",value:e.inputs.length,tags:n}).add({metric:"entries.assets.count",type:"count",value:e.outputs.length,tags:n})}})(e,o);for(const e of o)if(t.filters?.length){let s=e;for(const n of t.filters){if(!s)break;s=n(e)}s&&n.add(le(s,t))}else n.add(le(e,t));n.add(le({metric:"metrics.count",type:"count",value:n.size+1,tags:[]},t))},be=async(e,t,n,s)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:i,metrics:r}=e,a=Date.now();let u="";const p={timings:!0,metrics:!0};"object"==typeof t?(u=t.destination,p.timings=t.timings||!1,p.metrics=t.metrics||!1):"string"==typeof t&&(u=t);const c=o.resolve(s,u);try{const e={},t={};p.timings&&i?.timings&&(t.timings={content:{tapables:i.timings.tapables?Array.from(i.timings.tapables.values()):null,loaders:i.timings.loaders?Array.from(i.timings.loaders.values()):null,modules:i.timings.modules?Array.from(i.timings.modules.values()):null}}),p.metrics&&(t.metrics={content:Array.from(r)});const s=Object.entries(t).map((async([t,s])=>{const i=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return $(e,n)})(o.join(c,`${t}.json`),s.content),n.debug(`Wrote ${t}.json in ${E(Date.now()-i)}`)}catch(s){n.error(`Failed to write ${t}.json in ${E(Date.now()-i)}`),e[t]=s}}));await Promise.all(s),n.debug(`Wrote files in ${E(Date.now()-a)}.`);const u=Object.keys(e);u.length&&n.error(`Couldn't write files.\n${u.map((t=>` - ${t}: ${e[t].toString()}`))}`)}catch(e){n.error(`Couldn't write files. ${e}`)}},ve=t.bold.red,$e=t.bold.cyan,ke=e=>(t,n)=>{let s,o;return"function"==typeof e?(s=e(t),o=e(n)):(s=t[e],o=n[e]),s>o?-1:s<o?1:0},Se=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(ke("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:E(e.duration)}))),top:!0};n.sort(ke("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},De=(e,t,n)=>{const s=[];var o;n&&(s.push(...Se("Loader",n.timings.loaders)),s.push(...Se("Tapable",n.timings.tapables)),s.push(...Se("Module",n.timings.modules))),s.push(...(e=>{const t={name:"Module total dependents",values:[],top:!0},n={name:"Module total dependencies",values:[],top:!0},s={name:"Module size",values:[],top:!0},o={name:"Module aggregated size",values:[],top:!0},i=new Set,r=(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})(e.build),a=new Map,u=new Map,p=new Map;for(const e of r.inputs||[]){if("map"===e.type)continue;const t=new Set(e.dependencies),n=new Set(e.dependents);for(const n of t)p.has(n)||p.set(n,new Set),p.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(p.has(e.filepath)){const t=p.get(e.filepath);for(const e of t)n.add(e)}u.set(e.filepath,t),p.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,s=p.get(e)||new Set;let o=t.size;for(const e of n)o+=a.get(e)?.size||0;i.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!i.size)return[t,n,s];const c=Array.from(i);return c.sort(ke((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort(ke((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort(ke("size")),s.values=c.map((e=>({name:e.name,value:l(e.size)}))),c.sort(ke("aggregatedSize")),o.values=c.map((e=>({name:e.name,value:l(e.aggregatedSize||e.size)}))),[t,n,s,o]})(e)),s.push(...(o=e,[{name:"Asset size",values:(o.build.outputs||[]).filter((e=>"map"!==e.type)).sort(ke((e=>e.size))).map((e=>({name:e.name,value:l(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(ke((e=>e.size))).map((e=>({name:e.name,value:l(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(ke((e=>e.size))).map((e=>({name:e.name,value:e.inputs.length.toString()})))||[],top:!0}])),s.push(...(e=>{const t={name:"General Numbers",values:[],top:!1},n=e.build.inputs?e.build.inputs.length:0,s=e.build.outputs?e.build.outputs.length:0,o=e.build.warnings.length,i=e.build.errors.length,r=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:E(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:E(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:E(e.build.writeDuration)}),t.values.push({name:"Number of modules",value:n.toString()},{name:"Number of assets",value:s.toString()},{name:"Number of entries",value:r.toString()},{name:"Number of warnings",value:o.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=P(e.name,60)}const n=Math.max(...e.map((e=>e.name.length))),s=Math.max(...e.flatMap((e=>e.values.map((e=>e.name.length))))),o=Math.max(...e.flatMap((e=>e.values.map((e=>e.value.length))))),i=Math.max(n+4,s+o+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=o-e.value.length;t+=` [${ve(e.value)}] ${" ".repeat(n)}${$e(e.name)}\n`}}return t})(s);t.info(i)},Ee=["onStart","onLoad","onResolve","onEnd"],Pe=new Map,Me=new Map,xe=(e,t,n)=>{const s=Object.assign({},e);for(const o of Ee)s[o]=async(s,i)=>{const r=Pe.get(t)||{name:t,increment:0,duration:0,events:{}};r.events[o]=r.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=fe(e[0].path,n),a=Me.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=d.performance.now();try{return await i(...e)}finally{const n=d.performance.now(),i=n-u,p={start:u,end:n,duration:i,context:we(e)};r.events[o].values.push(p),r.duration+=i,r.increment+=1,Pe.set(t,r),a.events[o].values.push(p),a.duration+=i,a.increment+=1,Me.set(s,a)}}))};return s},Te=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0;const o=n.time("wrapping plugins");((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(pe))continue;const n=s.setup;s.setup=async o=>{const i=xe(o,s.name,t);await n({...i,initialOptions:{...i.initialOptions,plugins:e}})}}}})(s,t.cwd),o.end(),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const s=n.time("getting plugins results"),{plugins:o,modules:i}={plugins:Pe,modules:Me};s.end(),e.report={timings:{tapables:o,modules:i}}}))}});class je{constructor(e){this.started={},this.finished=[],this.cwd=e}startModule(e,t){const n=he(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(ge))(e);s.length||s.push("no-loader"),this.started[n]={module:me(n),timings:{start:d.performance.now(),duration:0,end:0},loaders:s}}doneModule(e,t){const n=he(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=d.performance.now(),s.timings.duration=s.timings.end-s.timings.start,this.finished.push(s),delete this.started[n])}getResults(){const e=new Map,t=new Map;for(const n of this.finished){const s=n.timings.end-n.timings.start,o=t.get(n.module)||{name:n.module,increment:0,duration:0,events:{}},i=n.loaders.join(",");o.events[i]=o.events[i]||{name:i,values:[]},o.events[i].values.push(n.timings),o.increment+=1,o.duration+=s,t.set(n.module,o);for(const t of n.loaders){const n=e.get(t)||{name:t,increment:0,duration:0,events:{}};n.increment+=1,n.duration+=s,e.set(t,n)}}return{loaders:e,modules:t}}}class ze{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,i){const r=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};r.events[n]||(r.events[n]={name:n,values:[]}),r.events[n].values.push({start:o,end:i,duration:i-o,context:s,type:e}),r.duration+=i-o,r.increment+=1,this.timings.set(t,r)}getResults(){const e=this.timings;for(const[t,n]of this.timings){const s=n;s.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,s)}return{monitoredTaps:this.monitoredTaps,tapables:this.tapables,hooks:this.hooks,timings:e}}getPromiseTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=d.performance.now(),r=t.apply(this,o),a=()=>{this.saveResult(e,n,s,we(o),i,d.performance.now())};return r.then(a,a),r}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=d.performance.now(),r=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,we(o),i,d.performance.now()),r(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const i=d.performance.now(),r=t.apply(this,o);return this.saveResult(e,n,s,we(o),i,d.performance.now()),r}}getTapPatch(e,t,n,s){switch(e){case"promise":return this.getPromiseTapPatch(e,t,n,s);case"async":return this.getAsyncTapPatch(e,t,n,s);default:return this.getDefaultTapPatch(e,t,n,s)}}newTap(e,t,n,s){return(o,i)=>{const r="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${r}`;if(this.monitoredTaps[u])return n.call(s,o,i);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,i,r,t);return n.call(s,o,p)}}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(pe)||(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 s of n)this.patchHook(t,s,e.hooks[s])}checkNewHooks(){for(const e of this.tapables)this.patchHooks(e)}throughHooks(e){this.tapables.includes(e)||this.tapables.push(e),this.patchHooks(e)}}const Oe=(e,t)=>async n=>{const s=t.getLogger(pe);t.build.start=Date.now();const o={name:pe},i=new ze(t.cwd),r=new je(t.cwd),a=s.time("parse compiler hooks");i.throughHooks(n),a.end(),n.hooks.thisCompilation.tap(o,(e=>{const t=s.time("parse compilation hooks");i.throughHooks(e),t.end(),e.hooks.buildModule.tap(o,(t=>{r.startModule(t,e)})),e.hooks.succeedModule.tap(o,(t=>{r.doneModule(t,e)})),e.hooks.failedModule&&e.hooks.failedModule.tap(o,(t=>{r.doneModule(t,e)}))})),n.hooks.afterEmit.tapPromise(o,(async t=>{const{timings:n}=i.getResults(),{loaders:s,modules:o}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:o}}}))},Ne={filters:ce},Re=({options:e,context:t})=>{const n=t.getLogger(pe);let s=0;const o={start:Date.now()},i=(e=>{const t=e[ue]?.endPoint||"https://app.datadoghq.com";return{disabled:!e[ue],enableTracing:!1,filters:ce,output:!1,prefix:"",tags:[],...e[ue],endPoint:t.startsWith("http")?t:`https://${t}`}})(e),r=[];if(i.disabled)return r;const a={name:pe,enforce:"pre",esbuild:Te(o,t,n),webpack:Oe(o,t),rspack:Oe(o,t)},u=n.time("build",{start:!1}),p={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){u.resume(),t.build.start=t.build.start||Date.now()},buildEnd(){u.end(),s=Date.now()},async writeBundle(){t.build.end=Date.now(),t.build.duration=t.build.end-t.build.start,t.build.writeDuration=t.build.end-s;const e=new Set,r=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(i),a=n.time("aggregating metrics");ye(t,r,e,o.report),a.end();const u=n.time("writing to files");await be({report:o.report,metrics:e},i.output,n,t.bundler.outDir),u.end();const p=n.time("outputing report");De(t,n,o.report),p.end();const c=n.time("sending metrics to Datadog");await((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.info("No metrics to send.");const s=new Map;for(const t of e)s.has(t.metric)||s.set(t.metric,0),s.set(t.metric,s.get(t.metric)+1);const o=Array.from(s.entries()).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${o.join("\n - ")}`),L({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:i.endPoint},n),c.end()}};return i.enableTracing&&r.push(a),r.push(p),r},Ie="datadog-analytics-plugin",Ae=e=>{const{context:t}=e,n=e.context.getLogger(Ie);return t.sendLog=async(e,s={})=>{if("production"===t.env)try{const n={name:t.bundler.name,version:t.bundler.version};await L({retries:2,minTimeout:100,url:"https://browser-http-intake.logs.datadoghq.com/v1/input/pub44d5f4eb86e1392037b7501f7adc540e",method:"POST",type:"json",getData:async()=>{const o={ddsource:`@datadog/${n.name}-plugin`,env:t.env,message:e,service:"build-plugins",bundler:n,metadata:t.build.metadata,plugins:t.pluginNames,version:t.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){n.debug(`Could not submit data to Datadog: ${e}`)}},[{name:Ie,async buildStart(){await t.sendLog("Build started")}}]},Fe=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,i=[],r=[];if(Array.isArray(o))for(const e of o){const t=e&&"object"==typeof e?e.in:e;i.push({path:t})}else o&&"object"==typeof o&&i.push(...Object.entries(o).map((([e,t])=>({name:e,path:t}))));const a=i.flatMap((e=>{return(t=e.path,t.includes("*")?m.glob.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const i=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});i.errors.length&&r.push(...i.errors.map((e=>e.text))),i.path&&s.push({name:n.name,resolved:i.path,original:n.path})}));for(const e of r)n.error(e);return await Promise.all(a),s},Ce=(e,t)=>D(t)?y:t.startsWith(e)||o.isAbsolute(t)?t:o.resolve(e,t),Le=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,_e=/(\?|%3F|\|)+/gi,qe=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=Ke(e),Le.lastIndex=0,Le.exec(t)?.[1]||"unknown");var t},He=["unknown","commonjsHelpers.js",`vite${o.sep}preload-helper.js`],Be=(e,t,n)=>{const s=new Set;for(const n of e){const e=Ke(n);D(n)||e===t||He.includes(e)||s.add(e)}return s},Ke=e=>e.split("!").pop().split(_e).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/\\]+/,""),We=(e,t)=>D(t)?y:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):((e,t)=>{const n=t.split(o.sep),s=e.split(o.sep).filter(((e,t)=>e===n[t])).join(o.sep);return e.replace(s,"")})(t.split("!").pop(),Ce(e.cwd,e.bundler.outDir)).split("node_modules").pop().split(_e).shift().replace(/^((\.\.?)?[/\\])+/g,""),Ue=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Ce(t,e),n]))),Ge=(e,t)=>({setup(n){const s=new Map;let i=[];const r=t.time("build report",{start:!1});n.onStart((async()=>{s.clear(),i=[],r.resume();const o=t.time("process entries");i.push(...await Fe(n,e,t));for(const t of i){const n=We(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}o.end(),r.pause()})),n.onEnd((n=>{r.resume();const i=t.time("collecting errors and warnings"),a=e.cwd;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(i.end(),!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const u=[],p=[],c=[],l=[],d=[],m={},f={},h=t.time("indexing metafile data"),g=Ue(n.metafile.inputs,a),w=Ue(n.metafile.outputs,a);h.end();const y=e=>{if(!D(e))return e;const t=g[Ce(a,e)];if(!t)return e;const n=t.imports.find((e=>!D(e.path)));return n?n.path:e},b=t.time("looping through inputs");for(const[t,s]of Object.entries(n.metafile.inputs)){if(D(t))continue;const n=Ce(a,t),o={name:We(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:qe(t)};m[n]=o,u.push(o)}b.end();const v=t.time("looping through outputs");for(const[o,i]of Object.entries(n.metafile.outputs)){const n=Ce(a,o),r=We(e,n),u=[];for(const e of Object.keys(i.inputs)){if(D(e))continue;const n=m[Ce(a,e)];n?u.push(n):t.debug(`Input ${e} not found for output ${r}`)}if(i.entryPoint&&!u.length){const e=m[Ce(a,i.entryPoint)];if(!e){t.debug(`Input ${i.entryPoint} not found for output ${r}`);continue}u.push(e)}const d={name:r,filepath:n,inputs:u,size:i.bytes,type:qe(n)};if(f[n]=d,"map"===d.type&&l.push(d),p.push(d),!i.entryPoint)continue;const h=m[Ce(a,y(i.entryPoint))];if(h){if(!s.get(h.name))continue;const e={...d,name:s.get(h.name)||h.name,outputs:[d],size:d.size};c.push(e)}}v.end();const $=t.time("looping through sourcemaps");for(const e of l){const n=f[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}$.end();const k={inputs:{report:m,meta:g},outputs:{report:f,meta:w}},S=/(<runtime>|https:|file:|data:|#)/g,E=e=>!D(e)&&!e.match(S),P=(n,s,i={})=>{if(!E(n))return i;const r=s.report[n];if(!r)return t.debug(`Could not find report's ${n}`),i;if(i[r.filepath])return i;i[r.filepath]=r;const p=s.meta[n];if(!p)return t.debug(`Could not find metafile's ${n}`),i;if(!p.imports||!p.imports.length)return i;for(const t of p.imports){const p=t.path.match(/^\.\.?\//),c=p?o.dirname(n):a,l=Ce(c,t.path);if(t.external){if(E(t.path)){const n=p?l:t.path,s=k.inputs.report[n]||{filepath:n,name:We(e,t.path),size:0,type:"external",dependencies:new Set,dependents:new Set};"dependencies"in r&&(s.dependents.add(r),r.dependencies.add(s)),"inputs"in r&&!r.inputs.includes(s)&&r.inputs.push(s),u.includes(s)||u.push(s),k.inputs.report[n]=s,i[s.filepath]=s}}else P(l,s,i)}return i},M=t.time("looping through entries");for(const e of c){const t={},n={};for(const n of e.inputs)P(n.filepath,k.inputs,t);for(const t of e.outputs)P(t.filepath,k.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),d.push(e)}M.end();const x=t.time("aggregate dependencies and dependents");for(const e of u){if("external"===e.type)continue;const n=k.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!E(s.path))continue;const n=s.path.match(/^\.?\.\//),i=n?o.dirname(e.filepath):a,r=Ce(i,s.path);let u;if(s.external){const e=n?r:s.path;u=k.inputs.report[e]}else u=k.inputs.report[r];u?(e.dependencies.add(u),u.dependents.add(e)):t.debug(`Could not find input file of ${s.path} imported from ${e.name}`)}else t.debug(`Could not find metafile's ${e.name}`)}x.end(),e.build.outputs=p,e.build.inputs=u,e.build.entries=d,r.end(),e.hook("buildReport",e.build)}))}}),Je=(e,t)=>{const n=t.time("module parsing",{start:!1});let s={};return{buildStart(){s={}},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=Ke(e.id),o=s[t]||{dependencies:new Set,dependents:new Set},i=Be(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Be(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)o.dependents.add(e);for(const e of i)o.dependencies.add(e);s[t]=o,n.tag([`module:${t}`],{span:!0}),n.pause()},writeBundle(n,o){const i=t.time("build report"),r=[],a=[],u=[],p=[],c={},l=[],d={},m={},f=t.time("completing dependencies and dependents");for(const[e,{dependencies:t,dependents:n}]of Object.entries(s)){for(const n of t){const t=Ke(n);s[t]||(s[t]={dependencies:new Set,dependents:new Set}),s[t].dependents.has(e)||s[t].dependents.add(e)}for(const t of n){const n=Ke(t);s[n]||(s[n]={dependencies:new Set,dependents:new Set}),s[n].dependencies.has(e)||s[n].dependencies.add(e)}}f.end();const h=t.time("filling inputs and outputs");for(const[n,i]of Object.entries(o)){const o={name:n,filepath:Ce(e.bundler.outDir,n),inputs:[],size:"code"in i?Buffer.byteLength(i.code,"utf8"):Buffer.byteLength(i.source,"utf8"),type:qe(n)};if("map"===o.type&&p.push(o),"modules"in i)for(const[t,n]of Object.entries(i.modules)){if(Ke(t)!==t)continue;const s={name:We(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:n.originalLength,type:qe(t)};o.inputs.push(s),d[s.filepath]=s,r.push(s)}if("imports"in i)for(const n of i.imports){const i=Ke(n);if(!s[i]){c[Ce(e.bundler.outDir,i)]=o;continue}if(d[i]){t.debug(`Input report already there for ${i} from ${o.name}.`);continue}const a={name:We(e,n),dependencies:new Set,dependents:new Set,filepath:i,size:0,type:"external"};o.inputs.push(a),d[a.filepath]=a,r.push(a)}"isEntry"in i&&i.isEntry&&u.push({...o,name:i.name,size:0,outputs:[o]}),m[o.filepath]=o,a.push(o)}h.end();for(const[e,n]of Object.entries(c)){const s=m[e];s?n.inputs.includes(s)||n.inputs.push(s):t.debug(`Could not find the output report for ${e}.`)}const g=t.time("filling dependencies and dependents");for(const n of r){const o=s[n.filepath];if(o){for(const s of o.dependencies){const o=d[s];o?n.dependencies.add(o):t.debug(`Could not find input for dependency ${We(e,s)} of ${n.name}`)}for(const s of o.dependents){const o=d[s];o?n.dependents.add(o):t.debug(`Could not find input for dependent ${We(e,s)} of ${n.name}`)}}else t.debug(`Could not find the import report for ${n.name}.`)}if(g.end(),p.length){const e=t.time("filling sourcemaps inputs");for(const e of p){const n=e.filepath.replace(/\.map$/,""),s=m[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}e.end()}const w=(n,s={})=>{if(s[n])return s;const i=We(e,n),r=m[n];if(!r){return!!d[i]||t.debug(`Could not find output for ${i}`),s}s[n]=r;const a=o[We(e,n)];if(!a)return t.debug(`Could not find asset for ${i}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)w(Ce(e.bundler.outDir,t),s);return s},y=t.time("filling entries");for(const e of u){const t=w(e.filepath);e.outputs=Object.values(t),e.inputs=Array.from(new Set(e.outputs.flatMap((e=>e.inputs)))),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),l.push(e)}y.end(),e.build.inputs=r,e.build.outputs=a,e.build.entries=l,i.end(),e.hook("buildReport",e.build)}}},Ve=(e,t,n)=>s=>{let o=[],i=[],r=[];const a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,m=n.time("build report",{start:!1}),f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||D(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"],s=e=>{const n=Ke(e);t.add(n),n.startsWith("external ")&&t.add(h(n))};s(e.identifier());for(const t of n){const n=e[t];t&&t in e&&"string"==typeof n&&s(n)}return t})(e);for(const e of n)if(c.has(e)){const n=c.get(e);n.dependencies.push(...t.dependencies||[]),n.blocks.push(...t.blocks||[])}else c.set(e,t)},w=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),w(n,t);if("blocks"in e)for(const n of e.blocks)w(n,t);return t},y=(e,t)=>{if("request"in t&&t.request){const n=Ke(t.request);if(c.has(n))return c.get(n);if(e.context){const t=Ce(Ke(e.context),n);if(c.has(t))return c.get(t)}}},b=e=>!(!("externalType"in e)||!e.externalType)||(!(!("external"in e)||!e.external)||!!e.identifier?.().startsWith("external "));s.hooks.thisCompilation.tap(t,(s=>{o=[],i=[],r=[],a.clear(),u.clear(),c.clear(),d.clear(),s.hooks.finishModules.tap(t,(t=>{m.resume();const s=n.time("dependency graph"),i=n.time("indexing modules");for(const e of t)g(e);i.end();const r=n.time("building inputs");for(const n of t){const t=n.identifier(),s=We(e,t),i=new Set(w(n).map((e=>{const s=y(n,e);if(!s?.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&(b(s)?h(o):o))})).filter(Boolean));if(!f(t))continue;const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of i){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),r.dependencies.add(e),d.set(e,n)}d.set(t,r);const u=b(n)?{size:0,name:h(s),dependencies:new Set,dependents:new Set,filepath:t,type:"external"}:{size:n.size()||0,name:s,dependencies:new Set,dependents:new Set,filepath:t,type:qe(t)};o.push(u),a.set(t,u),b(n)&&a.set(h(t),u)}r.end();const u=n.time("assigning dependencies and dependents");for(const e of o){const t=d.get(e.filepath);if(t){for(const s of t.dependencies){const t=a.get(s);t?e.dependencies.add(t):n.debug(`Could not find input of dependency ${s}`)}for(const s of t.dependents){const t=a.get(s);t?e.dependents.add(t):n.debug(`Could not find input of dependent ${s}`)}}else n.debug(`Could not find dependency report for ${e.name}`)}u.end(),s.end(),m.pause()}))})),s.hooks.afterEmit.tap(t,(t=>{m.resume();const s=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Ce(e.bundler.outDir,t))),h=n.time("indexing chunks"),g=t.chunkGraph;for(const e of s){const t=d(e),n=(g?g?.getChunkModules(e):"getModules"in e&&"function"==typeof e.getModules?e.getModules():[]).flatMap((e=>"modules"in e&&Array.isArray(e.modules)?e.modules.map((e=>e.identifier())):e.identifier())).filter(f);for(const e of t){if("map"===qe(e))continue;const t=p.get(e)||new Set;for(const e of n)t.add(e);p.set(e,t)}}h.end();const w=n.time("building outputs");for(const t of c){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Ce(e.bundler.outDir,t.name),type:qe(t.name)};if(u.set(s.filepath,s),i.push(s),"map"===s.type){l.push(s);continue}const o=p.get(s.filepath);if(o)for(const e of o){const t=a.get(e);t?s.inputs.push(t):n.debug(`Could not find input of ${e}`)}else n.debug(`Could not find modules for ${s.name}`)}w.end();const y=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}`)}y.end();const b=n.time("building entries");for(const[s,o]of t.entrypoints){const t=new Map,i=new Map;let a=0;const p=o.chunks.flatMap(d),c=o.chunks.filter((e=>g?g.getChunkEntryModulesIterable(e):"hasEntryModule"in e&&"function"==typeof e.hasEntryModule&&e.hasEntryModule())).flatMap((e=>Array.from(e.files))).filter((e=>e.includes(s)||o.name&&e.includes(o.name))).find((e=>"js"===qe(e)));for(const e of p){const s=u.get(e);if(e&&s){if("map"!==s.type&&!t.has(s.name)){t.set(s.name,s);for(const e of s.inputs)i.has(e.filepath)||i.set(e.filepath,e);a+=s.size}}else n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:c?Ce(e.bundler.outDir,c):"unknown",size:a,inputs:Array.from(i.values()),outputs:Array.from(t.values()),type:c?qe(c):"unknown"};r.push(l)}b.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=o,e.build.outputs=i,e.build.entries=r,m.end(),e.hook("buildReport",e.build)}))},Ye="datadog-build-report-plugin",Qe=e=>{const{context:t}=e,n=t.getLogger(Ye);return[{name:Ye,enforce:"post",esbuild:Ge(t,n),rspack:Ve(t,Ye,n),webpack:Ve(t,Ye,n),vite:Je(t,n),rollup:Je(t,n)}]},Xe=(e,t)=>{const n=(e=>{let t,n=Ce(process.cwd(),e),i=n.split(o.sep).length;for(;i>0;){const e=o.resolve(n,"package.json");s.existsSync(e)&&(t=n),n=n.split(o.sep).slice(0,-1).join(o.sep),i--}return t})(t);if(n)return n;const i=(e=>{const t=[...e].map((e=>Ce(process.cwd(),e).split(o.sep))),n=t.length?Math.min(...t.map((e=>e.length))):0,s=[];for(let e=0;e<n;e++){const n=t[0][e];if(!t.every((t=>t[e]===n)))break;s.push(n)}return s.length>0&&s.join(o.sep)||o.sep})(Array.from(e));return i!==o.sep?i:void 0},Ze=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),e.hook("bundlerReport",e.bundler),t.options.context&&(e.cwd=t.options.context),e.hook("cwd",e.cwd)},et=e=>{const{context:t}=e,n=new Set,s=e=>{e&&(e.dir?(t.bundler.outDir=e.dir,n.add(e.dir)):e.file&&(t.bundler.outDir=o.dirname(e.file),n.add(t.bundler.outDir)),t.bundler.outDir=Ce(process.cwd(),t.bundler.outDir),"vite"!==t.bundler.name&&(t.cwd=Xe(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)))},i=()=>({options(e){if(t.bundler.rawConfig=e,e.input)if(Array.isArray(e.input))for(const t of e.input)n.add(o.dirname(t));else if("object"==typeof e.input)for(const t of Object.values(e.input))n.add(o.dirname(t));else{if("string"!=typeof e.input)throw new Error("Invalid input type");n.add(o.dirname(e.input))}if("output"in e){const t=Array.isArray(e.output)?e.output:[e.output];for(const e of t)s(e)}t.hook("bundlerReport",t.bundler)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(e){t.bundler.rawConfig=e.initialOptions,e.initialOptions.outdir&&(t.bundler.outDir=e.initialOptions.outdir),e.initialOptions.outfile&&(t.bundler.outDir=o.dirname(e.initialOptions.outfile)),t.hook("bundlerReport",t.bundler),e.initialOptions.absWorkingDir&&(t.cwd=e.initialOptions.absWorkingDir),t.hook("cwd",t.cwd),e.initialOptions.metafile=!0}},webpack:Ze(t),rspack:Ze(t),vite:{...i(),config(e){e.build?.outDir&&(t.bundler.outDir=e.build.outDir),e.root?t.cwd=e.root:t.cwd=Xe(n,t.bundler.outDir)||t.cwd,t.hook("cwd",t.cwd)}},rollup:i()}]},tt="datadog-custom-hooks-plugin",nt=e=>{const{context:t}=e,n=t.getLogger(tt),s=e=>(s,...o)=>{const i=n.time(`execution | ${s}`,{tags:["type:custom-hook",`hook:${s}`]}),r=[],a=[];for(const n of t.plugins){if(!(s in n))continue;const t=n[s];if("function"==typeof t)try{const i=t(...o);i instanceof Promise&&(e||r.push(`Plugin "${n.name}" returned a promise on the non async hook "${s}".`),a.push(i))}catch(e){r.push(`Plugin "${n.name}" errored on hook "${s}". [${e}]`)}else r.push(`Plugin "${n.name}" has an invalid hook type for "${s}". [${typeof t}]`)}if(r.length>0){for(const e of r)n.error(e);throw new Error("Some plugins errored during the hook execution.")}return Promise.all(a).finally((()=>i.end()))};return t.hook=s(!1),t.asyncHook=s(!0),[{name:tt,enforce:"pre"}]};class st{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=s.readFileSync(e,"utf8"),o=JSON.parse(n);if(!o.sources)return void t("Missing 'sources' field in sourcemap.");const i=o.sources;if(0===i.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(i);if(0!==r.length)return r;t(`${i.map(this.displaySource).join(", ")} not in the tracked files.`)}matchSources(e){let t=[];const n=new Set;for(const s of e){const e=this.getFilename(s);if(n.has(e))continue;n.add(e);const o=this.trackedFilenames.get(e);o&&(t=t.concat(o))}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 ot=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await it(e);for(const e of t)if(e.name===n)return M(e.refs.push);return M(t[0].refs.push)},it=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},rt=async e=>e.revparse("HEAD"),at=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ut=async e=>e.branch(),pt=async e=>e.show(["-s","--format=%s"]),ct=async e=>e.show(["-s","--format=%an,%ae,%aI,%cn,%ce,%cI"]),lt="datadog-git-plugin",dt=e=>{const{options:t,context:n}=e,s=n.getLogger(lt);return[{name:lt,enforce:"pre",async buildStart(){if((e=>!!e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)(t))try{const e=s.time("get git information"),t=await(async e=>{const t=[rt(e),ut(e),pt(e),ct(e),at(e),ot(e)],[n,s,o,i,r,a]=await Promise.all(t),[u,p,c,l,d,m]=i.split(",").map((e=>e.trim()));return{commit:{author:{name:u,email:p,date:c},committer:{name:l,email:d,date:m},message:o.trim(),hash:n},hash:n,branch:s.current,remote:a.trim(),trackedFilesMatcher:new st(r)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=f.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return f.simpleGit(t)})(n.cwd));n.git=t,e.end(),await n.asyncHook("git",n.git)}catch(e){s.error(`Could not get git information: ${e.message}`)}}}]},mt="datadog-injection-plugin",ft=/^https?:\/\//,ht=async(e,t,s=process.cwd())=>{let o;const i=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)o=i.match(ft)?await(async(e,t=5e3)=>{let n;return Promise.race([L({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(i):await(async(e,t=process.cwd())=>{const s=Ce(t,e);return n.readFile(s,{encoding:"utf-8"})})(i,s);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);o=i}}catch(n){const s=`${e.type} - ${P(i)}`;e.fallback?(t.info(`Fallback for "${s}": ${n.toString()}`),o=await ht(e.fallback,t)):(t.warn(`Failed "${s}": ${n.toString()}`),o="")}return o},gt=e=>{if(0===e.size)return"";return`// begin injection by Datadog build plugins\n${Array.from(e.values()).map((e=>`(() => {${e}})();`)).join("\n\n")}\n// end injection by Datadog build plugins`},wt=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,i]of e.entries()){const e=await ht(i,t,n);e&&s.set(o,{value:e,position:i.position||te.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},yt=s.promises,bt=(e,t,n)=>({setup(i){const{onStart:r,onResolve:a,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=i,d=[],m=`${T()}.${te.MIDDLE}.${y}.js`,f=s.realpathSync(h.tmpdir()),g=o.resolve(f,m),w=new RegExp(`${m}$`),b=l.inject;l.inject=b?[...b]:[],l.inject.push(g),r((async()=>{d.push(...await Fe(i,t,e)),i.initialOptions.inject=b;try{await $(g,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:w},(async e=>({path:e.path,namespace:mt}))),u({filter:w,namespace:mt},(async()=>({contents:gt(n[te.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),p((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=gt(n[te.BEFORE]),i=gt(n[te.AFTER]);if(!o&&!i)return;const r=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?Ce(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await yt.readFile(e,"utf-8"),n=await c.transform(t,{loader:"default",banner:o,footer:i});await yt.writeFile(e,n.code)}));await Promise.all(r)}))}}),vt=y,$t="?inject-proxy",kt=e=>({banner:t=>t.isEntry?gt(e[te.BEFORE]):"",async resolveId(t,n,s){if(D(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&gt(e[te.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${$t}`}return null},load(t){if(D(t))return gt(e[te.MIDDLE]);if(t.endsWith($t)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(vt)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?gt(e[te.AFTER]):""}),St=(e,t,n,i,r)=>a=>{const u=new WeakMap,p=(e=>{if(!e?.sources?.ConcatSource)return g.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),c=o.resolve(n.bundler.outDir,`${T()}.${te.MIDDLE}.${y}.js`);k(c,"");const l=()=>{var e;e=c,s.rmSync(e,{force:!0,maxRetries:3,recursive:!0})};a.hooks.shutdown?a.hooks.shutdown.tap(mt,l):(a.hooks.done.tap(mt,l),a.hooks.failed.tap(mt,l));a.hooks.beforeRun.tapPromise(mt,(async()=>{await wt(t,i,r,n.cwd)})),a.hooks.compilation.tap(mt,(t=>{const n=()=>{const e=gt(r[te.BEFORE]),n=gt(r[te.AFTER]);for(const s of t.chunks)if(s.canBeInitial())for(const o of s.files)t.updateAsset(o,(t=>{const s=u.get(t);if(!s||s.banner!==e||s.footer!==n){const s=new p(e,"\n",t,"\n",n);return u.set(t,{source:s,banner:e,footer:n}),s}return s.source}))};if(t.hooks.processAssets){const s=e.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;t.hooks.processAssets.tap({name:mt,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:mt},n)}));const d=(e=>{const s="webpack4"===n.bundler.fullName?c:{import:[c]},o=e=>{for(const[n,s]of Object.entries(e))"object"==typeof s?(s.import=s.import||[],s.import.unshift(c)):"string"==typeof s?e[n]=[c,s]:Array.isArray(s)?s.unshift(c):t.error("Invalid entry type: "+typeof s)};return e?"function"==typeof e?async()=>{const t=await e();return o(t),t}:"object"!=typeof e?"string"==typeof e?[s,e]:(t.error("Invalid entry type: "+typeof e),e):(o(e),e):{ddHelper:s}})(a.options.entry);a.options.entry=d},Dt=e=>{const{bundler:t,context:n}=e,s=n.getLogger(mt),o=new Map,i={[te.BEFORE]:new Map,[te.MIDDLE]:new Map,[te.AFTER]:new Map};n.inject=e=>{o.set(T(),e)};const r={name:mt,enforce:"post",esbuild:bt(s,n,i),webpack:St(t,s,n,o,i),rspack:St(t,s,n,o,i),rollup:kt(i),vite:{...kt(i),enforce:"pre"}};var a;return a=n.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(a)?(r.loadInclude=e=>!!D(e)||null,r.load=e=>D(e)?{code:gt(i[te.MIDDLE])}:null):r.buildStart=async()=>{await wt(s,o,i,n.cwd)},[r]},Et="datadog-true-end-plugin",Pt=e=>{const{context:t}=e,n=async()=>{await t.asyncHook("asyncTrueEnd")},s=()=>{t.hook("syncTrueEnd")},o=async()=>{s(),await n()},i=e=>{e.hooks.shutdown?e.hooks.shutdown.tapPromise(Et,o):(e.hooks.done.tapPromise(Et,o),e.hooks.failed.tap(Et,s))},r={async writeBundle(){},async closeBundle(){await o()}};return[{name:Et,enforce:"post",webpack:i,esbuild:{setup(e){e.onEnd((async()=>{await n()})),e.onDispose((()=>{s()}))}},vite:r,rollup:r,rspack:i}]},Mt={[ue]:Ne};var xt="2.6.1";const Tt=(({bundler:n,version:s})=>{const o=Date.now();return e.createUnplugin(((e,i)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",metadata:{},...e}))(e);"esbuild"===i.framework&&(i.esbuildHostName=v);const a=(({start:e,options:t,bundlerName:n,bundlerVersion:s,version:o})=>{const i=process.cwd(),r="webpack"===n?s.split(".")[0]:"",a={errors:[],warnings:[],logs:[],metadata:t.metadata||{},timings:[],bundler:{name:n,fullName:`${n}${r}`,variant:r,version:s}},u=process.env.BUILD_PLUGINS_ENV||"production",p=b.includes(u)?u:"development";return{auth:t.auth,pluginNames:[],bundler:{...a.bundler,outDir:i},build:a,cwd:i,env:p,getLogger:z(a,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.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},plugins:[],start:e,version:o}})({start:o,options:r,bundlerVersion:n.rspackVersion||n.version||n.VERSION,bundlerName:i.framework,version:s}),u=a.getLogger("factory").time("Plugins initialization",{start:o});a.pluginNames.push(v);const p=[];p.push(["analytics",Ae],["build-report",Qe],["bundler-report",et],["custom-hooks",nt],["git",dt],["injection",Dt],["true-end",Pt]),r.customPlugins&&p.push(["custom",r.customPlugins]),p.push(["error-tracking",ee],["rum",ae],["telemetry",Re]);for(const[e,t]of p)a.plugins.push(...R(a,t,e)({bundler:n,context:a,options:r}));a.pluginNames.push(...a.plugins.map((e=>e.name)));const c=new Set(a.pluginNames.filter((e=>a.pluginNames.filter((t=>t===e)).length>1)));if(c.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(c).join(", "))}`);return a.hook("init",a),u.end(),a.plugins}))})({bundler:w,version:xt}).esbuild,jt=xt,zt=Mt;exports.datadogEsbuildPlugin=Tt,exports.helpers=zt,exports.version=jt;
5
5
  //# sourceMappingURL=index.js.map