@datadog/rspack-plugin 2.5.1-dev-4 → 2.5.1-dev-5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/index.d.ts +37 -11
- package/dist/src/index.js +1 -1
- package/dist/src/index.mjs +1 -1
- package/package.json +1 -1
package/dist/src/index.d.ts
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import * as unplugin from 'unplugin';
|
|
2
2
|
import { UnpluginOptions } from 'unplugin';
|
|
3
|
-
import
|
|
4
|
-
export { types as ErrorTrackingTypes } from '@dd/error-tracking-plugin';
|
|
5
|
-
import { RumInitConfiguration as RumInitConfiguration$1 } from '@datadog/browser-rum';
|
|
6
|
-
import * as rum from '@dd/rum-plugin';
|
|
7
|
-
export { types as RumTypes } from '@dd/rum-plugin';
|
|
8
|
-
import * as telemetry from '@dd/telemetry-plugin';
|
|
9
|
-
export { types as TelemetryTypes } from '@dd/telemetry-plugin';
|
|
3
|
+
import { datadogRum, RumInitConfiguration as RumInitConfiguration$1 } from '@datadog/browser-rum';
|
|
10
4
|
|
|
11
5
|
declare class TrackedFilesMatcher {
|
|
12
6
|
private trackedFilenames;
|
|
@@ -18,6 +12,8 @@ declare class TrackedFilesMatcher {
|
|
|
18
12
|
private getFilename;
|
|
19
13
|
}
|
|
20
14
|
|
|
15
|
+
declare const CONFIG_KEY$2: "errorTracking";
|
|
16
|
+
|
|
21
17
|
type MinifiedPathPrefix = `http://${string}` | `https://${string}` | `/${string}`;
|
|
22
18
|
type SourcemapsOptions = {
|
|
23
19
|
bailOnError?: boolean;
|
|
@@ -33,15 +29,44 @@ type ErrorTrackingOptions = {
|
|
|
33
29
|
disabled?: boolean;
|
|
34
30
|
sourcemaps?: SourcemapsOptions;
|
|
35
31
|
};
|
|
32
|
+
interface OptionsWithErrorTracking extends GetPluginsOptions {
|
|
33
|
+
[CONFIG_KEY$2]: ErrorTrackingOptions;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type types$2 = {
|
|
37
|
+
ErrorTrackingOptions: ErrorTrackingOptions;
|
|
38
|
+
OptionsWithErrorTracking: OptionsWithErrorTracking;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
declare const CONFIG_KEY$1: "rum";
|
|
36
42
|
|
|
37
43
|
type RumOptions = {
|
|
38
44
|
disabled?: boolean;
|
|
39
45
|
sdk?: SDKOptions;
|
|
40
46
|
};
|
|
47
|
+
type RumPublicApi = typeof datadogRum;
|
|
41
48
|
type RumInitConfiguration = RumInitConfiguration$1;
|
|
42
49
|
type SDKOptions = Assign<RumInitConfiguration, {
|
|
43
50
|
clientToken?: string;
|
|
44
51
|
}>;
|
|
52
|
+
interface OptionsWithRum extends GetPluginsOptions {
|
|
53
|
+
[CONFIG_KEY$1]: RumOptions;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type types$1 = {
|
|
57
|
+
RumOptions: RumOptions;
|
|
58
|
+
OptionsWithRum: OptionsWithRum;
|
|
59
|
+
RumPublicApi: RumPublicApi;
|
|
60
|
+
RumInitConfiguration: RumInitConfiguration;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
declare const CONFIG_KEY: "telemetry";
|
|
64
|
+
|
|
65
|
+
type types = {
|
|
66
|
+
Filter: Filter;
|
|
67
|
+
Metric: Metric;
|
|
68
|
+
TelemetryOptions: TelemetryOptions;
|
|
69
|
+
};
|
|
45
70
|
|
|
46
71
|
declare const ALL_ENVS: readonly ["development", "production", "test"];
|
|
47
72
|
declare const SUPPORTED_BUNDLERS: readonly ["webpack", "vite", "esbuild", "rollup", "rspack"];
|
|
@@ -145,11 +170,12 @@ interface BaseOptions {
|
|
|
145
170
|
logLevel?: LogLevel;
|
|
146
171
|
}
|
|
147
172
|
interface Options extends BaseOptions {
|
|
148
|
-
[
|
|
149
|
-
[
|
|
150
|
-
[
|
|
173
|
+
[CONFIG_KEY$2]?: ErrorTrackingOptions;
|
|
174
|
+
[CONFIG_KEY$1]?: RumOptions;
|
|
175
|
+
[CONFIG_KEY]?: TelemetryOptions;
|
|
151
176
|
customPlugins?: GetCustomPlugins;
|
|
152
177
|
}
|
|
178
|
+
type GetPluginsOptions = Required<BaseOptions>;
|
|
153
179
|
|
|
154
180
|
interface Metric {
|
|
155
181
|
metric: string;
|
|
@@ -185,4 +211,4 @@ declare const helpers: {
|
|
|
185
211
|
};
|
|
186
212
|
};
|
|
187
213
|
|
|
188
|
-
export { type RspackPluginOptions, datadogRspackPlugin, helpers, version };
|
|
214
|
+
export { type types$2 as ErrorTrackingTypes, type RspackPluginOptions, type types$1 as RumTypes, type types as TelemetryTypes, datadogRspackPlugin, helpers, version };
|
package/dist/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var e=require("unplugin"),t=require("chalk"),n=require("outdent"),s=require("path"),o=require("async-retry"),r=require("fs/promises"),i=require("fs"),a=require("glob"),u=require("buffer"),p=require("p-queue"),c=require("stream"),l=require("zlib"),d=require("pretty-bytes"),f=require("perf_hooks"),m=require("simple-git"),h=require("url"),g=require("os"),w=require("module"),y=require("@rspack/core");const b="__datadog-helper-file",v=["development","production","test"],$={debug:0,info:1,warn:2,error:3,none:4},k=(e,n="warn")=>s=>{const o=(e=>e.split(">").map((e=>e.replace(/^datadog-|-plugin$/g,""))).join(">"))(s),r=(s,r="debug")=>{let i=t.dim,a=console.log;"error"===r?(i=t.red,a=console.error):"warn"===r?(i=t.yellow,a=console.warn):"info"===r&&(i=t.cyan,a=console.log);const u=`[${r}|${e.bundler.fullName}|${o}]`,p="string"==typeof s?s:JSON.stringify(s,null,2);e.logs.push({bundler:e.bundler.fullName,pluginName:o,type:r,message:p,time:Date.now()}),"error"===r&&e.errors.push(p),"warn"===r&&e.warnings.push(p),$[r]>=$[n]&&a(`${i(u)} ${p}`)};return{getLogger:t=>k(e,n)(`${o}>${t}`),error:e=>r(e,"error"),warn:e=>r(e,"warn"),info:e=>r(e,"info"),debug:e=>r(e,"debug")}},S="errorTracking",D="datadog-error-tracking-plugin",E=(e,n,o)=>{if(".map"!==s.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=r.replace(n.bundler.outDir,"");return{minifiedFilePath:r,minifiedUrl:e.minifiedPathPrefix?s.join(e.minifiedPathPrefix,i):i,relativePath:i}},M=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(),r=n.getUTCSeconds(),i=n.getUTCMilliseconds();return`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${r?`${r}s `:""}${i?`${i}ms`:""}`.trim()},P=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,r=[],i=[];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("*")?a.glob.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const r=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});r.errors.length&&i.push(...r.errors.map((e=>e.text))),r.path&&s.push({name:n.name,resolved:r.path,original:n.path})}));for(const e of i)n.error(e);return await Promise.all(u),s},j=[400,403,413],O=e=>{const{auth:t,url:n,method:s="GET",getData:r,type:i="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return o((async(e,o)=>{let a;try{const e={method:s,duplex:"half"};let o={};if(t?.apiKey&&(o["DD-API-KEY"]=t.apiKey),t?.appKey&&(o["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof r){const{data:t,headers:n}=await r();e.body=t,o={...o,...n}}a=await fetch(n,{...e,headers:o})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(j.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)},T=(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)),r=s-o;return`${e.slice(0,o)}${n}${e.slice(-r)}`},z=e=>e.includes(b),N=async(e,t)=>{await(async e=>r.mkdir(e,{recursive:!0}))(s.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})},R=(e,t)=>{var n;n=s.dirname(e),i.mkdirSync(n,{recursive:!0}),i.writeFileSync(e,t,{encoding:"utf-8"})};let x=0;const I=()=>`${Date.now()}.${performance.now()}.${++x}`,A=/[/]+|[\\]+/g,F=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,q=(e,t)=>{const n=e.replace(F,"").split(A),s=t.replace(F,"").split(A),o=n.join("/");let r="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(r=t)}return r},C=async e=>{const t={empty:!1,exists:!0};try{0===(await i.promises.stat(e)).size&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},L=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,s]=await Promise.all([C(e.minifiedFilePath),C(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:q(e.relativePath,t)}})(e,n),i=[],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(o)try{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${s.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){a.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&i.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||i.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&i.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||i.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:u,errors:i,warnings:a}},_=t.green.bold,K=t.yellow.bold,B=t.red.bold,H=async(e,t)=>{if("function"==typeof i.openAsBlob){const n=await i.openAsBlob(e,{type:t.contentType});return new u.File([n],t.filename)}{const n=c.Readable.toWeb(i.createReadStream(e)),s=await new Response(n).blob();return new u.File([s],t.filename,{type:t.contentType})}},U=(e,t={})=>async()=>{const n=new FormData,s=l.createGzip();for(const[t,s]of e.content){const e="file"===s.type?await H(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:c.Readable.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},W=async(e,t,n,s)=>{const o=Date.now(),r=t.minifiedPathPrefix,i={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=>L(e,i,r,n.git)))),u=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 - ")}`),u.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${u.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=[],r=[];if(!n.auth?.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:r};if(0===e.length)return r.push("No sourcemaps to upload"),{errors:o,warnings:r};const i=new(p.default?p.default:p)({concurrency:t.maxConcurrency}),a={"DD-API-KEY":n.auth.apiKey,"DD-EVP-ORIGIN":`${n.bundler.fullName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},u=[];for(const p of e){const e={sourcemap:p.content.get("source_map")?.path.replace(n.bundler.outDir,"."),file:p.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${_(e.sourcemap)} | ${_(e.file)}`),u.push(i.add((async()=>{try{await O({url:t.intakeUrl,method:"POST",getData:U(p,a),onRetry:(t,n)=>{const o=`Failed to upload ${K(e.sourcemap)} | ${K(e.file)}:\n ${t.message}\nRetrying ${n}/5`;r.push(o),s.debug(o)}}),s.debug(`Sent ${_(e.sourcemap)} | ${_(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(u),await i.onIdle(),{warnings:r,errors:o}})(a,t,n,s);if(s.info(`Done uploading ${_(e.length.toString())} sourcemaps in ${_(M(Date.now()-o))}.`),l.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${l.map((({metadata:e,error:t})=>e?`${B(e.file)} | ${B(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 - ")}`)},G=async(e,s,o)=>{const r=t.green.bold,i=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${r(t.toString())}`)).join("\n"),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=>({...E(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,s),u=n.outdent`
|
|
2
2
|
Uploading ${r(a.length.toString())} sourcemaps with configuration:
|
|
3
3
|
${i}
|
|
4
|
-
`;o.info(u),await W(a,e.sourcemaps,s,o)},J=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,V=e=>{const n=t.bold.red,s=e[S]||{},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||J,...s.sourcemaps};o.config=e}return o},Y=(e,t)=>{const n=t.getLogger(D),s=((e,t)=>{const n=[],s=V(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${D}.`);const o={...e[S],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return[{name:D,enforce:"post",async writeBundle(){s.disabled||s.sourcemaps&&await G(s,t,n)}}]};var Q=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Q||{});const X="rum",Z="datadog-rum-plugin",ee=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,te=(e,t)=>{const n=e.sdk;if(n.clientToken)return ee(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 O({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 ee({...e,sdk:{clientToken:s,...n}})}},ne=e=>{const n=t.bold.red,s=e[X]||{},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},se=(e,t)=>{const n=((e,t)=>{const n=[],s=ne(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${Z}.`);const o={...e[X],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(Z));return n.sdk&&(t.inject({type:"file",position:Q.MIDDLE,value:s.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Q.MIDDLE,value:te(n,t)})),[]},oe="telemetry",re="datadog-telemetry-plugin",ie=[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}],ae=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),ue=(e="")=>e.endsWith("/")?e:`${e}/`,pe=(e,t)=>{let n=e;return e.split(ue(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},ce=(e,t)=>e.split("!").pop().replace(ue(t),"./"),le=(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)),ce(s||"no-name",n)},de=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),fe=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),me=(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 r=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;r+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:r,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||[],r=e.build.warnings.length,i=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:i,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:r,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(ae(s,t))}else n.add(ae(e,t))},he=async(e,t,n,o)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:r,metrics:i}=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=s.resolve(o,u);try{const e={},t={};p.timings&&r?.timings&&(t.timings={content:{tapables:r.timings.tapables?Array.from(r.timings.tapables.values()):null,loaders:r.timings.loaders?Array.from(r.timings.loaders.values()):null,modules:r.timings.modules?Array.from(r.timings.modules.values()):null}}),p.metrics&&(t.metrics={content:Array.from(i)});const o=Object.entries(t).map((async([t,o])=>{const r=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return N(e,n)})(s.join(c,`${t}.json`),o.content),n.debug(`Wrote ${t}.json in ${M(Date.now()-r)}`)}catch(s){n.error(`Failed to write ${t}.json in ${M(Date.now()-r)}`),e[t]=s}}));await Promise.all(o),n.debug(`Wrote files in ${M(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}`)}},ge=t.bold.red,we=t.bold.cyan,ye=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},be=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(ye("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:M(e.duration)}))),top:!0};n.sort(ye("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},ve=(e,t,n)=>{const s=[];var o;n&&(s.push(...be("Loader",n.timings.loaders)),s.push(...be("Tapable",n.timings.tapables)),s.push(...be("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},r=new Set,i=(e=>{const t={bundler:e.bundler,errors:e.errors,warnings:e.warnings,logs:e.logs,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 i.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;r.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!r.size)return[t,n,s];const c=Array.from(r);return c.sort(ye((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort(ye((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort(ye("size")),s.values=c.map((e=>({name:e.name,value:d(e.size)}))),c.sort(ye("aggregatedSize")),o.values=c.map((e=>({name:e.name,value:d(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(ye((e=>e.size))).map((e=>({name:e.name,value:d(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(ye((e=>e.size))).map((e=>({name:e.name,value:d(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(ye((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,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:M(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:M(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:M(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:i.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=T(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))))),r=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${ge(e.value)}] ${" ".repeat(n)}${we(e.name)}\n`}}return t})(s);t.info(r)},$e=["onStart","onLoad","onResolve","onEnd"],ke=new Map,Se=new Map,De=(e,t,n)=>{const s=Object.assign({},e);for(const o of $e)s[o]=async(s,r)=>{const i=ke.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[o]=i.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=ce(e[0].path,n),a=Se.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 r(...e)}finally{const n=f.performance.now(),r=n-u,p={start:u,end:n,duration:r,context:fe(e)};i.events[o].values.push(p),i.duration+=r,i.increment+=1,ke.set(t,i),a.events[o].values.push(p),a.duration+=r,a.increment+=1,Se.set(s,a)}}))};return s},Ee=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0,((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(re))continue;const n=s.setup;s.setup=async o=>{const r=De(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const{plugins:s,modules:o}={plugins:ke,modules:Se};e.report={timings:{tapables:s,modules:o}}}))}});class Me{constructor(e){this.started={},this.finished=[],this.cwd=e}buildModule(e,t){const n=le(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(de))(e);s.length||s.push("no-loader"),this.started[n]={module:pe(n),timings:{start:f.performance.now(),duration:0,end:0},loaders:s}}succeedModule(e,t){const n=le(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:{}},r=n.loaders.join(",");o.events[r]=o.events[r]||{name:r,values:[]},o.events[r].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 Pe{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:o,end:r,duration:r-o,context:s,type:e}),i.duration+=r-o,i.increment+=1,this.timings.set(t,i)}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 r=f.performance.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,fe(o),r,f.performance.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.performance.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,fe(o),r,f.performance.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.performance.now(),i=t.apply(this,o);return this.saveResult(e,n,s,fe(o),r,f.performance.now()),i}}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,r)=>{const i="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(s,o,r);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,r,i,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(re)||(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 je=(e,t)=>async n=>{t.build.start=Date.now();const s={name:re},o=new Pe(t.cwd),r=new Me(t.cwd);o.throughHooks(n),n.hooks.thisCompilation.tap(s,(e=>{o.throughHooks(e),e.hooks.buildModule.tap(s,(t=>{r.buildModule(t,e)})),e.hooks.succeedModule.tap(s,(t=>{r.succeedModule(t,e)}))})),n.hooks.afterEmit.tapPromise(s,(async t=>{const{timings:n}=o.getResults(),{loaders:s,modules:i}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:i}}}))},Oe={filters:ie},Te=(e,t)=>{const n=t.getLogger(re);let s=0;const o={start:Date.now()},r=(e=>{const t=e[oe]||{},n=t.endPoint||"https://app.datadoghq.com";return{disabled:!1,enableTracing:!1,filters:ie,output:!1,prefix:"",tags:[],...t,endPoint:n.startsWith("http")?n:`https://${n}`}})(e),i=[],a={name:re,enforce:"pre",esbuild:Ee(o,t,n),webpack:je(o,t),rspack:je(o,t)},u={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){t.build.start=t.build.start||Date.now()},buildEnd(){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,i=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(r);me(t,i,e,o.report),await he({report:o.report,metrics:e},r.output,n,t.bundler.outDir),ve(t,n,o.report),await((e,t,n)=>{const s=Date.now();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 o=new Map;for(const t of e)o.has(t.metric)||o.set(t.metric,0),o.set(t.metric,o.get(t.metric)+1);const r=Array.from(o.entries()).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${r.join("\n - ")}`),O({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).then((()=>{n.debug(`Sent metrics in ${M(Date.now()-s)}.`)})).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:r.endPoint},n)}};return r.enableTracing&&i.push(a),i.push(u),i},ze="datadog-analytics-plugin",Ne=e=>{const t=e.getLogger(ze);return e.sendLog=async(n,s={})=>{if("production"===e.env)try{const t={name:e.bundler.name,version:e.bundler.version};await O({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/${t.name}-plugin`,env:e.env,message:n,service:"build-plugins",bundler:t,plugins:e.pluginNames,version:e.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}},[{name:ze,async buildStart(){await e.sendLog("Build started")}}]},Re=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,xe=/(\?|%3F|\|)+/gi,Ie=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=qe(e),Re.lastIndex=0,Re.exec(t)?.[1]||"unknown");var t},Ae=["unknown","commonjsHelpers.js","vite/preload-helper.js"],Fe=(e,t,n)=>{const s=new Set;for(const n of e){const e=qe(n);z(n)||e===t||Ae.includes(e)||s.add(e)}return s},qe=e=>e.split("!").pop().split(xe).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/]+/,""),Ce=(e,t)=>z(t)?b:t.startsWith(e)?t:s.resolve(e,t),Le=(e,t)=>z(t)?b:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):t.split("!").pop().replace(e.bundler.outDir,"").replace(e.cwd,"").split("node_modules").pop().split(xe).shift().replace(/^\/+/,""),_e=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Ce(t,e),n]))),Ke=(e,t)=>({setup(n){const s=new Map,o=[];n.onStart((async()=>{o.push(...await P(n,e,t));for(const t of o){const n=Le(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}})),n.onEnd((n=>{const o=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(!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const r=[],i=[],a=[],u=[],p=[],c={},l={},d=_e(n.metafile.inputs,o),f=_e(n.metafile.outputs,o),m=e=>{if(!z(e))return e;const t=d[Ce(o,e)];if(!t)return e;const n=t.imports.find((e=>!z(e.path)));return n?n.path:e};for(const[t,s]of Object.entries(n.metafile.inputs)){if(z(t))continue;const n=Ce(o,t),i={name:Le(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Ie(t)};c[n]=i,r.push(i)}for(const[r,p]of Object.entries(n.metafile.outputs)){const n=Ce(o,r),d=Le(e,n),f=[];for(const e of Object.keys(p.inputs)){if(z(e))continue;const n=c[Ce(o,e)];n?f.push(n):t.debug(`Input ${e} not found for output ${d}`)}if(p.entryPoint&&!f.length){const e=c[Ce(o,p.entryPoint)];if(!e){t.debug(`Input ${p.entryPoint} not found for output ${d}`);continue}f.push(e)}const h={name:d,filepath:n,inputs:f,size:p.bytes,type:Ie(n)};if(l[n]=h,"map"===h.type&&u.push(h),i.push(h),!p.entryPoint)continue;const g=c[Ce(o,m(p.entryPoint))];if(g){if(!s.get(g.name))continue;const e={...h,name:s.get(g.name)||g.name,outputs:[h],size:h.size};a.push(e)}}for(const e of u){const n=l[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}const h={inputs:{report:c,meta:d},outputs:{report:l,meta:f}},g=/(<runtime>|https:|file:|data:|#)/g,w=e=>!z(e)&&!e.match(g),y=(e,n,s={})=>{if(!w(e))return s;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),s;if(s[r.filepath])return s;s[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),s;if(!i.imports||!i.imports.length)return s;for(const e of i.imports){const t=Ce(o,e.path);y(t,n,s)}return s};for(const e of a){const t={},n={};for(const n of e.inputs)y(n.filepath,h.inputs,t);for(const t of e.outputs)y(t.filepath,h.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.push(e)}for(const e of r){const n=h.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!w(s.path))continue;const n=Ce(o,s.path),r=h.inputs.report[n];r?(e.dependencies.add(r),r.dependents.add(e)):t.debug(`Could not find input file of ${s.path}`)}else t.debug(`Could not find metafile's ${e.name}`)}e.build.outputs=i,e.build.inputs=r,e.build.entries=p}))}}),Be=(e,t)=>{const n={};return{onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){const t=qe(e.id),s=n[t]||{dependencies:new Set,dependents:new Set},o=Fe(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Fe(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)s.dependents.add(e);for(const e of o)s.dependencies.add(e);n[t]=s},writeBundle(s,o){const r=[],i=[],a=[],u=[],p=[],c={},l={};for(const[e,{dependencies:t,dependents:s}]of Object.entries(n)){for(const s of t){const t=qe(s);n[t]||(n[t]={dependencies:new Set,dependents:new Set}),n[t].dependents.has(e)||n[t].dependents.add(e)}for(const t of s){const s=qe(t);n[s]||(n[s]={dependencies:new Set,dependents:new Set}),n[s].dependencies.has(e)||n[s].dependencies.add(e)}}for(const[t,n]of Object.entries(o)){const s={name:t,filepath:Ce(e.bundler.outDir,t),inputs:[],size:"code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),type:Ie(t)};if("map"===s.type&&u.push(s),"modules"in n)for(const[t,o]of Object.entries(n.modules)){if(qe(t)!==t)continue;const n={name:Le(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:o.originalLength,type:Ie(t)};s.inputs.push(n),c[n.filepath]=n,r.push(n)}"isEntry"in n&&n.isEntry&&a.push({...s,name:n.name,size:0,outputs:[s]}),l[s.filepath]=s,i.push(s)}for(const s of r){const o=n[s.filepath];if(o){for(const n of o.dependencies){const o=c[n];o?s.dependencies.add(o):t.debug(`Could not find input for dependency ${Le(e,n)} of ${s.name}`)}for(const n of o.dependents){const o=c[n];o?s.dependents.add(o):t.debug(`Could not find input for dependent ${Le(e,n)} of ${s.name}`)}}else t.debug(`Could not find the import report for ${s.name}.`)}if(u.length)for(const e of u){const n=e.filepath.replace(/\.map$/,""),s=l[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}const d=(n,s={})=>{if(s[n])return s;const r=Le(e,n),i=l[n];if(!i)return t.debug(`Could not find output for ${r}`),s;s[n]=i;const a=o[r];if(!a)return t.debug(`Could not find asset for ${r}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)d(Ce(e.bundler.outDir,t),s);return s};for(const e of a){const t=d(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),p.push(e)}e.build.inputs=r,e.build.outputs=i,e.build.entries=p}}},He=(e,t,n)=>s=>{const o=[],r=[],i=[],a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||z(e)),m=e=>{const t={identifier:e.identifier()};"resource"in e&&"string"==typeof e.resource&&(t.resource=e.resource),"request"in e&&"string"==typeof e.request&&(t.request=e.request),"rawRequest"in e&&"string"==typeof e.rawRequest&&(t.rawRequest=e.rawRequest),"userRequest"in e&&"string"==typeof e.userRequest&&(t.userRequest=e.userRequest);const s=new Set;for(const[o,r]of Object.entries(t))r&&(c.has(r)?(n.debug(`Module ${e.identifier()} is already indexed by ${o}.`),c.get(r)!==e&&n.debug(`Module ${e.identifier()} is indexed with a different value.`)):s.add(r));return s},h=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),h(n,t);if("blocks"in e)for(const n of e.blocks)h(n,t);return t},g=(e,t)=>{if("request"in t&&t.request){if(c.has(t.request))return c.get(t.request);if(e.context&&c.has(Ce(e.context,t.request)))return c.get(Ce(e.context,t.request))}};s.hooks.thisCompilation.tap(t,(s=>{s.hooks.finishModules.tap(t,(t=>{for(const e of t){const t=m(e);for(const n of t)c.set(n,e)}for(const n of t){const t=n.identifier(),s=new Set(h(n).map((e=>{const s=g(n,e);if(!s||!s.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&o)})).filter(Boolean));if(!f(t))continue;for(const e of s){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),d.set(e,n)}const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of s)r.dependencies.add(e);d.set(t,r);const i={size:n.size()||0,name:Le(e,t),dependencies:new Set,dependents:new Set,filepath:t,type:Ie(t)};o.push(i),a.set(t,i)}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}`)}}))})),s.hooks.afterEmit.tap(t,(t=>{const s=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Ce(e.bundler.outDir,t))),m=t.chunkGraph;for(const e of s){const t=d(e),n=(m?m?.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"===Ie(e))continue;const t=p.get(e)||[];p.set(e,[...t,...n])}}for(const t of c){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Ce(e.bundler.outDir,t.name),type:Ie(t.name)};if(u.set(s.filepath,s),r.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}`)}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}`)}for(const[s,o]of t.entrypoints){const t=[],r=[];let a=0;const p=o.chunks.flatMap(d),c=o.chunks.filter((e=>m?m.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"===Ie(e)));for(const e of p){const s=u.get(e);e&&s?"map"===s.type||t.includes(s)||(t.push(s),r.push(...s.inputs),a+=s.size):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(new Set(r)),outputs:t,type:c?Ie(c):"unknown"};i.push(l)}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=r,e.build.entries=i}))},Ue="datadog-build-report-plugin",We=e=>{const t=e.getLogger(Ue);return[{name:Ue,enforce:"post",esbuild:Ke(e,t),rspack:He(e,Ue,t),webpack:He(e,Ue,t),vite:Be(e,t),rollup:Be(e,t)}]},Ge=(e,t)=>{const n=((e,t)=>{const n=e.map((e=>(s.isAbsolute(e)?e:s.resolve(t,e)).split(s.sep))),o=Math.min(...n.map((e=>e.length))),r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0?r.join(s.sep):s.sep})(e,t.cwd);n!==s.sep&&(t.cwd=n)},Je=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),t.options.context&&(e.cwd=t.options.context)},Ve=e=>{const t=new Set,n=n=>{n&&(n.dir?(e.bundler.outDir=n.dir,t.add(n.dir)):n.file&&(e.bundler.outDir=s.dirname(n.file),t.add(n.dir)),"vite"!==e.bundler.name&&Ge(Array.from(t),e))},o=()=>({options(o){if(e.bundler.rawConfig=o,o.input)if(Array.isArray(o.input))for(const e of o.input)t.add(s.dirname(e));else if("object"==typeof o.input)for(const e of Object.values(o.input))t.add(s.dirname(e));else{if("string"!=typeof o.input)throw new Error("Invalid input type");t.add(s.dirname(o.input))}"output"in o&&n(o.output)},outputOptions(e){n(e)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(t){e.bundler.rawConfig=t.initialOptions,t.initialOptions.outdir&&(e.bundler.outDir=t.initialOptions.outdir),t.initialOptions.outfile&&(e.bundler.outDir=s.dirname(t.initialOptions.outfile)),t.initialOptions.absWorkingDir&&(e.cwd=t.initialOptions.absWorkingDir),t.initialOptions.metafile=!0}},webpack:Je(e),rspack:Je(e),vite:{...o(),config(n){n.root?e.cwd=n.root:Ge(Array.from(t),e)}},rollup:o()}]};class Ye{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=i.readFileSync(e,"utf8"),s=JSON.parse(n);if(!s.sources)return void t("Missing 'sources' field in sourcemap.");const o=s.sources;if(0===o.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(o);if(0!==r.length)return r;t(`${o.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 Qe=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await Xe(e);for(const e of t)if(e.name===n)return Ze(e.refs.push);return Ze(t[0].refs.push)},Xe=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},Ze=e=>{try{const t=new h.URL(e);return t.username="",t.password="",t.toString()}catch{return e}},et=async e=>e.revparse("HEAD"),tt=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),nt="datadog-git-plugin",st=(e,t)=>{const n=t.getLogger(nt);return[{name:nt,enforce:"pre",async buildStart(){if(e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)try{const e=await(async e=>{let t,n,s;return[t,n,s]=await Promise.all([Qe(e),et(e),tt(e)]),{hash:n,remote:t,trackedFilesMatcher:new Ye(s)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=m.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return m.simpleGit(t)})(t.cwd));t.git=e}catch(e){n.error(`Could not get git information: ${e.message}`)}}}]},ot="datadog-injection-plugin",rt=/^https?:\/\//,it=async(e,t,n=process.cwd())=>{let s;const o=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)s=o.match(rt)?await(async(e,t=5e3)=>{let n;return Promise.race([O({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await(async(e,t=process.cwd())=>{const n=Ce(t,e);return r.readFile(n,{encoding:"utf-8"})})(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(n){const r=`${e.type} - ${T(o)}`;e.fallback?(t.info(`Fallback for "${r}": ${n.toString()}`),s=await it(e.fallback,t)):(t.warn(`Failed "${r}": ${n.toString()}`),s="")}return s},at=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`},ut=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,r]of e.entries()){const e=await it(r,t,n);e&&s.set(o,{value:e,position:r.position||Q.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},pt=i.promises,ct=(e,t,n)=>({setup(o){const{onStart:r,onResolve:a,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=o,d=[],f=`${I()}.${Q.MIDDLE}.${b}.js`,m=i.realpathSync(g.tmpdir()),h=s.resolve(m,f),w=new RegExp(`${f}$`),y=l.inject;l.inject=y?[...y]:[],l.inject.push(h),r((async()=>{d.push(...await P(o,t,e)),o.initialOptions.inject=y;try{await N(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:w},(async e=>({path:e.path,namespace:ot}))),u({filter:w,namespace:ot},(async()=>({contents:at(n[Q.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),p((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=at(n[Q.BEFORE]),r=at(n[Q.AFTER]);if(!o&&!r)return;const i=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 pt.readFile(e,"utf-8"),n=await c.transform(t,{loader:"default",banner:o,footer:r});await pt.writeFile(e,n.code)}));await Promise.all(i)}))}}),lt=b,dt="?inject-proxy",ft=e=>({banner:t=>t.isEntry?at(e[Q.BEFORE]):"",async resolveId(t,n,s){if(z(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&at(e[Q.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${dt}`}return null},load(t){if(z(t))return at(e[Q.MIDDLE]);if(t.endsWith(dt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(lt)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?at(e[Q.AFTER]):""}),mt=(e,t,n,o,r)=>a=>{const u=new WeakMap,p=(e=>{if(!e?.sources?.ConcatSource)return w.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),c=s.resolve(n.bundler.outDir,`${I()}.${Q.MIDDLE}.${b}.js`);R(c,"");const l=()=>{(async e=>{i.rmSync(e,{force:!0,maxRetries:3,recursive:!0})})(c)};a.hooks.shutdown?a.hooks.shutdown.tap(ot,l):(a.hooks.done.tap(ot,l),a.hooks.failed.tap(ot,l));a.hooks.beforeRun.tapPromise(ot,(async()=>{await ut(t,o,r,n.cwd)})),a.hooks.compilation.tap(ot,(t=>{const n=()=>{const e=at(r[Q.BEFORE]),n=at(r[Q.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:ot,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:ot},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},ht=(e,t)=>{const n=t.getLogger(ot),s=new Map,o={[Q.BEFORE]:new Map,[Q.MIDDLE]:new Map,[Q.AFTER]:new Map};t.inject=e=>{s.set(I(),e)};const r={name:ot,enforce:"post",esbuild:ct(n,t,o),webpack:mt(e,n,t,s,o),rspack:mt(e,n,t,s,o),rollup:ft(o),vite:{...ft(o),enforce:"pre"}};var i;return i=t.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(i)?(r.loadInclude=e=>!!z(e)||null,r.load=e=>z(e)?{code:at(o[Q.MIDDLE])}:null):r.buildStart=async()=>{await ut(n,s,o,t.cwd)},[r]},gt={[oe]:Oe},wt="datadog-build-plugins";var yt="2.5.1-dev-4";const bt=(({bundler:n,version:s})=>e.createUnplugin(((e,o)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",...e}))(e);"esbuild"===o.framework&&(o.esbuildHostName=wt);const i=(({options:e,bundlerName:t,bundlerVersion:n,version:s})=>{const o=process.cwd(),r="webpack"===t?n.split(".")[0]:"",i={errors:[],warnings:[],logs:[],bundler:{name:t,fullName:`${t}${r}`,variant:r,version:n}},a=process.env.BUILD_PLUGINS_ENV||"production",u=v.includes(a)?a:"development";return{auth:e.auth,pluginNames:[],bundler:{...i.bundler,outDir:o},build:i,cwd:o,env:u,getLogger:k(i,e.logLevel),inject:()=>{throw new Error("Inject function called before it was initialized.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},start:Date.now(),version:s}})({options:r,bundlerVersion:n.version||n.VERSION,bundlerName:o.framework,version:s});i.pluginNames.push(wt);const a=[...Ne(i),...We(i),...Ve(i),...st(r,i),...ht(n,i)];if(r.customPlugins){const e=r.customPlugins(r,i);a.push(...e)}r[S]&&!0!==r[S].disabled&&a.push(...Y(r,i)),r[X]&&!0!==r[X].disabled&&a.push(...se(r,i)),r[oe]&&!0!==r[oe].disabled&&a.push(...Te(r,i)),i.pluginNames.push(...a.map((e=>e.name)));const u=new Set(i.pluginNames.filter((e=>i.pluginNames.filter((t=>t===e)).length>1)));if(u.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(u).join(", "))}`);return a})))({bundler:y,version:yt}).rspack,vt=yt,$t=gt;exports.datadogRspackPlugin=bt,exports.helpers=$t,exports.version=vt;
|
|
4
|
+
`;o.info(u),await W(a,e.sourcemaps,s,o)},J=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,V=e=>{const n=t.bold.red,s=e[S]||{},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||J,...s.sourcemaps};o.config=e}return o},Y=(e,t)=>{const n=t.getLogger(D),s=((e,t)=>{const n=[],s=V(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${D}.`);const o={...e[S],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return[{name:D,enforce:"post",async writeBundle(){s.disabled||s.sourcemaps&&await G(s,t,n)}}]};var Q=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Q||{});const X="rum",Z="datadog-rum-plugin",ee=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,te=(e,t)=>{const n=e.sdk;if(n.clientToken)return ee(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 O({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 ee({...e,sdk:{clientToken:s,...n}})}},ne=e=>{const n=t.bold.red,s=e[X]||{},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},se=(e,t)=>{const n=((e,t)=>{const n=[],s=ne(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${Z}.`);const o={...e[X],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(Z));return n.sdk&&(t.inject({type:"file",position:Q.MIDDLE,value:s.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Q.MIDDLE,value:te(n,t)})),[]},oe="telemetry",re="datadog-telemetry-plugin",ie=[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}],ae=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),ue=(e="")=>e.endsWith("/")?e:`${e}/`,pe=(e,t)=>{let n=e;return e.split(ue(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},ce=(e,t)=>e.split("!").pop().replace(ue(t),"./"),le=(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)),ce(s||"no-name",n)},de=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),fe=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),me=(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 r=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;r+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:r,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||[],r=e.build.warnings.length,i=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:i,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:r,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(ae(s,t))}else n.add(ae(e,t))},he=async(e,t,n,o)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:r,metrics:i}=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=s.resolve(o,u);try{const e={},t={};p.timings&&r?.timings&&(t.timings={content:{tapables:r.timings.tapables?Array.from(r.timings.tapables.values()):null,loaders:r.timings.loaders?Array.from(r.timings.loaders.values()):null,modules:r.timings.modules?Array.from(r.timings.modules.values()):null}}),p.metrics&&(t.metrics={content:Array.from(i)});const o=Object.entries(t).map((async([t,o])=>{const r=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return N(e,n)})(s.join(c,`${t}.json`),o.content),n.debug(`Wrote ${t}.json in ${M(Date.now()-r)}`)}catch(s){n.error(`Failed to write ${t}.json in ${M(Date.now()-r)}`),e[t]=s}}));await Promise.all(o),n.debug(`Wrote files in ${M(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}`)}},ge=t.bold.red,we=t.bold.cyan,ye=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},be=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(ye("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:M(e.duration)}))),top:!0};n.sort(ye("increment"));return[s,{name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0}]},ve=(e,t,n)=>{const s=[];var o;n&&(s.push(...be("Loader",n.timings.loaders)),s.push(...be("Tapable",n.timings.tapables)),s.push(...be("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},r=new Set,i=(e=>{const t={bundler:e.bundler,errors:e.errors,warnings:e.warnings,logs:e.logs,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 i.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;r.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!r.size)return[t,n,s];const c=Array.from(r);return c.sort(ye((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort(ye((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort(ye("size")),s.values=c.map((e=>({name:e.name,value:d(e.size)}))),c.sort(ye("aggregatedSize")),o.values=c.map((e=>({name:e.name,value:d(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(ye((e=>e.size))).map((e=>({name:e.name,value:d(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(ye((e=>e.size))).map((e=>({name:e.name,value:d(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(ye((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,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:M(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:M(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:M(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:i.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=T(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))))),r=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${ge(e.value)}] ${" ".repeat(n)}${we(e.name)}\n`}}return t})(s);t.info(r)},$e=["onStart","onLoad","onResolve","onEnd"],ke=new Map,Se=new Map,De=(e,t,n)=>{const s=Object.assign({},e);for(const o of $e)s[o]=async(s,r)=>{const i=ke.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[o]=i.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=ce(e[0].path,n),a=Se.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 r(...e)}finally{const n=f.performance.now(),r=n-u,p={start:u,end:n,duration:r,context:fe(e)};i.events[o].values.push(p),i.duration+=r,i.increment+=1,ke.set(t,i),a.events[o].values.push(p),a.duration+=r,a.increment+=1,Se.set(s,a)}}))};return s},Ee=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0,((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(re))continue;const n=s.setup;s.setup=async o=>{const r=De(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const{plugins:s,modules:o}={plugins:ke,modules:Se};e.report={timings:{tapables:s,modules:o}}}))}});class Me{constructor(e){this.started={},this.finished=[],this.cwd=e}buildModule(e,t){const n=le(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(de))(e);s.length||s.push("no-loader"),this.started[n]={module:pe(n),timings:{start:f.performance.now(),duration:0,end:0},loaders:s}}succeedModule(e,t){const n=le(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:{}},r=n.loaders.join(",");o.events[r]=o.events[r]||{name:r,values:[]},o.events[r].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 Pe{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:o,end:r,duration:r-o,context:s,type:e}),i.duration+=r-o,i.increment+=1,this.timings.set(t,i)}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 r=f.performance.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,fe(o),r,f.performance.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.performance.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,fe(o),r,f.performance.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=f.performance.now(),i=t.apply(this,o);return this.saveResult(e,n,s,fe(o),r,f.performance.now()),i}}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,r)=>{const i="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(s,o,r);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,r,i,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(re)||(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 je=(e,t)=>async n=>{t.build.start=Date.now();const s={name:re},o=new Pe(t.cwd),r=new Me(t.cwd);o.throughHooks(n),n.hooks.thisCompilation.tap(s,(e=>{o.throughHooks(e),e.hooks.buildModule.tap(s,(t=>{r.buildModule(t,e)})),e.hooks.succeedModule.tap(s,(t=>{r.succeedModule(t,e)}))})),n.hooks.afterEmit.tapPromise(s,(async t=>{const{timings:n}=o.getResults(),{loaders:s,modules:i}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:i}}}))},Oe={filters:ie},Te=(e,t)=>{const n=t.getLogger(re);let s=0;const o={start:Date.now()},r=(e=>{const t=e[oe]||{},n=t.endPoint||"https://app.datadoghq.com";return{disabled:!1,enableTracing:!1,filters:ie,output:!1,prefix:"",tags:[],...t,endPoint:n.startsWith("http")?n:`https://${n}`}})(e),i=[],a={name:re,enforce:"pre",esbuild:Ee(o,t,n),webpack:je(o,t),rspack:je(o,t)},u={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){t.build.start=t.build.start||Date.now()},buildEnd(){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,i=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(r);me(t,i,e,o.report),await he({report:o.report,metrics:e},r.output,n,t.bundler.outDir),ve(t,n,o.report),await((e,t,n)=>{const s=Date.now();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 o=new Map;for(const t of e)o.has(t.metric)||o.set(t.metric,0),o.set(t.metric,o.get(t.metric)+1);const r=Array.from(o.entries()).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${r.join("\n - ")}`),O({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).then((()=>{n.debug(`Sent metrics in ${M(Date.now()-s)}.`)})).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:r.endPoint},n)}};return r.enableTracing&&i.push(a),i.push(u),i},ze="datadog-analytics-plugin",Ne=e=>{const t=e.getLogger(ze);return e.sendLog=async(n,s={})=>{if("production"===e.env)try{const t={name:e.bundler.name,version:e.bundler.version};await O({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/${t.name}-plugin`,env:e.env,message:n,service:"build-plugins",bundler:t,plugins:e.pluginNames,version:e.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}},[{name:ze,async buildStart(){await e.sendLog("Build started")}}]},Re=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,xe=/(\?|%3F|\|)+/gi,Ie=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=qe(e),Re.lastIndex=0,Re.exec(t)?.[1]||"unknown");var t},Ae=["unknown","commonjsHelpers.js","vite/preload-helper.js"],Fe=(e,t,n)=>{const s=new Set;for(const n of e){const e=qe(n);z(n)||e===t||Ae.includes(e)||s.add(e)}return s},qe=e=>e.split("!").pop().split(xe).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/]+/,""),Ce=(e,t)=>z(t)?b:t.startsWith(e)?t:s.resolve(e,t),Le=(e,t)=>z(t)?b:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):t.split("!").pop().replace(e.bundler.outDir,"").replace(e.cwd,"").split("node_modules").pop().split(xe).shift().replace(/^\/+/,""),_e=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[Ce(t,e),n]))),Ke=(e,t)=>({setup(n){const s=new Map,o=[];n.onStart((async()=>{o.push(...await P(n,e,t));for(const t of o){const n=Le(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}})),n.onEnd((n=>{const o=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(!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const r=[],i=[],a=[],u=[],p=[],c={},l={},d=_e(n.metafile.inputs,o),f=_e(n.metafile.outputs,o),m=e=>{if(!z(e))return e;const t=d[Ce(o,e)];if(!t)return e;const n=t.imports.find((e=>!z(e.path)));return n?n.path:e};for(const[t,s]of Object.entries(n.metafile.inputs)){if(z(t))continue;const n=Ce(o,t),i={name:Le(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Ie(t)};c[n]=i,r.push(i)}for(const[r,p]of Object.entries(n.metafile.outputs)){const n=Ce(o,r),d=Le(e,n),f=[];for(const e of Object.keys(p.inputs)){if(z(e))continue;const n=c[Ce(o,e)];n?f.push(n):t.debug(`Input ${e} not found for output ${d}`)}if(p.entryPoint&&!f.length){const e=c[Ce(o,p.entryPoint)];if(!e){t.debug(`Input ${p.entryPoint} not found for output ${d}`);continue}f.push(e)}const h={name:d,filepath:n,inputs:f,size:p.bytes,type:Ie(n)};if(l[n]=h,"map"===h.type&&u.push(h),i.push(h),!p.entryPoint)continue;const g=c[Ce(o,m(p.entryPoint))];if(g){if(!s.get(g.name))continue;const e={...h,name:s.get(g.name)||g.name,outputs:[h],size:h.size};a.push(e)}}for(const e of u){const n=l[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}const h={inputs:{report:c,meta:d},outputs:{report:l,meta:f}},g=/(<runtime>|https:|file:|data:|#)/g,w=e=>!z(e)&&!e.match(g),y=(e,n,s={})=>{if(!w(e))return s;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),s;if(s[r.filepath])return s;s[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),s;if(!i.imports||!i.imports.length)return s;for(const e of i.imports){const t=Ce(o,e.path);y(t,n,s)}return s};for(const e of a){const t={},n={};for(const n of e.inputs)y(n.filepath,h.inputs,t);for(const t of e.outputs)y(t.filepath,h.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.push(e)}for(const e of r){const n=h.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!w(s.path))continue;const n=Ce(o,s.path),r=h.inputs.report[n];r?(e.dependencies.add(r),r.dependents.add(e)):t.debug(`Could not find input file of ${s.path}`)}else t.debug(`Could not find metafile's ${e.name}`)}e.build.outputs=i,e.build.inputs=r,e.build.entries=p}))}}),Be=(e,t)=>{const n={};return{onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){const t=qe(e.id),s=n[t]||{dependencies:new Set,dependents:new Set},o=Fe(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Fe(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)s.dependents.add(e);for(const e of o)s.dependencies.add(e);n[t]=s},writeBundle(s,o){const r=[],i=[],a=[],u=[],p=[],c={},l={};for(const[e,{dependencies:t,dependents:s}]of Object.entries(n)){for(const s of t){const t=qe(s);n[t]||(n[t]={dependencies:new Set,dependents:new Set}),n[t].dependents.has(e)||n[t].dependents.add(e)}for(const t of s){const s=qe(t);n[s]||(n[s]={dependencies:new Set,dependents:new Set}),n[s].dependencies.has(e)||n[s].dependencies.add(e)}}for(const[t,n]of Object.entries(o)){const s={name:t,filepath:Ce(e.bundler.outDir,t),inputs:[],size:"code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),type:Ie(t)};if("map"===s.type&&u.push(s),"modules"in n)for(const[t,o]of Object.entries(n.modules)){if(qe(t)!==t)continue;const n={name:Le(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:o.originalLength,type:Ie(t)};s.inputs.push(n),c[n.filepath]=n,r.push(n)}"isEntry"in n&&n.isEntry&&a.push({...s,name:n.name,size:0,outputs:[s]}),l[s.filepath]=s,i.push(s)}for(const s of r){const o=n[s.filepath];if(o){for(const n of o.dependencies){const o=c[n];o?s.dependencies.add(o):t.debug(`Could not find input for dependency ${Le(e,n)} of ${s.name}`)}for(const n of o.dependents){const o=c[n];o?s.dependents.add(o):t.debug(`Could not find input for dependent ${Le(e,n)} of ${s.name}`)}}else t.debug(`Could not find the import report for ${s.name}.`)}if(u.length)for(const e of u){const n=e.filepath.replace(/\.map$/,""),s=l[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}const d=(n,s={})=>{if(s[n])return s;const r=Le(e,n),i=l[n];if(!i)return t.debug(`Could not find output for ${r}`),s;s[n]=i;const a=o[r];if(!a)return t.debug(`Could not find asset for ${r}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)d(Ce(e.bundler.outDir,t),s);return s};for(const e of a){const t=d(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),p.push(e)}e.build.inputs=r,e.build.outputs=i,e.build.entries=p}}},He=(e,t,n)=>s=>{const o=[],r=[],i=[],a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||z(e)),m=e=>{const t={identifier:e.identifier()};"resource"in e&&"string"==typeof e.resource&&(t.resource=e.resource),"request"in e&&"string"==typeof e.request&&(t.request=e.request),"rawRequest"in e&&"string"==typeof e.rawRequest&&(t.rawRequest=e.rawRequest),"userRequest"in e&&"string"==typeof e.userRequest&&(t.userRequest=e.userRequest);const s=new Set;for(const[o,r]of Object.entries(t))r&&(c.has(r)?(n.debug(`Module ${e.identifier()} is already indexed by ${o}.`),c.get(r)!==e&&n.debug(`Module ${e.identifier()} is indexed with a different value.`)):s.add(r));return s},h=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),h(n,t);if("blocks"in e)for(const n of e.blocks)h(n,t);return t},g=(e,t)=>{if("request"in t&&t.request){if(c.has(t.request))return c.get(t.request);if(e.context&&c.has(Ce(e.context,t.request)))return c.get(Ce(e.context,t.request))}};s.hooks.thisCompilation.tap(t,(s=>{s.hooks.finishModules.tap(t,(t=>{for(const e of t){const t=m(e);for(const n of t)c.set(n,e)}for(const n of t){const t=n.identifier(),s=new Set(h(n).map((e=>{const s=g(n,e);if(!s||!s.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&o)})).filter(Boolean));if(!f(t))continue;for(const e of s){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),d.set(e,n)}const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of s)r.dependencies.add(e);d.set(t,r);const i={size:n.size()||0,name:Le(e,t),dependencies:new Set,dependents:new Set,filepath:t,type:Ie(t)};o.push(i),a.set(t,i)}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}`)}}))})),s.hooks.afterEmit.tap(t,(t=>{const s=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>Ce(e.bundler.outDir,t))),m=t.chunkGraph;for(const e of s){const t=d(e),n=(m?m?.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"===Ie(e))continue;const t=p.get(e)||[];p.set(e,[...t,...n])}}for(const t of c){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:Ce(e.bundler.outDir,t.name),type:Ie(t.name)};if(u.set(s.filepath,s),r.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}`)}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}`)}for(const[s,o]of t.entrypoints){const t=[],r=[];let a=0;const p=o.chunks.flatMap(d),c=o.chunks.filter((e=>m?m.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"===Ie(e)));for(const e of p){const s=u.get(e);e&&s?"map"===s.type||t.includes(s)||(t.push(s),r.push(...s.inputs),a+=s.size):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(new Set(r)),outputs:t,type:c?Ie(c):"unknown"};i.push(l)}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=r,e.build.entries=i}))},Ue="datadog-build-report-plugin",We=e=>{const t=e.getLogger(Ue);return[{name:Ue,enforce:"post",esbuild:Ke(e,t),rspack:He(e,Ue,t),webpack:He(e,Ue,t),vite:Be(e,t),rollup:Be(e,t)}]},Ge=(e,t)=>{const n=((e,t)=>{const n=e.map((e=>(s.isAbsolute(e)?e:s.resolve(t,e)).split(s.sep))),o=Math.min(...n.map((e=>e.length))),r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0?r.join(s.sep):s.sep})(e,t.cwd);n!==s.sep&&(t.cwd=n)},Je=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),t.options.context&&(e.cwd=t.options.context)},Ve=e=>{const t=new Set,n=n=>{n&&(n.dir?(e.bundler.outDir=n.dir,t.add(n.dir)):n.file&&(e.bundler.outDir=s.dirname(n.file),t.add(n.dir)),"vite"!==e.bundler.name&&Ge(Array.from(t),e))},o=()=>({options(o){if(e.bundler.rawConfig=o,o.input)if(Array.isArray(o.input))for(const e of o.input)t.add(s.dirname(e));else if("object"==typeof o.input)for(const e of Object.values(o.input))t.add(s.dirname(e));else{if("string"!=typeof o.input)throw new Error("Invalid input type");t.add(s.dirname(o.input))}"output"in o&&n(o.output)},outputOptions(e){n(e)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(t){e.bundler.rawConfig=t.initialOptions,t.initialOptions.outdir&&(e.bundler.outDir=t.initialOptions.outdir),t.initialOptions.outfile&&(e.bundler.outDir=s.dirname(t.initialOptions.outfile)),t.initialOptions.absWorkingDir&&(e.cwd=t.initialOptions.absWorkingDir),t.initialOptions.metafile=!0}},webpack:Je(e),rspack:Je(e),vite:{...o(),config(n){n.root?e.cwd=n.root:Ge(Array.from(t),e)}},rollup:o()}]};class Ye{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=i.readFileSync(e,"utf8"),s=JSON.parse(n);if(!s.sources)return void t("Missing 'sources' field in sourcemap.");const o=s.sources;if(0===o.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(o);if(0!==r.length)return r;t(`${o.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 Qe=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await Xe(e);for(const e of t)if(e.name===n)return Ze(e.refs.push);return Ze(t[0].refs.push)},Xe=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},Ze=e=>{try{const t=new h.URL(e);return t.username="",t.password="",t.toString()}catch{return e}},et=async e=>e.revparse("HEAD"),tt=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),nt="datadog-git-plugin",st=(e,t)=>{const n=t.getLogger(nt);return[{name:nt,enforce:"pre",async buildStart(){if(e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)try{const e=await(async e=>{let t,n,s;return[t,n,s]=await Promise.all([Qe(e),et(e),tt(e)]),{hash:n,remote:t,trackedFilesMatcher:new Ye(s)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=m.simpleGit(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return m.simpleGit(t)})(t.cwd));t.git=e}catch(e){n.error(`Could not get git information: ${e.message}`)}}}]},ot="datadog-injection-plugin",rt=/^https?:\/\//,it=async(e,t,n=process.cwd())=>{let s;const o=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)s=o.match(rt)?await(async(e,t=5e3)=>{let n;return Promise.race([O({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await(async(e,t=process.cwd())=>{const n=Ce(t,e);return r.readFile(n,{encoding:"utf-8"})})(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(n){const r=`${e.type} - ${T(o)}`;e.fallback?(t.info(`Fallback for "${r}": ${n.toString()}`),s=await it(e.fallback,t)):(t.warn(`Failed "${r}": ${n.toString()}`),s="")}return s},at=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`},ut=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,r]of e.entries()){const e=await it(r,t,n);e&&s.set(o,{value:e,position:r.position||Q.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},pt=i.promises,ct=(e,t,n)=>({setup(o){const{onStart:r,onResolve:a,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=o,d=[],f=`${I()}.${Q.MIDDLE}.${b}.js`,m=i.realpathSync(g.tmpdir()),h=s.resolve(m,f),w=new RegExp(`${f}$`),y=l.inject;l.inject=y?[...y]:[],l.inject.push(h),r((async()=>{d.push(...await P(o,t,e)),o.initialOptions.inject=y;try{await N(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),a({filter:w},(async e=>({path:e.path,namespace:ot}))),u({filter:w,namespace:ot},(async()=>({contents:at(n[Q.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),p((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=at(n[Q.BEFORE]),r=at(n[Q.AFTER]);if(!o&&!r)return;const i=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 pt.readFile(e,"utf-8"),n=await c.transform(t,{loader:"default",banner:o,footer:r});await pt.writeFile(e,n.code)}));await Promise.all(i)}))}}),lt=b,dt="?inject-proxy",ft=e=>({banner:t=>t.isEntry?at(e[Q.BEFORE]):"",async resolveId(t,n,s){if(z(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&at(e[Q.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${dt}`}return null},load(t){if(z(t))return at(e[Q.MIDDLE]);if(t.endsWith(dt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(lt)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?at(e[Q.AFTER]):""}),mt=(e,t,n,o,r)=>a=>{const u=new WeakMap,p=(e=>{if(!e?.sources?.ConcatSource)return w.createRequire(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),c=s.resolve(n.bundler.outDir,`${I()}.${Q.MIDDLE}.${b}.js`);R(c,"");const l=()=>{(async e=>{i.rmSync(e,{force:!0,maxRetries:3,recursive:!0})})(c)};a.hooks.shutdown?a.hooks.shutdown.tap(ot,l):(a.hooks.done.tap(ot,l),a.hooks.failed.tap(ot,l));a.hooks.beforeRun.tapPromise(ot,(async()=>{await ut(t,o,r,n.cwd)})),a.hooks.compilation.tap(ot,(t=>{const n=()=>{const e=at(r[Q.BEFORE]),n=at(r[Q.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:ot,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:ot},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},ht=(e,t)=>{const n=t.getLogger(ot),s=new Map,o={[Q.BEFORE]:new Map,[Q.MIDDLE]:new Map,[Q.AFTER]:new Map};t.inject=e=>{s.set(I(),e)};const r={name:ot,enforce:"post",esbuild:ct(n,t,o),webpack:mt(e,n,t,s,o),rspack:mt(e,n,t,s,o),rollup:ft(o),vite:{...ft(o),enforce:"pre"}};var i;return i=t.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(i)?(r.loadInclude=e=>!!z(e)||null,r.load=e=>z(e)?{code:at(o[Q.MIDDLE])}:null):r.buildStart=async()=>{await ut(n,s,o,t.cwd)},[r]},gt={[oe]:Oe},wt="datadog-build-plugins";var yt="2.5.1-dev-5";const bt=(({bundler:n,version:s})=>e.createUnplugin(((e,o)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",...e}))(e);"esbuild"===o.framework&&(o.esbuildHostName=wt);const i=(({options:e,bundlerName:t,bundlerVersion:n,version:s})=>{const o=process.cwd(),r="webpack"===t?n.split(".")[0]:"",i={errors:[],warnings:[],logs:[],bundler:{name:t,fullName:`${t}${r}`,variant:r,version:n}},a=process.env.BUILD_PLUGINS_ENV||"production",u=v.includes(a)?a:"development";return{auth:e.auth,pluginNames:[],bundler:{...i.bundler,outDir:o},build:i,cwd:o,env:u,getLogger:k(i,e.logLevel),inject:()=>{throw new Error("Inject function called before it was initialized.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},start:Date.now(),version:s}})({options:r,bundlerVersion:n.version||n.VERSION,bundlerName:o.framework,version:s});i.pluginNames.push(wt);const a=[...Ne(i),...We(i),...Ve(i),...st(r,i),...ht(n,i)];if(r.customPlugins){const e=r.customPlugins(r,i);a.push(...e)}r[S]&&!0!==r[S].disabled&&a.push(...Y(r,i)),r[X]&&!0!==r[X].disabled&&a.push(...se(r,i)),r[oe]&&!0!==r[oe].disabled&&a.push(...Te(r,i)),i.pluginNames.push(...a.map((e=>e.name)));const u=new Set(i.pluginNames.filter((e=>i.pluginNames.filter((t=>t===e)).length>1)));if(u.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(u).join(", "))}`);return a})))({bundler:y,version:yt}).rspack,vt=yt,$t=gt;exports.datadogRspackPlugin=bt,exports.helpers=$t,exports.version=vt;
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/dist/src/index.mjs
CHANGED
|
@@ -9,5 +9,5 @@ const require = cjsModule.createRequire(import.meta.url);
|
|
|
9
9
|
const $="__datadog-helper-file",k=["development","production","test"],S={debug:0,info:1,warn:2,error:3,none:4},D=(e,n="warn")=>s=>{const o=(e=>e.split(">").map((e=>e.replace(/^datadog-|-plugin$/g,""))).join(">"))(s),r=(s,r="debug")=>{let i=t.dim,a=console.log;"error"===r?(i=t.red,a=console.error):"warn"===r?(i=t.yellow,a=console.warn):"info"===r&&(i=t.cyan,a=console.log);const u=`[${r}|${e.bundler.fullName}|${o}]`,p="string"==typeof s?s:JSON.stringify(s,null,2);e.logs.push({bundler:e.bundler.fullName,pluginName:o,type:r,message:p,time:Date.now()}),"error"===r&&e.errors.push(p),"warn"===r&&e.warnings.push(p),S[r]>=S[n]&&a(`${i(u)} ${p}`)};return{getLogger:t=>D(e,n)(`${o}>${t}`),error:e=>r(e,"error"),warn:e=>r(e,"warn"),info:e=>r(e,"info"),debug:e=>r(e,"debug")}},E="errorTracking",M="datadog-error-tracking-plugin",P=(e,n,o)=>{if(".map"!==s.extname(o))throw new Error(`The file ${t.green.bold(o)} is not a sourcemap.`);const r=o.replace(/\.map$/,""),i=r.replace(n.bundler.outDir,"");return{minifiedFilePath:r,minifiedUrl:e.minifiedPathPrefix?s.join(e.minifiedPathPrefix,i):i,relativePath:i}},j=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(),r=n.getUTCSeconds(),i=n.getUTCMilliseconds();return`${t?`${t}d `:""}${s?`${s}h `:""}${o?`${o}m `:""}${r?`${r}s `:""}${i?`${i}ms`:""}`.trim()},O=async(e,t,n)=>{const s=[],o=e.initialOptions.entryPoints,r=[],i=[];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 a=r.flatMap((e=>{return(t=e.path,t.includes("*")?p.sync(t):[t]).map((t=>[e,t]));var t})).map((async([n,o])=>{const r=await e.resolve(o,{kind:"entry-point",resolveDir:t.cwd});r.errors.length&&i.push(...r.errors.map((e=>e.text))),r.path&&s.push({name:n.name,resolved:r.path,original:n.path})}));for(const e of i)n.error(e);return await Promise.all(a),s},T=[400,403,413],z=e=>{const{auth:t,url:n,method:s="GET",getData:r,type:i="text"}=e,a={retries:0===e.retries?0:e.retries||5,onRetry:e.onRetry,maxTimeout:e.maxTimeout,minTimeout:e.minTimeout};return o((async(e,o)=>{let a;try{const e={method:s,duplex:"half"};let o={};if(t?.apiKey&&(o["DD-API-KEY"]=t.apiKey),t?.appKey&&(o["DD-APPLICATION-KEY"]=t.appKey),"function"==typeof r){const{data:t,headers:n}=await r();e.body=t,o={...o,...n}}a=await fetch(n,{...e,headers:o})}catch(t){return e(t),{}}if(!a.ok){const t=`HTTP ${a.status} ${a.statusText}`;if(T.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)},N=(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)),r=s-o;return`${e.slice(0,o)}${n}${e.slice(-r)}`},R=e=>e.includes($),x=async(e,t)=>{await(async e=>r.mkdir(e,{recursive:!0}))(s.dirname(e)),await r.writeFile(e,t,{encoding:"utf-8"})},I=(e,t)=>{var n;n=s.dirname(e),a.mkdirSync(n,{recursive:!0}),a.writeFileSync(e,t,{encoding:"utf-8"})};let A=0;const F=()=>`${Date.now()}.${performance.now()}.${++A}`,C=/[/]+|[\\]+/g,L=/^[/]+|^[\\]+|[/]+$|[\\]+$/g,_=(e,t)=>{const n=e.replace(L,"").split(C),s=t.replace(L,"").split(C),o=n.join("/");let r="";for(let e=0;e<s.length;e+=1){const t=s.slice(-e).join("/");o.startsWith(t)&&(r=t)}return r},q=async e=>{const t={empty:!1,exists:!0};try{0===(await u.stat(e)).size&&(t.empty=!0)}catch(e){if("ENOENT"!==e.code)throw e;t.exists=!1}return t},K=async(e,t,n,o)=>{const r=await(async(e,t)=>{const[n,s]=await Promise.all([q(e.minifiedFilePath),q(e.sourcemapFilePath)]);return{file:n,sourcemap:s,repeatedPrefix:_(e.relativePath,t)}})(e,n),i=[],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(o)try{u.set("repository",{type:"string",options:{contentType:"application/json",filename:"repository"},value:JSON.stringify({data:[{files:o.trackedFilesMatcher.matchSourcemap(e.sourcemapFilePath,(t=>{a.push(`${s.basename(e.sourcemapFilePath)}: "${t}"`)})),hash:o.hash,repository_url:o.remote}],version:1})})}catch(t){a.push(`Could not attach git data for sourcemap ${e.sourcemapFilePath}: ${t.message}`)}return r.file.empty&&i.push(`Minified file is empty: ${e.minifiedFilePath}`),r.file.exists||i.push(`Minified file not found: ${e.minifiedFilePath}`),r.sourcemap.empty&&i.push(`Sourcemap file is empty: ${e.sourcemapFilePath}`),r.sourcemap.exists||i.push(`Sourcemap file not found: ${e.sourcemapFilePath}`),r.repeatedPrefix&&a.push(`The minified file path contains a repeated pattern with the minified path prefix: ${r.repeatedPrefix}`),{content:u,errors:i,warnings:a}},B=t.green.bold,H=t.yellow.bold,W=t.red.bold,U=async(e,t)=>{if("function"==typeof a.openAsBlob){const n=await a.openAsBlob(e,{type:t.contentType});return new c([n],t.filename)}{const n=d.toWeb(a.createReadStream(e)),s=await new Response(n).blob();return new c([s],t.filename,{type:t.contentType})}},G=(e,t={})=>async()=>{const n=new FormData,s=f();for(const[t,s]of e.content){const e="file"===s.type?await U(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:d.fromWeb(o.body).pipe(s),headers:{"Content-Encoding":"gzip",...t,...Object.fromEntries(o.headers.entries())}}},J=async(e,t,n,s)=>{const o=Date.now(),r=t.minifiedPathPrefix,i={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,i,r,n.git)))),u=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 - ")}`),u.length>0){const e=`Failed to prepare payloads, aborting upload :\n - ${u.join("\n - ")}`;if(s.error(e),!0===t.bailOnError)throw new Error(e);return}const{errors:c,warnings:d}=await(async(e,t,n,s)=>{const o=[],r=[];if(!n.auth?.apiKey)return o.push({error:new Error("No authentication token provided")}),{errors:o,warnings:r};if(0===e.length)return r.push("No sourcemaps to upload"),{errors:o,warnings:r};const i=new(l.default?l.default:l)({concurrency:t.maxConcurrency}),a={"DD-API-KEY":n.auth.apiKey,"DD-EVP-ORIGIN":`${n.bundler.fullName}-build-plugin_sourcemaps`,"DD-EVP-ORIGIN-VERSION":n.version},u=[];for(const p of e){const e={sourcemap:p.content.get("source_map")?.path.replace(n.bundler.outDir,"."),file:p.content.get("minified_file")?.path.replace(n.bundler.outDir,".")};s.debug(`Queuing ${B(e.sourcemap)} | ${B(e.file)}`),u.push(i.add((async()=>{try{await z({url:t.intakeUrl,method:"POST",getData:G(p,a),onRetry:(t,n)=>{const o=`Failed to upload ${H(e.sourcemap)} | ${H(e.file)}:\n ${t.message}\nRetrying ${n}/5`;r.push(o),s.debug(o)}}),s.debug(`Sent ${B(e.sourcemap)} | ${B(e.file)}`)}catch(n){if(o.push({metadata:e,error:n}),!0===t.bailOnError)throw n}})))}return await Promise.all(u),await i.onIdle(),{warnings:r,errors:o}})(a,t,n,s);if(s.info(`Done uploading ${B(e.length.toString())} sourcemaps in ${B(j(Date.now()-o))}.`),c.length>0){const e=`Failed to upload some sourcemaps:\n${` - ${c.map((({metadata:e,error:t})=>e?`${W(e.file)} | ${W(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 - ")}`)},V=async(e,s,o)=>{const r=t.green.bold,i=Object.entries(e.sourcemaps).map((([e,t])=>` - ${e}: ${r(t.toString())}`)).join("\n"),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=>({...P(e,t,n),sourcemapFilePath:n,minifiedPathPrefix:e.minifiedPathPrefix})))})(e.sourcemaps,s),u=n`
|
|
10
10
|
Uploading ${r(a.length.toString())} sourcemaps with configuration:
|
|
11
11
|
${i}
|
|
12
|
-
`;o.info(u),await J(a,e.sourcemaps,s,o)},Y=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,Q=e=>{const n=t.bold.red,s=e[E]||{},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||Y,...s.sourcemaps};o.config=e}return o},X=(e,t)=>{const n=t.getLogger(M),s=((e,t)=>{const n=[],s=Q(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${M}.`);const o={...e[E],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return[{name:M,enforce:"post",async writeBundle(){s.disabled||s.sourcemaps&&await V(s,t,n)}}]};var Z=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Z||{});const ee="rum",te="datadog-rum-plugin",ne=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,se=(e,t)=>{const n=e.sdk;if(n.clientToken)return ne(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 z({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 ne({...e,sdk:{clientToken:s,...n}})}},oe=e=>{const n=t.bold.red,s=e[ee]||{},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},re=(e,t)=>{const n=((e,t)=>{const n=[],s=oe(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${te}.`);const o={...e[ee],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(te));return n.sdk&&(t.inject({type:"file",position:Z.MIDDLE,value:s.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Z.MIDDLE,value:se(n,t)})),[]},ie="telemetry",ae="datadog-telemetry-plugin",ue=[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}],pe=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),ce=(e="")=>e.endsWith("/")?e:`${e}/`,le=(e,t)=>{let n=e;return e.split(ce(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},de=(e,t)=>e.split("!").pop().replace(ce(t),"./"),fe=(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)),de(s||"no-name",n)},me=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),he=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),ge=(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 r=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;r+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:r,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||[],r=e.build.warnings.length,i=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:i,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:r,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(pe(s,t))}else n.add(pe(e,t))},we=async(e,t,n,o)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:r,metrics:i}=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=s.resolve(o,u);try{const e={},t={};p.timings&&r?.timings&&(t.timings={content:{tapables:r.timings.tapables?Array.from(r.timings.tapables.values()):null,loaders:r.timings.loaders?Array.from(r.timings.loaders.values()):null,modules:r.timings.modules?Array.from(r.timings.modules.values()):null}}),p.metrics&&(t.metrics={content:Array.from(i)});const o=Object.entries(t).map((async([t,o])=>{const r=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return x(e,n)})(s.join(c,`${t}.json`),o.content),n.debug(`Wrote ${t}.json in ${j(Date.now()-r)}`)}catch(s){n.error(`Failed to write ${t}.json in ${j(Date.now()-r)}`),e[t]=s}}));await Promise.all(o),n.debug(`Wrote files in ${j(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}`)}},ye=t.bold.red,be=t.bold.cyan,ve=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},$e=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(ve("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:j(e.duration)}))),top:!0};n.sort(ve("increment"));const o={name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0};return[s,o]},ke=(e,t,n)=>{const s=[];var o;n&&(s.push(...$e("Loader",n.timings.loaders)),s.push(...$e("Tapable",n.timings.tapables)),s.push(...$e("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},r=new Set,i=(e=>{const t={bundler:e.bundler,errors:e.errors,warnings:e.warnings,logs:e.logs,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 i.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;r.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!r.size)return[t,n,s];const c=Array.from(r);return c.sort(ve((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort(ve((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort(ve("size")),s.values=c.map((e=>({name:e.name,value:m(e.size)}))),c.sort(ve("aggregatedSize")),o.values=c.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(ve((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(ve((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(ve((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,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:j(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:j(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:j(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:i.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=N(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))))),r=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${ye(e.value)}] ${" ".repeat(n)}${be(e.name)}\n`}}return t})(s);t.info(r)},Se=["onStart","onLoad","onResolve","onEnd"],De=new Map,Ee=new Map,Me=(e,t,n)=>{const s=Object.assign({},e);for(const o of Se)s[o]=async(s,r)=>{const i=De.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[o]=i.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=de(e[0].path,n),a=Ee.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=h.now();try{return await r(...e)}finally{const n=h.now(),r=n-u,p={start:u,end:n,duration:r,context:he(e)};i.events[o].values.push(p),i.duration+=r,i.increment+=1,De.set(t,i),a.events[o].values.push(p),a.duration+=r,a.increment+=1,Ee.set(s,a)}}))};return s},Pe=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0,((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(ae))continue;const n=s.setup;s.setup=async o=>{const r=Me(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const{plugins:s,modules:o}={plugins:De,modules:Ee};e.report={timings:{tapables:s,modules:o}}}))}});class je{constructor(e){this.started={},this.finished=[],this.cwd=e}buildModule(e,t){const n=fe(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(me))(e);s.length||s.push("no-loader"),this.started[n]={module:le(n),timings:{start:h.now(),duration:0,end:0},loaders:s}}succeedModule(e,t){const n=fe(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=h.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:{}},r=n.loaders.join(",");o.events[r]=o.events[r]||{name:r,values:[]},o.events[r].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 Oe{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:o,end:r,duration:r-o,context:s,type:e}),i.duration+=r-o,i.increment+=1,this.timings.set(t,i)}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 r=h.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,he(o),r,h.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,he(o),r,h.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.now(),i=t.apply(this,o);return this.saveResult(e,n,s,he(o),r,h.now()),i}}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,r)=>{const i="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(s,o,r);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,r,i,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(ae)||(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 Te=(e,t)=>async n=>{t.build.start=Date.now();const s={name:ae},o=new Oe(t.cwd),r=new je(t.cwd);o.throughHooks(n),n.hooks.thisCompilation.tap(s,(e=>{o.throughHooks(e),e.hooks.buildModule.tap(s,(t=>{r.buildModule(t,e)})),e.hooks.succeedModule.tap(s,(t=>{r.succeedModule(t,e)}))})),n.hooks.afterEmit.tapPromise(s,(async t=>{const{timings:n}=o.getResults(),{loaders:s,modules:i}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:i}}}))},ze={filters:ue},Ne=(e,t)=>{const n=t.getLogger(ae);let s=0;const o={start:Date.now()},r=(e=>{const t=e[ie]||{},n=t.endPoint||"https://app.datadoghq.com";return{disabled:!1,enableTracing:!1,filters:ue,output:!1,prefix:"",tags:[],...t,endPoint:n.startsWith("http")?n:`https://${n}`}})(e),i=[],a={name:ae,enforce:"pre",esbuild:Pe(o,t,n),webpack:Te(o,t),rspack:Te(o,t)},u={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){t.build.start=t.build.start||Date.now()},buildEnd(){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,i=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(r);ge(t,i,e,o.report),await we({report:o.report,metrics:e},r.output,n,t.bundler.outDir),ke(t,n,o.report),await((e,t,n)=>{const s=Date.now();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 o=new Map;for(const t of e)o.has(t.metric)||o.set(t.metric,0),o.set(t.metric,o.get(t.metric)+1);const r=Array.from(o.entries()).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${r.join("\n - ")}`),z({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).then((()=>{n.debug(`Sent metrics in ${j(Date.now()-s)}.`)})).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:r.endPoint},n)}};return r.enableTracing&&i.push(a),i.push(u),i},Re="datadog-analytics-plugin",xe=e=>{const t=e.getLogger(Re);return e.sendLog=async(n,s={})=>{if("production"===e.env)try{const t={name:e.bundler.name,version:e.bundler.version};await z({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/${t.name}-plugin`,env:e.env,message:n,service:"build-plugins",bundler:t,plugins:e.pluginNames,version:e.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}},[{name:Re,async buildStart(){await e.sendLog("Build started")}}]},Ie=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Ae=/(\?|%3F|\|)+/gi,Fe=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=_e(e),Ie.lastIndex=0,Ie.exec(t)?.[1]||"unknown");var t},Ce=["unknown","commonjsHelpers.js","vite/preload-helper.js"],Le=(e,t,n)=>{const s=new Set;for(const n of e){const e=_e(n);R(n)||e===t||Ce.includes(e)||s.add(e)}return s},_e=e=>e.split("!").pop().split(Ae).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/]+/,""),qe=(e,t)=>R(t)?$:t.startsWith(e)?t:s.resolve(e,t),Ke=(e,t)=>R(t)?$:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):t.split("!").pop().replace(e.bundler.outDir,"").replace(e.cwd,"").split("node_modules").pop().split(Ae).shift().replace(/^\/+/,""),Be=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[qe(t,e),n]))),He=(e,t)=>({setup(n){const s=new Map,o=[];n.onStart((async()=>{o.push(...await O(n,e,t));for(const t of o){const n=Ke(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}})),n.onEnd((n=>{const o=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(!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const r=[],i=[],a=[],u=[],p=[],c={},l={},d=Be(n.metafile.inputs,o),f=Be(n.metafile.outputs,o),m=e=>{if(!R(e))return e;const t=d[qe(o,e)];if(!t)return e;const n=t.imports.find((e=>!R(e.path)));return n?n.path:e};for(const[t,s]of Object.entries(n.metafile.inputs)){if(R(t))continue;const n=qe(o,t),i={name:Ke(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Fe(t)};c[n]=i,r.push(i)}for(const[r,p]of Object.entries(n.metafile.outputs)){const n=qe(o,r),d=Ke(e,n),f=[];for(const e of Object.keys(p.inputs)){if(R(e))continue;const n=c[qe(o,e)];n?f.push(n):t.debug(`Input ${e} not found for output ${d}`)}if(p.entryPoint&&!f.length){const e=c[qe(o,p.entryPoint)];if(!e){t.debug(`Input ${p.entryPoint} not found for output ${d}`);continue}f.push(e)}const h={name:d,filepath:n,inputs:f,size:p.bytes,type:Fe(n)};if(l[n]=h,"map"===h.type&&u.push(h),i.push(h),!p.entryPoint)continue;const g=c[qe(o,m(p.entryPoint))];if(g){if(!s.get(g.name))continue;const e={...h,name:s.get(g.name)||g.name,outputs:[h],size:h.size};a.push(e)}}for(const e of u){const n=l[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}const h={inputs:{report:c,meta:d},outputs:{report:l,meta:f}},g=/(<runtime>|https:|file:|data:|#)/g,w=e=>!R(e)&&!e.match(g),y=(e,n,s={})=>{if(!w(e))return s;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),s;if(s[r.filepath])return s;s[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),s;if(!i.imports||!i.imports.length)return s;for(const e of i.imports){const t=qe(o,e.path);y(t,n,s)}return s};for(const e of a){const t={},n={};for(const n of e.inputs)y(n.filepath,h.inputs,t);for(const t of e.outputs)y(t.filepath,h.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.push(e)}for(const e of r){const n=h.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!w(s.path))continue;const n=qe(o,s.path),r=h.inputs.report[n];r?(e.dependencies.add(r),r.dependents.add(e)):t.debug(`Could not find input file of ${s.path}`)}else t.debug(`Could not find metafile's ${e.name}`)}e.build.outputs=i,e.build.inputs=r,e.build.entries=p}))}}),We=(e,t)=>{const n={};return{onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){const t=_e(e.id),s=n[t]||{dependencies:new Set,dependents:new Set},o=Le(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Le(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)s.dependents.add(e);for(const e of o)s.dependencies.add(e);n[t]=s},writeBundle(s,o){const r=[],i=[],a=[],u=[],p=[],c={},l={};for(const[e,{dependencies:t,dependents:s}]of Object.entries(n)){for(const s of t){const t=_e(s);n[t]||(n[t]={dependencies:new Set,dependents:new Set}),n[t].dependents.has(e)||n[t].dependents.add(e)}for(const t of s){const s=_e(t);n[s]||(n[s]={dependencies:new Set,dependents:new Set}),n[s].dependencies.has(e)||n[s].dependencies.add(e)}}for(const[t,n]of Object.entries(o)){const s={name:t,filepath:qe(e.bundler.outDir,t),inputs:[],size:"code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),type:Fe(t)};if("map"===s.type&&u.push(s),"modules"in n)for(const[t,o]of Object.entries(n.modules)){if(_e(t)!==t)continue;const n={name:Ke(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:o.originalLength,type:Fe(t)};s.inputs.push(n),c[n.filepath]=n,r.push(n)}"isEntry"in n&&n.isEntry&&a.push({...s,name:n.name,size:0,outputs:[s]}),l[s.filepath]=s,i.push(s)}for(const s of r){const o=n[s.filepath];if(o){for(const n of o.dependencies){const o=c[n];o?s.dependencies.add(o):t.debug(`Could not find input for dependency ${Ke(e,n)} of ${s.name}`)}for(const n of o.dependents){const o=c[n];o?s.dependents.add(o):t.debug(`Could not find input for dependent ${Ke(e,n)} of ${s.name}`)}}else t.debug(`Could not find the import report for ${s.name}.`)}if(u.length)for(const e of u){const n=e.filepath.replace(/\.map$/,""),s=l[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}const d=(n,s={})=>{if(s[n])return s;const r=Ke(e,n),i=l[n];if(!i)return t.debug(`Could not find output for ${r}`),s;s[n]=i;const a=o[r];if(!a)return t.debug(`Could not find asset for ${r}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)d(qe(e.bundler.outDir,t),s);return s};for(const e of a){const t=d(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),p.push(e)}e.build.inputs=r,e.build.outputs=i,e.build.entries=p}}},Ue=(e,t,n)=>s=>{const o=[],r=[],i=[],a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||R(e)),m=e=>{const t={identifier:e.identifier()};"resource"in e&&"string"==typeof e.resource&&(t.resource=e.resource),"request"in e&&"string"==typeof e.request&&(t.request=e.request),"rawRequest"in e&&"string"==typeof e.rawRequest&&(t.rawRequest=e.rawRequest),"userRequest"in e&&"string"==typeof e.userRequest&&(t.userRequest=e.userRequest);const s=new Set;for(const[o,r]of Object.entries(t))r&&(c.has(r)?(n.debug(`Module ${e.identifier()} is already indexed by ${o}.`),c.get(r)!==e&&n.debug(`Module ${e.identifier()} is indexed with a different value.`)):s.add(r));return s},h=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),h(n,t);if("blocks"in e)for(const n of e.blocks)h(n,t);return t},g=(e,t)=>{if("request"in t&&t.request){if(c.has(t.request))return c.get(t.request);if(e.context&&c.has(qe(e.context,t.request)))return c.get(qe(e.context,t.request))}};s.hooks.thisCompilation.tap(t,(s=>{s.hooks.finishModules.tap(t,(t=>{for(const e of t){const t=m(e);for(const n of t)c.set(n,e)}for(const n of t){const t=n.identifier(),s=new Set(h(n).map((e=>{const s=g(n,e);if(!s||!s.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&o)})).filter(Boolean));if(!f(t))continue;for(const e of s){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),d.set(e,n)}const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of s)r.dependencies.add(e);d.set(t,r);const i={size:n.size()||0,name:Ke(e,t),dependencies:new Set,dependents:new Set,filepath:t,type:Fe(t)};o.push(i),a.set(t,i)}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}`)}}))})),s.hooks.afterEmit.tap(t,(t=>{const s=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>qe(e.bundler.outDir,t))),m=t.chunkGraph;for(const e of s){const t=d(e),n=(m?m?.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"===Fe(e))continue;const t=p.get(e)||[];p.set(e,[...t,...n])}}for(const t of c){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:qe(e.bundler.outDir,t.name),type:Fe(t.name)};if(u.set(s.filepath,s),r.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}`)}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}`)}for(const[s,o]of t.entrypoints){const t=[],r=[];let a=0;const p=o.chunks.flatMap(d),c=o.chunks.filter((e=>m?m.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"===Fe(e)));for(const e of p){const s=u.get(e);e&&s?"map"===s.type||t.includes(s)||(t.push(s),r.push(...s.inputs),a+=s.size):n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:c?qe(e.bundler.outDir,c):"unknown",size:a,inputs:Array.from(new Set(r)),outputs:t,type:c?Fe(c):"unknown"};i.push(l)}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=r,e.build.entries=i}))},Ge="datadog-build-report-plugin",Je=e=>{const t=e.getLogger(Ge);return[{name:Ge,enforce:"post",esbuild:He(e,t),rspack:Ue(e,Ge,t),webpack:Ue(e,Ge,t),vite:We(e,t),rollup:We(e,t)}]},Ve=(e,t)=>{const n=((e,t)=>{const n=e.map((e=>(s.isAbsolute(e)?e:s.resolve(t,e)).split(s.sep))),o=Math.min(...n.map((e=>e.length))),r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0?r.join(s.sep):s.sep})(e,t.cwd);n!==s.sep&&(t.cwd=n)},Ye=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),t.options.context&&(e.cwd=t.options.context)},Qe=e=>{const t=new Set,n=n=>{n&&(n.dir?(e.bundler.outDir=n.dir,t.add(n.dir)):n.file&&(e.bundler.outDir=s.dirname(n.file),t.add(n.dir)),"vite"!==e.bundler.name&&Ve(Array.from(t),e))},o=()=>({options(o){if(e.bundler.rawConfig=o,o.input)if(Array.isArray(o.input))for(const e of o.input)t.add(s.dirname(e));else if("object"==typeof o.input)for(const e of Object.values(o.input))t.add(s.dirname(e));else{if("string"!=typeof o.input)throw new Error("Invalid input type");t.add(s.dirname(o.input))}"output"in o&&n(o.output)},outputOptions(e){n(e)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(t){e.bundler.rawConfig=t.initialOptions,t.initialOptions.outdir&&(e.bundler.outDir=t.initialOptions.outdir),t.initialOptions.outfile&&(e.bundler.outDir=s.dirname(t.initialOptions.outfile)),t.initialOptions.absWorkingDir&&(e.cwd=t.initialOptions.absWorkingDir),t.initialOptions.metafile=!0}},webpack:Ye(e),rspack:Ye(e),vite:{...o(),config(n){n.root?e.cwd=n.root:Ve(Array.from(t),e)}},rollup:o()}]};class Xe{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=a.readFileSync(e,"utf8"),s=JSON.parse(n);if(!s.sources)return void t("Missing 'sources' field in sourcemap.");const o=s.sources;if(0===o.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(o);if(0!==r.length)return r;t(`${o.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 Ze=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await et(e);for(const e of t)if(e.name===n)return tt(e.refs.push);return tt(t[0].refs.push)},et=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},tt=e=>{try{const t=new w(e);return t.username="",t.password="",t.toString()}catch{return e}},nt=async e=>e.revparse("HEAD"),st=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ot="datadog-git-plugin",rt=(e,t)=>{const n=t.getLogger(ot);return[{name:ot,enforce:"pre",async buildStart(){if(e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)try{const e=await(async e=>{let t,n,s;return[t,n,s]=await Promise.all([Ze(e),nt(e),st(e)]),{hash:n,remote:t,trackedFilesMatcher:new Xe(s)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=g(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return g(t)})(t.cwd));t.git=e}catch(e){n.error(`Could not get git information: ${e.message}`)}}}]},it="datadog-injection-plugin",at=/^https?:\/\//,ut=async(e,t,n=process.cwd())=>{let s;const o=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)s=o.match(at)?await(async(e,t=5e3)=>{let n;return Promise.race([z({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await(async(e,t=process.cwd())=>{const n=qe(t,e);return i(n,{encoding:"utf-8"})})(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(n){const r=`${e.type} - ${N(o)}`;e.fallback?(t.info(`Fallback for "${r}": ${n.toString()}`),s=await ut(e.fallback,t)):(t.warn(`Failed "${r}": ${n.toString()}`),s="")}return s},pt=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`},ct=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,r]of e.entries()){const e=await ut(r,t,n);e&&s.set(o,{value:e,position:r.position||Z.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},lt=a.promises,dt=(e,t,n)=>({setup(o){const{onStart:r,onResolve:i,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=o,d=[],f=`${F()}.${Z.MIDDLE}.${$}.js`,m=a.realpathSync(y.tmpdir()),h=s.resolve(m,f),g=new RegExp(`${f}$`),w=l.inject;l.inject=w?[...w]:[],l.inject.push(h),r((async()=>{d.push(...await O(o,t,e)),o.initialOptions.inject=w;try{await x(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),i({filter:g},(async e=>({path:e.path,namespace:it}))),u({filter:g,namespace:it},(async()=>({contents:pt(n[Z.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),p((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=pt(n[Z.BEFORE]),r=pt(n[Z.AFTER]);if(!o&&!r)return;const i=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?qe(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await lt.readFile(e,"utf-8"),n=await c.transform(t,{loader:"default",banner:o,footer:r});await lt.writeFile(e,n.code)}));await Promise.all(i)}))}}),ft=$,mt="?inject-proxy",ht=e=>({banner:t=>t.isEntry?pt(e[Z.BEFORE]):"",async resolveId(t,n,s){if(R(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&pt(e[Z.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${mt}`}return null},load(t){if(R(t))return pt(e[Z.MIDDLE]);if(t.endsWith(mt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(ft)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?pt(e[Z.AFTER]):""}),gt=(e,t,n,o,r)=>i=>{const u=new WeakMap,p=(e=>{if(!e?.sources?.ConcatSource)return b(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),c=s.resolve(n.bundler.outDir,`${F()}.${Z.MIDDLE}.${$}.js`);I(c,"");const l=()=>{(async e=>{a.rmSync(e,{force:!0,maxRetries:3,recursive:!0})})(c)};i.hooks.shutdown?i.hooks.shutdown.tap(it,l):(i.hooks.done.tap(it,l),i.hooks.failed.tap(it,l));i.hooks.beforeRun.tapPromise(it,(async()=>{await ct(t,o,r,n.cwd)})),i.hooks.compilation.tap(it,(t=>{const n=()=>{const e=pt(r[Z.BEFORE]),n=pt(r[Z.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:it,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:it},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}})(i.options.entry);i.options.entry=d},wt=(e,t)=>{const n=t.getLogger(it),s=new Map,o={[Z.BEFORE]:new Map,[Z.MIDDLE]:new Map,[Z.AFTER]:new Map};t.inject=e=>{s.set(F(),e)};const r={name:it,enforce:"post",esbuild:dt(n,t,o),webpack:gt(e,n,t,s,o),rspack:gt(e,n,t,s,o),rollup:ht(o),vite:{...ht(o),enforce:"pre"}};var i;return i=t.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(i)?(r.loadInclude=e=>!!R(e)||null,r.load=e=>R(e)?{code:pt(o[Z.MIDDLE])}:null):r.buildStart=async()=>{await ct(n,s,o,t.cwd)},[r]},yt={[ie]:ze},bt="datadog-build-plugins";var vt="2.5.1-dev-4";const $t=(({bundler:n,version:s})=>e(((e,o)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",...e}))(e);"esbuild"===o.framework&&(o.esbuildHostName=bt);const i=(({options:e,bundlerName:t,bundlerVersion:n,version:s})=>{const o=process.cwd(),r="webpack"===t?n.split(".")[0]:"",i={errors:[],warnings:[],logs:[],bundler:{name:t,fullName:`${t}${r}`,variant:r,version:n}},a=process.env.BUILD_PLUGINS_ENV||"production",u=k.includes(a)?a:"development";return{auth:e.auth,pluginNames:[],bundler:{...i.bundler,outDir:o},build:i,cwd:o,env:u,getLogger:D(i,e.logLevel),inject:()=>{throw new Error("Inject function called before it was initialized.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},start:Date.now(),version:s}})({options:r,bundlerVersion:n.version||n.VERSION,bundlerName:o.framework,version:s});i.pluginNames.push(bt);const a=[...xe(i),...Je(i),...Qe(i),...rt(r,i),...wt(n,i)];if(r.customPlugins){const e=r.customPlugins(r,i);a.push(...e)}r[E]&&!0!==r[E].disabled&&a.push(...X(r,i)),r[ee]&&!0!==r[ee].disabled&&a.push(...re(r,i)),r[ie]&&!0!==r[ie].disabled&&a.push(...Ne(r,i)),i.pluginNames.push(...a.map((e=>e.name)));const u=new Set(i.pluginNames.filter((e=>i.pluginNames.filter((t=>t===e)).length>1)));if(u.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(u).join(", "))}`);return a})))({bundler:v,version:vt}).rspack,kt=vt,St=yt;export{$t as datadogRspackPlugin,St as helpers,kt as version};
|
|
12
|
+
`;o.info(u),await J(a,e.sourcemaps,s,o)},Y=`https://sourcemap-intake.${process.env.DATADOG_SITE||"datadoghq.com"}/api/v2/srcmap`,Q=e=>{const n=t.bold.red,s=e[E]||{},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||Y,...s.sourcemaps};o.config=e}return o},X=(e,t)=>{const n=t.getLogger(M),s=((e,t)=>{const n=[],s=Q(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${M}.`);const o={...e[E],sourcemaps:void 0};return s.config&&(o.sourcemaps=s.config),o})(e,n);return[{name:M,enforce:"post",async writeBundle(){s.disabled||s.sourcemaps&&await V(s,t,n)}}]};var Z=(e=>(e[e.BEFORE=0]="BEFORE",e[e.MIDDLE=1]="MIDDLE",e[e.AFTER=2]="AFTER",e))(Z||{});const ee="rum",te="datadog-rum-plugin",ne=e=>`DD_RUM.init({${JSON.stringify(e.sdk).replace(/(^{|}$)/g,"")}});\n`,se=(e,t)=>{const n=e.sdk;if(n.clientToken)return ne(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 z({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 ne({...e,sdk:{clientToken:s,...n}})}},oe=e=>{const n=t.bold.red,s=e[ee]||{},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},re=(e,t)=>{const n=((e,t)=>{const n=[],s=oe(e);if(n.push(...s.errors),n.length)throw t.error(`\n - ${n.join("\n - ")}`),new Error(`Invalid configuration for ${te}.`);const o={...e[ee],sdk:void 0};return s.config&&(o.sdk=s.config),o})(e,t.getLogger(te));return n.sdk&&(t.inject({type:"file",position:Z.MIDDLE,value:s.join(__dirname,"./rum-browser-sdk.js")}),t.inject({type:"code",position:Z.MIDDLE,value:se(n,t)})),[]},ie="telemetry",ae="datadog-telemetry-plugin",ue=[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}],pe=(e,t)=>({type:"gauge",tags:[...e.tags,...t.tags],metric:`${t.prefix?`${t.prefix}.`:""}${e.metric}`,points:[[t.timestamp,e.value]]}),ce=(e="")=>e.endsWith("/")?e:`${e}/`,le=(e,t)=>{let n=e;return e.split(ce(t)),n.split("!").pop().replace(/(.*)?\/node_modules\//,"/node_modules/").replace(/^((\.)*\/)+/,"")},de=(e,t)=>e.split("!").pop().replace(ce(t),"./"),fe=(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)),de(s||"no-name",n)},me=e=>e.replace(/^.*\/node_modules\/(@[a-z0-9][\w-.]+\/[a-z0-9][\w-.]*|[^/]+).*$/,"$1"),he=e=>e.map((e=>({type:e?.constructor?.name??typeof e,name:e?.name,value:"string"==typeof e?e:void 0}))),ge=(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 r=0;s+=o.values.length;for(const t of o.values){const n=t.end-t.start;r+=n,e+=n}t.add({metric:"plugins.hooks.duration",type:"duration",value:r,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||[],r=e.build.warnings.length,i=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:i,tags:[]}).add({metric:"modules.count",type:"count",value:n.length,tags:[]}).add({metric:"warnings.count",type:"count",value:r,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(pe(s,t))}else n.add(pe(e,t))},we=async(e,t,n,o)=>{if("string"!=typeof t&&"object"!=typeof t&&!t)return;const{report:r,metrics:i}=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=s.resolve(o,u);try{const e={},t={};p.timings&&r?.timings&&(t.timings={content:{tapables:r.timings.tapables?Array.from(r.timings.tapables.values()):null,loaders:r.timings.loaders?Array.from(r.timings.loaders.values()):null,modules:r.timings.modules?Array.from(r.timings.modules.values()):null}}),p.metrics&&(t.metrics={content:Array.from(i)});const o=Object.entries(t).map((async([t,o])=>{const r=Date.now();n.debug(`Start writing ${t}.json.`);try{await(async(e,t)=>{const n=JSON.stringify(t,null,4);return x(e,n)})(s.join(c,`${t}.json`),o.content),n.debug(`Wrote ${t}.json in ${j(Date.now()-r)}`)}catch(s){n.error(`Failed to write ${t}.json in ${j(Date.now()-r)}`),e[t]=s}}));await Promise.all(o),n.debug(`Wrote files in ${j(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}`)}},ye=t.bold.red,be=t.bold.cyan,ve=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},$e=(e,t)=>{if(!t||!t.size)return[];const n=Array.from(t.values());n.sort(ve("duration"));const s={name:`${e} duration`,values:n.map((e=>({name:e.name,value:j(e.duration)}))),top:!0};n.sort(ve("increment"));const o={name:`${e} hits`,values:n.map((e=>({name:e.name,value:e.increment.toString()}))),top:!0};return[s,o]},ke=(e,t,n)=>{const s=[];var o;n&&(s.push(...$e("Loader",n.timings.loaders)),s.push(...$e("Tapable",n.timings.tapables)),s.push(...$e("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},r=new Set,i=(e=>{const t={bundler:e.bundler,errors:e.errors,warnings:e.warnings,logs:e.logs,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 i.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;r.add({name:t.name,size:t.size,aggregatedSize:o,dependents:s,dependencies:n})}if(!r.size)return[t,n,s];const c=Array.from(r);return c.sort(ve((e=>e.dependents.size))),t.values=c.map((e=>({name:e.name,value:e.dependents.size.toString()}))),c.sort(ve((e=>e.dependencies.size))),n.values=c.map((e=>({name:e.name,value:e.dependencies.size.toString()}))),c.sort(ve("size")),s.values=c.map((e=>({name:e.name,value:m(e.size)}))),c.sort(ve("aggregatedSize")),o.values=c.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(ve((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry aggregated size",values:(o.build.entries||[]).sort(ve((e=>e.size))).map((e=>({name:e.name,value:m(e.size)}))),top:!0},{name:"Entry number of modules",values:(o.build.entries||[]).sort(ve((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,r=e.build.errors.length,i=e.build.entries?e.build.entries.length:0;return e.build.start&&t.values.push({name:"Overhead duration",value:j(e.build.start-e.start)}),e.build.duration&&t.values.push({name:"Build duration",value:j(e.build.duration)}),e.build.writeDuration&&t.values.push({name:"Write duration",value:j(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:i.toString()},{name:"Number of warnings",value:o.toString()},{name:"Number of errors",value:r.toString()}),[t]})(e));const r=(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=N(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))))),r=Math.max(n+4,s+o+4);for(const n of e){if(0===n.values.length)continue;const e=r-(n.name.length+4);t+=`\n== ${n.name} ${"=".repeat(e)}=\n`;for(const e of n.values){const n=o-e.value.length;t+=` [${ye(e.value)}] ${" ".repeat(n)}${be(e.name)}\n`}}return t})(s);t.info(r)},Se=["onStart","onLoad","onResolve","onEnd"],De=new Map,Ee=new Map,Me=(e,t,n)=>{const s=Object.assign({},e);for(const o of Se)s[o]=async(s,r)=>{const i=De.get(t)||{name:t,increment:0,duration:0,events:{}};i.events[o]=i.events[o]||{name:o,values:[]};return(0,e[o])(s,(async(...e)=>{const s=de(e[0].path,n),a=Ee.get(s)||{name:s,increment:0,duration:0,events:{}};a.events[o]=a.events[o]||{name:o,values:[]};const u=h.now();try{return await r(...e)}finally{const n=h.now(),r=n-u,p={start:u,end:n,duration:r,context:he(e)};i.events[o].values.push(p),i.duration+=r,i.increment+=1,De.set(t,i),a.events[o].values.push(p),a.duration+=r,a.increment+=1,Ee.set(s,a)}}))};return s},Pe=(e,t,n)=>({setup:s=>{t.build.start=Date.now(),s.initialOptions.metafile=!0,((e,t)=>{const n=e.initialOptions.plugins;if(n){const e=n.map((e=>({...e})));for(const s of n){if(s.name.includes(ae))continue;const n=s.setup;s.setup=async o=>{const r=Me(o,s.name,t);await n({...r,initialOptions:{...r.initialOptions,plugins:e}})}}}})(s,t.cwd),s.onEnd((async t=>{if(!t.metafile)return void n.warn("Missing metafile, can't proceed with modules data.");const{plugins:s,modules:o}={plugins:De,modules:Ee};e.report={timings:{tapables:s,modules:o}}}))}});class je{constructor(e){this.started={},this.finished=[],this.cwd=e}buildModule(e,t){const n=fe(e,t,this.cwd),s=(e=>(e.loaders||[]).map((e=>e.loader||e)).map(me))(e);s.length||s.push("no-loader"),this.started[n]={module:le(n),timings:{start:h.now(),duration:0,end:0},loaders:s}}succeedModule(e,t){const n=fe(e,t,this.cwd),s=this.started[n];s&&(s.timings.end=h.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:{}},r=n.loaders.join(",");o.events[r]=o.events[r]||{name:r,values:[]},o.events[r].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 Oe{constructor(e){this.monitoredTaps={},this.tapables=[],this.hooks={},this.timings=new Map,this.ignoredHooks=["normalModuleLoader"],this.cwd=e}saveResult(e,t,n,s,o,r){const i=this.timings.get(t)||{name:t,duration:0,increment:0,events:{}};i.events[n]||(i.events[n]={name:n,values:[]}),i.events[n].values.push({start:o,end:r,duration:r-o,context:s,type:e}),i.duration+=r-o,i.increment+=1,this.timings.set(t,i)}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 r=h.now(),i=t.apply(this,o),a=()=>{this.saveResult(e,n,s,he(o),r,h.now())};return i.then(a,a),i}}getAsyncTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.now(),i=o.pop();return t.apply(this,[...o,(...t)=>(this.saveResult(e,n,s,he(o),r,h.now()),i(...t))])}}getDefaultTapPatch(e,t,n,s){return(...o)=>{this.checkNewHooks();const r=h.now(),i=t.apply(this,o);return this.saveResult(e,n,s,he(o),r,h.now()),i}}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,r)=>{const i="string"==typeof(a=o)?a:a.name;var a;const u=`${t}-${i}`;if(this.monitoredTaps[u])return n.call(s,o,r);this.monitoredTaps[u]=!0;const p=this.getTapPatch(e,r,i,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(ae)||(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 Te=(e,t)=>async n=>{t.build.start=Date.now();const s={name:ae},o=new Oe(t.cwd),r=new je(t.cwd);o.throughHooks(n),n.hooks.thisCompilation.tap(s,(e=>{o.throughHooks(e),e.hooks.buildModule.tap(s,(t=>{r.buildModule(t,e)})),e.hooks.succeedModule.tap(s,(t=>{r.succeedModule(t,e)}))})),n.hooks.afterEmit.tapPromise(s,(async t=>{const{timings:n}=o.getResults(),{loaders:s,modules:i}=r.getResults();e.report={timings:{tapables:n,loaders:s,modules:i}}}))},ze={filters:ue},Ne=(e,t)=>{const n=t.getLogger(ae);let s=0;const o={start:Date.now()},r=(e=>{const t=e[ie]||{},n=t.endPoint||"https://app.datadoghq.com";return{disabled:!1,enableTracing:!1,filters:ue,output:!1,prefix:"",tags:[],...t,endPoint:n.startsWith("http")?n:`https://${n}`}})(e),i=[],a={name:ae,enforce:"pre",esbuild:Pe(o,t,n),webpack:Te(o,t),rspack:Te(o,t)},u={name:"datadog-universal-telemetry-plugin",enforce:"post",buildStart(){t.build.start=t.build.start||Date.now()},buildEnd(){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,i=(e=>({timestamp:Math.floor((e.timestamp||Date.now())/1e3),tags:e.tags,prefix:e.prefix,filters:e.filters}))(r);ge(t,i,e,o.report),await we({report:o.report,metrics:e},r.output,n,t.bundler.outDir),ke(t,n,o.report),await((e,t,n)=>{const s=Date.now();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 o=new Map;for(const t of e)o.has(t.metric)||o.set(t.metric,0),o.set(t.metric,o.get(t.metric)+1);const r=Array.from(o.entries()).map((([e,t])=>`${e} - ${t}`));return n.debug(`\nSending ${e.size} metrics.\nMetrics:\n - ${r.join("\n - ")}`),z({method:"POST",url:`${t.endPoint}/api/v1/series?api_key=${t.apiKey}`,getData:()=>({data:JSON.stringify({series:Array.from(e)})})}).then((()=>{n.debug(`Sent metrics in ${j(Date.now()-s)}.`)})).catch((e=>{n.error(`Error sending metrics ${e}`)}))})(e,{apiKey:t.auth?.apiKey,endPoint:r.endPoint},n)}};return r.enableTracing&&i.push(a),i.push(u),i},Re="datadog-analytics-plugin",xe=e=>{const t=e.getLogger(Re);return e.sendLog=async(n,s={})=>{if("production"===e.env)try{const t={name:e.bundler.name,version:e.bundler.version};await z({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/${t.name}-plugin`,env:e.env,message:n,service:"build-plugins",bundler:t,plugins:e.pluginNames,version:e.version,team:"language-foundations",...s};return{data:JSON.stringify(o),headers:{"Content-Type":"application/json"}}}})}catch(e){t.debug(`Could not submit data to Datadog: ${e}`)}},[{name:Re,async buildStart(){await e.sendLog("Build started")}}]},Ie=/\.(?!.*(?:\.|\/|\\))(\w{1,})/g,Ae=/(\?|%3F|\|)+/gi,Fe=e=>{return"unknown"===e?e:e.includes("webpack/runtime")?"runtime":(t=_e(e),Ie.lastIndex=0,Ie.exec(t)?.[1]||"unknown");var t},Ce=["unknown","commonjsHelpers.js","vite/preload-helper.js"],Le=(e,t,n)=>{const s=new Set;for(const n of e){const e=_e(n);R(n)||e===t||Ce.includes(e)||s.add(e)}return s},_e=e=>e.split("!").pop().split(Ae).shift().replace(/^[^\w\s.,!@#$%^&*()=+~`\-/]+/,""),qe=(e,t)=>R(t)?$:t.startsWith(e)?t:s.resolve(e,t),Ke=(e,t)=>R(t)?$:"unknown"===t?t:t.includes("webpack/runtime")?t.replace("webpack/runtime/","").replace(/ +/g,"-"):t.split("!").pop().replace(e.bundler.outDir,"").replace(e.cwd,"").split("node_modules").pop().split(Ae).shift().replace(/^\/+/,""),Be=(e,t)=>Object.fromEntries(Object.entries(e).map((([e,n])=>[qe(t,e),n]))),He=(e,t)=>({setup(n){const s=new Map,o=[];n.onStart((async()=>{o.push(...await O(n,e,t));for(const t of o){const n=Ke(e,t.resolved);t.name?s.set(n,t.name):s.set(n,n)}})),n.onEnd((n=>{const o=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(!n.metafile){const n="Missing metafile from build report.";return e.build.warnings.push(n),void t.warn(n)}const r=[],i=[],a=[],u=[],p=[],c={},l={},d=Be(n.metafile.inputs,o),f=Be(n.metafile.outputs,o),m=e=>{if(!R(e))return e;const t=d[qe(o,e)];if(!t)return e;const n=t.imports.find((e=>!R(e.path)));return n?n.path:e};for(const[t,s]of Object.entries(n.metafile.inputs)){if(R(t))continue;const n=qe(o,t),i={name:Ke(e,t),filepath:n,dependents:new Set,dependencies:new Set,size:s.bytes,type:Fe(t)};c[n]=i,r.push(i)}for(const[r,p]of Object.entries(n.metafile.outputs)){const n=qe(o,r),d=Ke(e,n),f=[];for(const e of Object.keys(p.inputs)){if(R(e))continue;const n=c[qe(o,e)];n?f.push(n):t.debug(`Input ${e} not found for output ${d}`)}if(p.entryPoint&&!f.length){const e=c[qe(o,p.entryPoint)];if(!e){t.debug(`Input ${p.entryPoint} not found for output ${d}`);continue}f.push(e)}const h={name:d,filepath:n,inputs:f,size:p.bytes,type:Fe(n)};if(l[n]=h,"map"===h.type&&u.push(h),i.push(h),!p.entryPoint)continue;const g=c[qe(o,m(p.entryPoint))];if(g){if(!s.get(g.name))continue;const e={...h,name:s.get(g.name)||g.name,outputs:[h],size:h.size};a.push(e)}}for(const e of u){const n=l[e.filepath.replace(/\.map$/,"")];n?e.inputs.push(n):t.debug(`Could not find output for sourcemap ${e.name}`)}const h={inputs:{report:c,meta:d},outputs:{report:l,meta:f}},g=/(<runtime>|https:|file:|data:|#)/g,w=e=>!R(e)&&!e.match(g),y=(e,n,s={})=>{if(!w(e))return s;const r=n.report[e];if(!r)return t.debug(`Could not find report's ${e}`),s;if(s[r.filepath])return s;s[r.filepath]=r;const i=n.meta[e];if(!i)return t.debug(`Could not find metafile's ${e}`),s;if(!i.imports||!i.imports.length)return s;for(const e of i.imports){const t=qe(o,e.path);y(t,n,s)}return s};for(const e of a){const t={},n={};for(const n of e.inputs)y(n.filepath,h.inputs,t);for(const t of e.outputs)y(t.filepath,h.outputs,n);e.inputs=Object.values(t),e.outputs=Object.values(n),e.size=e.outputs.reduce(((e,t)=>e+t.size),0),p.push(e)}for(const e of r){const n=h.inputs.meta[e.filepath];if(n)for(const s of n.imports){if(!w(s.path))continue;const n=qe(o,s.path),r=h.inputs.report[n];r?(e.dependencies.add(r),r.dependents.add(e)):t.debug(`Could not find input file of ${s.path}`)}else t.debug(`Could not find metafile's ${e.name}`)}e.build.outputs=i,e.build.inputs=r,e.build.entries=p}))}}),We=(e,t)=>{const n={};return{onLog(t,n){"warn"===t&&e.build.warnings.push(n.message||n.toString())},renderError(t){t&&e.build.errors.push(t.message)},moduleParsed(e){const t=_e(e.id),s=n[t]||{dependencies:new Set,dependents:new Set},o=Le(new Set([...e.dynamicallyImportedIds,...e.importedIds]),t),r=Le(new Set([...e.dynamicImporters,...e.importers]),t);for(const e of r)s.dependents.add(e);for(const e of o)s.dependencies.add(e);n[t]=s},writeBundle(s,o){const r=[],i=[],a=[],u=[],p=[],c={},l={};for(const[e,{dependencies:t,dependents:s}]of Object.entries(n)){for(const s of t){const t=_e(s);n[t]||(n[t]={dependencies:new Set,dependents:new Set}),n[t].dependents.has(e)||n[t].dependents.add(e)}for(const t of s){const s=_e(t);n[s]||(n[s]={dependencies:new Set,dependents:new Set}),n[s].dependencies.has(e)||n[s].dependencies.add(e)}}for(const[t,n]of Object.entries(o)){const s={name:t,filepath:qe(e.bundler.outDir,t),inputs:[],size:"code"in n?Buffer.byteLength(n.code,"utf8"):Buffer.byteLength(n.source,"utf8"),type:Fe(t)};if("map"===s.type&&u.push(s),"modules"in n)for(const[t,o]of Object.entries(n.modules)){if(_e(t)!==t)continue;const n={name:Ke(e,t),dependencies:new Set,dependents:new Set,filepath:t,size:o.originalLength,type:Fe(t)};s.inputs.push(n),c[n.filepath]=n,r.push(n)}"isEntry"in n&&n.isEntry&&a.push({...s,name:n.name,size:0,outputs:[s]}),l[s.filepath]=s,i.push(s)}for(const s of r){const o=n[s.filepath];if(o){for(const n of o.dependencies){const o=c[n];o?s.dependencies.add(o):t.debug(`Could not find input for dependency ${Ke(e,n)} of ${s.name}`)}for(const n of o.dependents){const o=c[n];o?s.dependents.add(o):t.debug(`Could not find input for dependent ${Ke(e,n)} of ${s.name}`)}}else t.debug(`Could not find the import report for ${s.name}.`)}if(u.length)for(const e of u){const n=e.filepath.replace(/\.map$/,""),s=l[n];s?e.inputs.push(s):t.debug(`Could not find output for sourcemap ${e.name}`)}const d=(n,s={})=>{if(s[n])return s;const r=Ke(e,n),i=l[n];if(!i)return t.debug(`Could not find output for ${r}`),s;s[n]=i;const a=o[r];if(!a)return t.debug(`Could not find asset for ${r}`),s;const u=[];"imports"in a&&u.push(...a.imports),"dynamicImports"in a&&u.push(...a.dynamicImports);for(const t of u)d(qe(e.bundler.outDir,t),s);return s};for(const e of a){const t=d(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),p.push(e)}e.build.inputs=r,e.build.outputs=i,e.build.entries=p}}},Ue=(e,t,n)=>s=>{const o=[],r=[],i=[],a=new Map,u=new Map,p=new Map,c=new Map,l=[],d=new Map,f=e=>!(!e||e.startsWith("webpack/runtime")||e.includes("/webpack4/buildin/")||e.startsWith("multi ")||R(e)),m=e=>{const t={identifier:e.identifier()};"resource"in e&&"string"==typeof e.resource&&(t.resource=e.resource),"request"in e&&"string"==typeof e.request&&(t.request=e.request),"rawRequest"in e&&"string"==typeof e.rawRequest&&(t.rawRequest=e.rawRequest),"userRequest"in e&&"string"==typeof e.userRequest&&(t.userRequest=e.userRequest);const s=new Set;for(const[o,r]of Object.entries(t))r&&(c.has(r)?(n.debug(`Module ${e.identifier()} is already indexed by ${o}.`),c.get(r)!==e&&n.debug(`Module ${e.identifier()} is indexed with a different value.`)):s.add(r));return s},h=(e,t=[])=>{if("dependencies"in e)for(const n of e.dependencies)t.push(n),h(n,t);if("blocks"in e)for(const n of e.blocks)h(n,t);return t},g=(e,t)=>{if("request"in t&&t.request){if(c.has(t.request))return c.get(t.request);if(e.context&&c.has(qe(e.context,t.request)))return c.get(qe(e.context,t.request))}};s.hooks.thisCompilation.tap(t,(s=>{s.hooks.finishModules.tap(t,(t=>{for(const e of t){const t=m(e);for(const n of t)c.set(n,e)}for(const n of t){const t=n.identifier(),s=new Set(h(n).map((e=>{const s=g(n,e);if(!s||!s.identifier())return!1;const o=s.identifier();return!!f(o)&&(o!==t&&o)})).filter(Boolean));if(!f(t))continue;for(const e of s){const n=d.get(e)||{dependencies:new Set,dependents:new Set};n.dependents.add(t),d.set(e,n)}const r=d.get(t)||{dependents:new Set,dependencies:new Set};for(const e of s)r.dependencies.add(e);d.set(t,r);const i={size:n.size()||0,name:Ke(e,t),dependencies:new Set,dependents:new Set,filepath:t,type:Fe(t)};o.push(i),a.set(t,i)}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}`)}}))})),s.hooks.afterEmit.tap(t,(t=>{const s=t.chunks,c=t.getAssets(),d=t=>[...t.files||[],...t.auxiliaryFiles||[]].map((t=>qe(e.bundler.outDir,t))),m=t.chunkGraph;for(const e of s){const t=d(e),n=(m?m?.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"===Fe(e))continue;const t=p.get(e)||[];p.set(e,[...t,...n])}}for(const t of c){const s={size:t.source.size()||0,name:t.name,inputs:[],filepath:qe(e.bundler.outDir,t.name),type:Fe(t.name)};if(u.set(s.filepath,s),r.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}`)}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}`)}for(const[s,o]of t.entrypoints){const t=[],r=[];let a=0;const p=o.chunks.flatMap(d),c=o.chunks.filter((e=>m?m.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"===Fe(e)));for(const e of p){const s=u.get(e);e&&s?"map"===s.type||t.includes(s)||(t.push(s),r.push(...s.inputs),a+=s.size):n.debug(`Could not find output of ${JSON.stringify(e)}`)}const l={name:s,filepath:c?qe(e.bundler.outDir,c):"unknown",size:a,inputs:Array.from(new Set(r)),outputs:t,type:c?Fe(c):"unknown"};i.push(l)}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=r,e.build.entries=i}))},Ge="datadog-build-report-plugin",Je=e=>{const t=e.getLogger(Ge);return[{name:Ge,enforce:"post",esbuild:He(e,t),rspack:Ue(e,Ge,t),webpack:Ue(e,Ge,t),vite:We(e,t),rollup:We(e,t)}]},Ve=(e,t)=>{const n=((e,t)=>{const n=e.map((e=>(s.isAbsolute(e)?e:s.resolve(t,e)).split(s.sep))),o=Math.min(...n.map((e=>e.length))),r=[];for(let e=0;e<o;e++){const t=n[0][e];if(!n.every((n=>n[e]===t)))break;r.push(t)}return r.length>0?r.join(s.sep):s.sep})(e,t.cwd);n!==s.sep&&(t.cwd=n)},Ye=e=>t=>{e.bundler.rawConfig=t.options,t.options.output?.path&&(e.bundler.outDir=t.options.output.path),t.options.context&&(e.cwd=t.options.context)},Qe=e=>{const t=new Set,n=n=>{n&&(n.dir?(e.bundler.outDir=n.dir,t.add(n.dir)):n.file&&(e.bundler.outDir=s.dirname(n.file),t.add(n.dir)),"vite"!==e.bundler.name&&Ve(Array.from(t),e))},o=()=>({options(o){if(e.bundler.rawConfig=o,o.input)if(Array.isArray(o.input))for(const e of o.input)t.add(s.dirname(e));else if("object"==typeof o.input)for(const e of Object.values(o.input))t.add(s.dirname(e));else{if("string"!=typeof o.input)throw new Error("Invalid input type");t.add(s.dirname(o.input))}"output"in o&&n(o.output)},outputOptions(e){n(e)}});return[{name:"datadog-bundler-report-plugin",enforce:"pre",esbuild:{setup(t){e.bundler.rawConfig=t.initialOptions,t.initialOptions.outdir&&(e.bundler.outDir=t.initialOptions.outdir),t.initialOptions.outfile&&(e.bundler.outDir=s.dirname(t.initialOptions.outfile)),t.initialOptions.absWorkingDir&&(e.cwd=t.initialOptions.absWorkingDir),t.initialOptions.metafile=!0}},webpack:Ye(e),rspack:Ye(e),vite:{...o(),config(n){n.root?e.cwd=n.root:Ve(Array.from(t),e)}},rollup:o()}]};class Xe{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=a.readFileSync(e,"utf8"),s=JSON.parse(n);if(!s.sources)return void t("Missing 'sources' field in sourcemap.");const o=s.sources;if(0===o.length)return void t("Empty 'sources' field in sourcemap.");const r=this.matchSources(o);if(0!==r.length)return r;t(`${o.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 Ze=async e=>{const t=await e.getRemotes(!0);if(0===t.length)throw new Error("No git remotes available");const n=await et(e);for(const e of t)if(e.name===n)return tt(e.refs.push);return tt(t[0].refs.push)},et=async e=>{try{return(await e.getConfig("clone.defaultRemoteName"))?.value??"origin"}catch(e){return"origin"}},tt=e=>{try{const t=new w(e);return t.username="",t.password="",t.toString()}catch{return e}},nt=async e=>e.revparse("HEAD"),st=async e=>(await e.raw("ls-files")).split(/\r\n|\r|\n/),ot="datadog-git-plugin",rt=(e,t)=>{const n=t.getLogger(ot);return[{name:ot,enforce:"pre",async buildStart(){if(e.errorTracking?.sourcemaps&&!0!==e.errorTracking?.sourcemaps.disableGit&&!0!==e.disableGit)try{const e=await(async e=>{let t,n,s;return[t,n,s]=await Promise.all([Ze(e),nt(e),st(e)]),{hash:n,remote:t,trackedFilesMatcher:new Xe(s)}})(await(async e=>{const t={baseDir:e||process.cwd(),binary:"git",maxConcurrentProcesses:3};try{const e=g(t),n=await e.revparse("--show-toplevel");t.baseDir=n}catch{}return g(t)})(t.cwd));t.git=e}catch(e){n.error(`Could not get git information: ${e.message}`)}}}]},it="datadog-injection-plugin",at=/^https?:\/\//,ut=async(e,t,n=process.cwd())=>{let s;const o=await(async e=>"function"==typeof e.value?e.value():e.value)(e);try{if("file"===e.type)s=o.match(at)?await(async(e,t=5e3)=>{let n;return Promise.race([z({retries:2,minTimeout:100,url:e}).finally((()=>{t&&clearTimeout(n)})),new Promise(((e,s)=>{n=setTimeout((()=>{s(new Error("Timeout"))}),t)}))])})(o):await(async(e,t=process.cwd())=>{const n=qe(t,e);return i(n,{encoding:"utf-8"})})(o,n);else{if("code"!==e.type)throw new Error(`Invalid item type "${e.type}", only accepts "code" or "file".`);s=o}}catch(n){const r=`${e.type} - ${N(o)}`;e.fallback?(t.info(`Fallback for "${r}": ${n.toString()}`),s=await ut(e.fallback,t)):(t.warn(`Failed "${r}": ${n.toString()}`),s="")}return s},pt=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`},ct=async(e,t,n,s=process.cwd())=>{const o=await(async(e,t,n=process.cwd())=>{const s=new Map;for(const[o,r]of e.entries()){const e=await ut(r,t,n);e&&s.set(o,{value:e,position:r.position||Z.BEFORE})}return s})(t,e,s);for(const[e,t]of o.entries())n[t.position].set(e,t.value)},lt=a.promises,dt=(e,t,n)=>({setup(o){const{onStart:r,onResolve:i,onLoad:u,onEnd:p,esbuild:c,initialOptions:l}=o,d=[],f=`${F()}.${Z.MIDDLE}.${$}.js`,m=a.realpathSync(y.tmpdir()),h=s.resolve(m,f),g=new RegExp(`${f}$`),w=l.inject;l.inject=w?[...w]:[],l.inject.push(h),r((async()=>{d.push(...await O(o,t,e)),o.initialOptions.inject=w;try{await x(h,"")}catch(t){e.error(`Could not create the files: ${t.message}`)}})),i({filter:g},(async e=>({path:e.path,namespace:it}))),u({filter:g,namespace:it},(async()=>({contents:pt(n[Z.MIDDLE])||" ",resolveDir:t.cwd,loader:"js"}))),p((async s=>{if(!s.metafile)return void e.warn("Missing metafile from build result.");const o=pt(n[Z.BEFORE]),r=pt(n[Z.AFTER]);if(!o&&!r)return;const i=Object.entries(s.metafile.outputs).map((([e,n])=>{const s=n.entryPoint;if(!s)return;return d.find((e=>e.resolved.endsWith(s)))?qe(t.cwd,e):void 0})).filter(Boolean).map((async e=>{const t=await lt.readFile(e,"utf-8"),n=await c.transform(t,{loader:"default",banner:o,footer:r});await lt.writeFile(e,n.code)}));await Promise.all(i)}))}}),ft=$,mt="?inject-proxy",ht=e=>({banner:t=>t.isEntry?pt(e[Z.BEFORE]):"",async resolveId(t,n,s){if(R(t))return{id:t,moduleSideEffects:!0};if(s.isEntry&&pt(e[Z.MIDDLE])){const e=await this.resolve(t,n,s);if(!e||e.external)return e;return(await this.load(e)).moduleSideEffects=!0,`${e.id}${mt}`}return null},load(t){if(R(t))return pt(e[Z.MIDDLE]);if(t.endsWith(mt)){const e=t.slice(0,-13),n=this.getModuleInfo(e);let s=`import ${JSON.stringify(ft)};\nexport * from ${JSON.stringify(e)};`;return n?.hasDefaultExport&&(s+=`export { default } from ${JSON.stringify(e)};`),s}return null},footer:t=>t.isEntry?pt(e[Z.AFTER]):""}),gt=(e,t,n,o,r)=>i=>{const u=new WeakMap,p=(e=>{if(!e?.sources?.ConcatSource)return b(require.resolve("webpack"))("webpack-sources").ConcatSource;return e.sources.ConcatSource})(e),c=s.resolve(n.bundler.outDir,`${F()}.${Z.MIDDLE}.${$}.js`);I(c,"");const l=()=>{(async e=>{a.rmSync(e,{force:!0,maxRetries:3,recursive:!0})})(c)};i.hooks.shutdown?i.hooks.shutdown.tap(it,l):(i.hooks.done.tap(it,l),i.hooks.failed.tap(it,l));i.hooks.beforeRun.tapPromise(it,(async()=>{await ct(t,o,r,n.cwd)})),i.hooks.compilation.tap(it,(t=>{const n=()=>{const e=pt(r[Z.BEFORE]),n=pt(r[Z.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:it,stage:s},n)}else t.hooks.optimizeChunkAssets.tap({name:it},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}})(i.options.entry);i.options.entry=d},wt=(e,t)=>{const n=t.getLogger(it),s=new Map,o={[Z.BEFORE]:new Map,[Z.MIDDLE]:new Map,[Z.AFTER]:new Map};t.inject=e=>{s.set(F(),e)};const r={name:it,enforce:"post",esbuild:dt(n,t,o),webpack:gt(e,n,t,s,o),rspack:gt(e,n,t,s,o),rollup:ht(o),vite:{...ht(o),enforce:"pre"}};var i;return i=t.bundler.fullName,["rspack","webpack4","webpack5","webpack"].includes(i)?(r.loadInclude=e=>!!R(e)||null,r.load=e=>R(e)?{code:pt(o[Z.MIDDLE])}:null):r.buildStart=async()=>{await ct(n,s,o,t.cwd)},[r]},yt={[ie]:ze},bt="datadog-build-plugins";var vt="2.5.1-dev-5";const $t=(({bundler:n,version:s})=>e(((e,o)=>{const r=((e={})=>({auth:{},disableGit:!1,logLevel:"warn",...e}))(e);"esbuild"===o.framework&&(o.esbuildHostName=bt);const i=(({options:e,bundlerName:t,bundlerVersion:n,version:s})=>{const o=process.cwd(),r="webpack"===t?n.split(".")[0]:"",i={errors:[],warnings:[],logs:[],bundler:{name:t,fullName:`${t}${r}`,variant:r,version:n}},a=process.env.BUILD_PLUGINS_ENV||"production",u=k.includes(a)?a:"development";return{auth:e.auth,pluginNames:[],bundler:{...i.bundler,outDir:o},build:i,cwd:o,env:u,getLogger:D(i,e.logLevel),inject:()=>{throw new Error("Inject function called before it was initialized.")},sendLog:()=>{throw new Error("SendLog function called before it was initialized.")},start:Date.now(),version:s}})({options:r,bundlerVersion:n.version||n.VERSION,bundlerName:o.framework,version:s});i.pluginNames.push(bt);const a=[...xe(i),...Je(i),...Qe(i),...rt(r,i),...wt(n,i)];if(r.customPlugins){const e=r.customPlugins(r,i);a.push(...e)}r[E]&&!0!==r[E].disabled&&a.push(...X(r,i)),r[ee]&&!0!==r[ee].disabled&&a.push(...re(r,i)),r[ie]&&!0!==r[ie].disabled&&a.push(...Ne(r,i)),i.pluginNames.push(...a.map((e=>e.name)));const u=new Set(i.pluginNames.filter((e=>i.pluginNames.filter((t=>t===e)).length>1)));if(u.size>0)throw new Error(`Duplicate plugin names: ${t.bold.red(Array.from(u).join(", "))}`);return a})))({bundler:v,version:vt}).rspack,kt=vt,St=yt;export{$t as datadogRspackPlugin,St as helpers,kt as version};
|
|
13
13
|
//# sourceMappingURL=index.mjs.map
|