@datadog/vite-plugin 3.0.0 → 3.0.1-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../factory/src/validate.ts","../../../../core/src/constants.ts","../../../../core/src/helpers/request.ts","../../../../core/src/helpers/log.ts","../../../../core/src/helpers/plugins.ts","../../../../core/src/helpers/strings.ts","../../../../factory/src/helpers/logger.ts","../../../../factory/src/helpers/wrapPlugins.ts","../../../../plugins/error-tracking/src/constants.ts","../../../../plugins/error-tracking/src/sourcemaps/files.ts","../../../../core/src/helpers/fs.ts","../../../../plugins/error-tracking/src/sourcemaps/payload.ts","../../../../plugins/error-tracking/src/sourcemaps/sender.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts","../../../../plugins/error-tracking/src/validate.ts","../../../../plugins/error-tracking/src/index.ts","../../../../plugins/metrics/src/common/filters.ts","../../../../plugins/metrics/src/constants.ts","../../../../plugins/metrics/src/common/helpers.ts","../../../../plugins/metrics/src/common/output/text.ts","../../../../plugins/metrics/src/esbuild-plugin/plugins.ts","../../../../plugins/metrics/src/esbuild-plugin/index.ts","../../../../plugins/metrics/src/webpack-plugin/loaders.ts","../../../../plugins/metrics/src/webpack-plugin/tapables.ts","../../../../plugins/metrics/src/webpack-plugin/index.ts","../../../../plugins/metrics/src/index.ts","../../../../plugins/metrics/src/common/aggregator.ts","../../../../plugins/metrics/src/common/sender.ts","../../../../plugins/output/src/constants.ts","../../../../plugins/output/src/validate.ts","../../../../plugins/output/src/index.ts","../../../../core/src/types.ts","../../../../plugins/rum/src/constants.ts","../../../../plugins/rum/src/privacy/constants.ts","../../../../plugins/rum/src/privacy/index.ts","../../../../plugins/rum/src/sdk.ts","../../../../plugins/rum/src/validate.ts","../../../../plugins/rum/src/index.ts","../../../../plugins/rum/src/privacy/transform.ts","../../../../plugins/analytics/src/constants.ts","../../../../plugins/analytics/src/index.ts","../../../../plugins/async-queue/src/constants.ts","../../../../plugins/async-queue/src/index.ts","../../../../core/src/helpers/bundlers.ts","../../../../core/src/helpers/paths.ts","../../../../plugins/build-report/src/helpers.ts","../../../../plugins/build-report/src/esbuild.ts","../../../../plugins/build-report/src/rollup.ts","../../../../plugins/build-report/src/xpack.ts","../../../../plugins/build-report/src/index.ts","../../../../plugins/bundler-report/src/index.ts","../../../../plugins/custom-hooks/src/constants.ts","../../../../plugins/custom-hooks/src/index.ts","../../../../plugins/git/src/trackedFilesMatcher.ts","../../../../plugins/git/src/helpers.ts","../../../../plugins/git/src/index.ts","../../../../plugins/injection/src/constants.ts","../../../../plugins/injection/src/helpers.ts","../../../../plugins/injection/src/esbuild.ts","../../../../plugins/injection/src/rollup.ts","../../../../plugins/injection/src/xpack.ts","../../../../plugins/injection/src/index.ts","../../../../plugins/true-end/src/index.ts","../../../../factory/src/index.ts","../../src/index.ts","../../../../factory/src/helpers/context.ts"],"sourcesContent":["// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { AuthOptionsWithDefaults, Options, OptionsWithDefaults } from '@dd/core/types';\n\nconst getEnvValue = (key: string) => {\n return process.env[`DATADOG_${key}`] || process.env[`DD_${key}`];\n};\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n const auth: AuthOptionsWithDefaults = {\n // DATADOG_SITE env var takes precedence over configuration\n site: getEnvValue('SITE') || options.auth?.site || 'datadoghq.com',\n };\n\n // Prevent these from being accidentally logged.\n Object.defineProperty(auth, 'apiKey', {\n value: getEnvValue('API_KEY') || options.auth?.apiKey,\n enumerable: false,\n });\n\n Object.defineProperty(auth, 'appKey', {\n value: getEnvValue('APP_KEY') || options.auth?.appKey,\n enumerable: false,\n });\n\n return {\n enableGit: true,\n logLevel: 'warn',\n metadata: {},\n ...options,\n auth,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const INJECTED_FILE = '__datadog-helper-file';\nexport const INJECTED_FILE_RX = new RegExp(INJECTED_FILE);\n\nexport const ALL_ENVS = ['development', 'production', 'test'] as const;\nexport const ALL_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack', 'rolldown', 'farm'];\nexport const SUPPORTED_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack'] as const;\nexport const ENV_VAR_REQUESTED_BUNDLERS = 'PLAYWRIGHT_REQUESTED_BUNDLERS';\n\nexport const HOST_NAME = 'datadog-build-plugins';\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport retry from 'async-retry';\nimport type { RequestInit } from 'undici-types';\n\nimport type { RequestOpts } from '../types';\n\nexport const ERROR_CODES_NO_RETRY = [400, 403, 413];\nexport const NB_RETRIES = 5;\n// Do a retriable fetch.\nexport const doRequest = <T>(opts: RequestOpts): Promise<T> => {\n const { auth, url, method = 'GET', getData, type = 'text' } = opts;\n const retryOpts: retry.Options = {\n retries: opts.retries === 0 ? 0 : opts.retries || NB_RETRIES,\n onRetry: opts.onRetry,\n maxTimeout: opts.maxTimeout,\n minTimeout: opts.minTimeout,\n };\n\n return retry(async (bail: (e: Error) => void, attempt: number) => {\n let response: Response;\n try {\n const requestInit: RequestInit = {\n method,\n // This is needed for sending body in NodeJS' Fetch.\n // https://github.com/nodejs/node/issues/46221\n duplex: 'half',\n };\n let requestHeaders: RequestInit['headers'] = {\n 'X-Datadog-Origin': 'build-plugins',\n };\n\n // Do auth if present.\n if (auth?.apiKey) {\n requestHeaders['DD-API-KEY'] = auth.apiKey;\n }\n\n if (auth?.appKey) {\n requestHeaders['DD-APPLICATION-KEY'] = auth.appKey;\n }\n\n if (typeof getData === 'function') {\n const { data, headers } = await getData();\n requestInit.body = data;\n requestHeaders = { ...requestHeaders, ...headers };\n }\n\n response = await fetch(url, { ...requestInit, headers: requestHeaders });\n } catch (error: any) {\n // We don't want to retry if there is a non-fetch related error.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n\n if (!response.ok) {\n // Not instantiating the error here, as it will make Jest throw in the tests.\n const errorMessage = `HTTP ${response.status} ${response.statusText}`;\n if (ERROR_CODES_NO_RETRY.includes(response.status)) {\n bail(new Error(errorMessage));\n // bail(error) throws so the return is never executed.\n return {} as T;\n } else {\n // Trigger the retry.\n throw new Error(errorMessage);\n }\n }\n\n try {\n let result;\n // Await it so we catch any parsing error and bail.\n if (type === 'json') {\n result = await response.json();\n } else {\n result = await response.text();\n }\n\n return result as T;\n } catch (error: any) {\n // We don't want to retry on parsing errors.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n }, retryOpts);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '../constants';\nimport type { GlobalData, DdLogOptions } from '../types';\n\nimport { doRequest } from './request';\n\nexport const INTAKE_PATH = 'v1/input/pub44d5f4eb86e1392037b7501f7adc540e';\nexport const INTAKE_HOST = 'browser-http-intake.logs.datadoghq.com';\n\nexport const getSendLog =\n (data: GlobalData) =>\n ({ message, context }: DdLogOptions): Promise<void> => {\n return doRequest({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url: `https://${INTAKE_HOST}/${INTAKE_PATH}`,\n method: 'POST',\n type: 'json',\n getData: async () => {\n const payload = {\n ddsource: data.packageName || HOST_NAME,\n message,\n service: 'build-plugins',\n team: 'language-foundations',\n env: data.env,\n version: data.version,\n bundler: {\n name: data.bundler.name,\n version: data.bundler.version,\n },\n metadata: data.metadata,\n ...context,\n };\n return {\n data: JSON.stringify(payload),\n headers: {\n 'Content-Type': 'application/json',\n },\n };\n },\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n Input,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\n\nexport const cleanPluginName = (name: string) => {\n // Will remove the \"@dd/\", \"@dd/datadog-\", \"@dd/internal-\", \"datadog-\" prefixes and the \"-plugin\" suffix.\n return name.replace(/^@dd\\/(datadog-|internal-)?|^datadog-|-plugin$/g, '');\n};\n\n// Is the file coming from the injection plugin?\nexport const isInjectionFile = (filename: string) => filename.includes(INJECTED_FILE);\n\n// Returns an object that is safe to serialize to JSON.\n// Mostly useful for debugging and testing.\nexport const serializeBuildReport = (report: BuildReport): SerializedBuildReport => {\n // Report is an object that self reference some of its values.\n // To make it JSON serializable, we need to remove the self references\n // and replace them with strings, we'll use \"filepath\" to still have them uniquely identifiable.\n const jsonReport: SerializedBuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n entries: [],\n inputs: [],\n outputs: [],\n };\n\n for (const entry of report.entries || []) {\n const newEntry: SerializedEntry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs.map((file: FileReport) => file.filepath);\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.entries.push(newEntry);\n }\n\n for (const input of report.inputs || []) {\n const newInput: SerializedInput = { ...input, dependencies: [], dependents: [] };\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n newInput.dependencies.push(dependency.filepath);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n newInput.dependents.push(dependent.filepath);\n }\n }\n jsonReport.inputs.push(newInput);\n }\n\n for (const output of report.outputs || []) {\n const newOutput: SerializedOutput = { ...output, inputs: [] };\n if (output.inputs) {\n newOutput.inputs = output.inputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.outputs.push(newOutput);\n }\n\n return jsonReport;\n};\n\n// Returns an object that is unserialized from serializeBuildReport().\n// Mostly useful for debugging and testing.\nexport const unserializeBuildReport = (report: SerializedBuildReport): BuildReport => {\n const buildReport: BuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n };\n\n const reportInputs = report.inputs || [];\n const reportOutputs = report.outputs || [];\n\n const entries: Entry[] = [];\n\n // Prefill inputs and outputs as they are sometimes self-referencing themselves.\n const indexedInputs: Map<string, Input> = new Map();\n const inputs: Input[] = reportInputs.map<Input>((input) => {\n const newInput: Input = {\n ...input,\n // Keep them empty for now, we'll fill them later.\n dependencies: new Set(),\n dependents: new Set(),\n };\n indexedInputs.set(input.filepath, newInput);\n return newInput;\n });\n\n const indexedOutputs: Map<string, Output> = new Map();\n const outputs: Output[] = reportOutputs.map<Output>((output) => {\n const newOutput: Output = { ...output, inputs: [] };\n indexedOutputs.set(output.filepath, newOutput);\n return newOutput;\n });\n\n // Fill in the inputs' dependencies and dependents.\n for (const input of reportInputs) {\n const newInput: Input = indexedInputs.get(input.filepath)!;\n\n // Re-assign the dependencies and dependents to the actual objects.\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n const newDependency = indexedInputs.get(dependency)!;\n newInput.dependencies.add(newDependency);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n const newDependent = indexedInputs.get(dependent)!;\n newInput.dependents.add(newDependent);\n }\n }\n }\n\n // Fill in the outputs' inputs.\n for (const output of reportOutputs) {\n const newOutput: Output = indexedOutputs.get(output.filepath)!;\n if (output.inputs) {\n // Re-assign the inputs to the actual objects.\n newOutput.inputs = output.inputs\n .map<\n // Can be either an input or an output (for sourcemaps).\n Input | Output | undefined\n >((filepath: string) => indexedInputs.get(filepath) || indexedOutputs.get(filepath))\n .filter(Boolean) as (Input | Output)[];\n }\n }\n\n for (const entry of report.entries || []) {\n const newEntry: Entry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs\n .map((filepath: string) => indexedInputs.get(filepath))\n .filter(Boolean) as (Output | Input)[];\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs\n .map((filepath: string) => indexedOutputs.get(filepath))\n .filter(Boolean) as Output[];\n }\n entries.push(newEntry);\n }\n\n return {\n ...buildReport,\n entries,\n inputs,\n outputs,\n };\n};\n\n// Verify that we should get the git information based on the options.\n// Only get git information if sourcemaps are enabled and git is enabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n // If we don't have sourcemaps enabled, we don't need git.\n const gitEnabledFromSourcemaps = !!options.errorTracking?.sourcemaps;\n // If we have the 'enableGit' configuration at the root, use it and default to `true`.\n const gitEnabledFromRoot = options.enableGit ?? true;\n return gitEnabledFromSourcemaps && gitEnabledFromRoot;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// Format a duration 0h 0m 0s 0ms\nexport const formatDuration = (duration: number) => {\n const days = Math.floor(duration / 1000 / 60 / 60 / 24);\n const usedDuration = duration - days * 24 * 60 * 60 * 1000;\n const d = new Date(usedDuration);\n const hours = d.getUTCHours();\n const minutes = d.getUTCMinutes();\n const seconds = d.getUTCSeconds();\n const milliseconds = d.getUTCMilliseconds();\n const timeString =\n `${days ? `${days}d ` : ''}${hours ? `${hours}h ` : ''}${minutes ? `${minutes}m ` : ''}${\n seconds ? `${seconds}s` : ''\n }`.trim();\n // Split here so we can show 0ms in case we have a duration of 0.\n return `${timeString}${!timeString || milliseconds ? ` ${milliseconds}ms` : ''}`.trim();\n};\n\n// Truncate a string to a certain length.\n// Placing a [...] placeholder in the middle.\n// \"A way too long sentence could be truncated a bit.\" => \"A way too[...]could be truncated a bit.\"\nexport const truncateString = (\n str: string,\n maxLength: number = 60,\n placeholder: string = '[...]',\n) => {\n if (str.length <= maxLength) {\n return str;\n }\n\n // We want to keep at the very least 4 characters.\n const stringLength = Math.max(4, maxLength - placeholder.length);\n\n // We want to keep most of the end of the string, hence the 10 chars top limit for left.\n const leftStop = Math.min(10, Math.floor(stringLength / 2));\n const rightStop = stringLength - leftStop;\n\n return `${str.slice(0, leftStop)}${placeholder}${str.slice(-rightStop)}`;\n};\n\n// Remove the sensitive information from a repository URL.\nexport const filterSensitiveInfoFromRepositoryUrl = (repositoryUrl: string = '') => {\n try {\n // Keep empty strings and git@ URLs as they are.\n if (!repositoryUrl || repositoryUrl.startsWith('git@')) {\n return repositoryUrl;\n }\n\n const url = new URL(repositoryUrl);\n\n // Construct clean URL with protocol, host and pathname (if not root)\n const cleanPath = url.pathname === '/' ? '' : url.pathname;\n const protocol = url.protocol ? `${url.protocol}//` : '';\n return `${protocol}${url.host}${cleanPath}`;\n } catch {\n return repositoryUrl;\n }\n};\n\nlet index = 0;\nexport const getUniqueId = () => `${Date.now()}.${performance.now()}.${++index}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type {\n GetLogger,\n GlobalData,\n GlobalStores,\n LogLevel,\n LogOptions,\n TimeLog,\n TimeLogger,\n Timer,\n} from '@dd/core/types';\nimport c from 'chalk';\n\nconst logPriority: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n};\n\n// Which separator to use for plugin names.\nexport const NAME_SEP = '>';\n\nconst cleanName = (name: string) => {\n return name.split(NAME_SEP).map(cleanPluginName).join(NAME_SEP);\n};\n\ntype LogFn = (text: any, type?: LogLevel, opts?: LogOptions) => void;\n\nexport const getLogFn = (\n name: string,\n data: GlobalData,\n stores: GlobalStores,\n logLevel: LogLevel,\n): LogFn => {\n // Will remove any \"datadog-\" prefix and \"-plugin\" suffix in the name string.\n const cleanedName = cleanName(name);\n return (text, type = 'debug', { forward } = {}) => {\n // By default (debug) we print dimmed.\n let color = c.dim;\n let logFn = console.log;\n\n if (type === 'error') {\n color = c.red;\n logFn = console.error;\n } else if (type === 'warn') {\n color = c.yellow;\n logFn = console.warn;\n } else if (type === 'info') {\n color = c.cyan;\n logFn = console.log;\n }\n\n const buildName = data.metadata?.name ? `${data.metadata.name}|` : '';\n const prefix = `[${buildName}${type}|${data.bundler.name}|${cleanedName}]`;\n\n // Keep a trace of the log in the build report.\n const content = typeof text === 'string' ? text : JSON.stringify(text, null, 2);\n stores.logs.push({\n bundler: data.bundler.name,\n pluginName: name,\n type,\n message: content,\n time: Date.now(),\n });\n\n if (type === 'error') {\n stores.errors.push(content);\n }\n if (type === 'warn') {\n stores.warnings.push(content);\n }\n\n if (forward) {\n const forwardLog = async () => {\n try {\n const sendLog = getSendLog(data);\n await sendLog({ message: content, context: { plugin: name, status: type } });\n } catch (e) {\n // Log the error using the parent logger.\n const subLogger = getLogFn(name, data, stores, logLevel);\n subLogger(`Error forwarding log: ${e}`, 'debug');\n }\n };\n stores.queue.push(forwardLog());\n }\n\n // Only log if the log level is high enough.\n if (logPriority[type] >= logPriority[logLevel]) {\n logFn(`${color(prefix)} ${content}`);\n }\n };\n};\n\nexport const getTimeLogger = (\n name: string,\n store: GlobalStores['timings'],\n log: LogFn,\n): TimeLog => {\n return (label, opts = {}) => {\n const { level = 'debug', start = true, log: toLog = true, tags = [] } = opts;\n const timer: Timer = {\n pluginName: name,\n label,\n spans: [],\n tags: [...tags, `plugin:${name}`, `level:${level}`],\n logLevel: level,\n total: 0,\n };\n\n // Add it to the build report.\n store.push(timer);\n\n const getUncompleteSpans = () => timer.spans.filter((span) => !span.end);\n\n // Push a new span.\n const resume: TimeLogger['resume'] = (startTime?: number) => {\n // Ignore if there is already an ongoing span.\n const uncompleteSpans = getUncompleteSpans();\n if (uncompleteSpans.length) {\n return;\n }\n\n // Log the start if it's the first span.\n if (!timer.spans.length && toLog) {\n log(c.dim(`[${c.cyan(label)}] : start`), 'debug');\n }\n\n // Add the new span.\n timer.spans.push({\n start: startTime || Date.now(),\n tags: [`plugin:${name}`],\n });\n };\n\n // Complete all the uncompleted spans.\n const pause: TimeLogger['pause'] = (pauseTime?: number, warn: boolean = true) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n if (warn) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\n }\n return;\n }\n\n if (uncompleteSpans.length > 1) {\n log(`Timer ${c.cyan(label)} has more than one ongoing span.`, 'debug');\n }\n\n for (const span of uncompleteSpans) {\n span.end = pauseTime || Date.now();\n }\n };\n\n // End the timer and add it to the build report.\n const end: TimeLogger['end'] = (endTime?: number) => {\n // We don't want to log a warning if the timer is already paused.\n pause(endTime, false);\n // Compute the total duration.\n const duration = timer.spans.reduce((acc, span) => acc + (span.end! - span.start), 0);\n timer.total = duration;\n if (toLog) {\n log(`[${c.cyan(label)}] : ${c.cyan(formatDuration(duration))}`, level);\n }\n };\n\n // Add a tag to the timer or the ongoing spans.\n const tag: TimeLogger['tag'] = (tagsToAdd, tagOpts = {}) => {\n const { span = false } = tagOpts;\n if (span) {\n const uncompleteSpans = getUncompleteSpans();\n for (const uncompleteSpan of uncompleteSpans) {\n uncompleteSpan.tags.push(...tagsToAdd);\n }\n } else {\n timer.tags.push(...tagsToAdd);\n }\n };\n\n // Auto start the timer.\n if (start) {\n let param: number | undefined;\n if (typeof start === 'number') {\n param = start;\n }\n resume(param);\n }\n\n const timeLogger: TimeLogger = {\n timer,\n resume,\n end,\n pause,\n tag,\n };\n\n return timeLogger;\n };\n};\n\nexport const getLoggerFactory =\n (data: GlobalData, stores: GlobalStores, logLevel: LogLevel = 'warn'): GetLogger =>\n (name) => {\n const log = getLogFn(name, data, stores, logLevel);\n return {\n getLogger: (subName: string) => {\n const logger = getLoggerFactory(data, stores, logLevel);\n return logger(`${cleanName(name)}${NAME_SEP}${subName}`);\n },\n time: getTimeLogger(name, stores.timings, log),\n error: (text: any, opts?: LogOptions) => log(text, 'error', opts),\n warn: (text: any, opts?: LogOptions) => log(text, 'warn', opts),\n info: (text: any, opts?: LogOptions) => log(text, 'info', opts),\n debug: (text: any, opts?: LogOptions) => log(text, 'debug', opts),\n };\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '@dd/core/constants';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport type {\n CustomPluginOptions,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPluginsArg,\n GetPlugins,\n GlobalContext,\n Logger,\n PluginOptions,\n GetWrappedPlugins,\n CustomHooks,\n} from '@dd/core/types';\nimport type { UnpluginOptions } from 'unplugin';\n\n// Unplugin universal hooks.\nconst UNPLUGIN_HOOKS = [\n 'buildEnd',\n 'buildStart',\n 'load',\n 'resolveId',\n 'transform',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['buildRoot', 'init', 'buildReport', 'bundlerReport', 'git'] as const;\n\n// All the hooks that we want to trace.\nconst HOOKS_TO_TRACE = [...UNPLUGIN_HOOKS, ...CUSTOM_HOOKS];\n\n// Represents the hook names a plugin can have (including those we're not tracing).\ntype PluginHookName = keyof (PluginOptions | CustomPluginOptions);\n// Represents the custom hook names.\ntype CustomHookName = (typeof CUSTOM_HOOKS)[number];\n// Represents the unplugin hook names.\ntype UnpluginHookName = (typeof UNPLUGIN_HOOKS)[number];\n// Represents the hook names that we want to trace.\ntype HookName = CustomHookName | UnpluginHookName;\n// Represents the hook handler that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = <T extends HookFn>(\n pluginName: string,\n hookName: HookName,\n hook: T,\n log: Logger,\n): T => {\n // Create a wrapper function that adds timing to any hook function\n const wrapWithTiming = <F extends (...args: any[]) => any>(fn: F): F => {\n return function (this: any, ...args) {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n const result = fn.apply(this, args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n } as F;\n };\n\n // Handle object hooks (with filter/handler pattern)\n if (typeof hook === 'object' && hook !== null && 'handler' in hook) {\n return {\n ...hook,\n handler: wrapWithTiming(hook.handler),\n };\n }\n\n // Handle function hooks\n return wrapWithTiming(hook) as T;\n};\n\nexport const wrapPlugin = (plugin: PluginOptions | CustomPluginOptions, log: Logger) => {\n const wrappedPlugin: PluginOptions | CustomPluginOptions = {\n ...plugin,\n };\n const name = cleanPluginName(plugin.name);\n\n // Wrap all the hooks that we want to trace.\n for (const hookName of HOOKS_TO_TRACE) {\n const hook = plugin[hookName];\n if (hook) {\n wrappedPlugin[hookName as PluginHookName] = wrapHook(name, hookName, hook, log);\n }\n }\n\n return wrappedPlugin;\n};\n\nexport const wrapGetPlugins = (\n context: GlobalContext,\n getPlugins: GetPlugins | GetCustomPlugins | GetInternalPlugins,\n name: string,\n): GetWrappedPlugins => {\n const log = context.getLogger(HOST_NAME);\n // Return the getPlugins function wrapped, so we can measure the initialization time.\n return (arg: GetPluginsArg) => {\n // Start our timer.\n const initTimer = log.time(`hook | init ${name}`, { log: false });\n\n // Wrap all the plugins that are returned by the initial getPlugins function.\n const wrappedPlugins = getPlugins(arg).map((plugin) => wrapPlugin(plugin, log));\n\n // Tag our timer with the plugin names.\n const pluginNames = wrappedPlugins.map((plugin) => `plugin:${plugin.name}`);\n initTimer.tag(pluginNames);\n\n // End of initialization.\n initTimer.end();\n return wrappedPlugins;\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'errorTracking' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-error-tracking-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport path from 'path';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap, MinifiedPathPrefix } from '../types';\n\ntype PartialSourcemap = Pick<Sourcemap, 'minifiedFilePath' | 'minifiedUrl' | 'relativePath'>;\n\n// Helper function to safely join URLs or paths\nexport const joinUrlOrPath = (prefix: MinifiedPathPrefix, relativePath: string): string => {\n // Prefix is a path.\n if (prefix.startsWith('/')) {\n // Simply join the prefix with the relative path.\n return path.join(prefix, relativePath);\n }\n\n // Prefix is a URL.\n try {\n // Ensure it ends with a slash for deterministic URL path joining.\n const normalizedPrefix = prefix.replace(/\\/*$/, '/');\n const url = new URL(normalizedPrefix);\n // Ensure the relative path does not start with a slash\n // otherwise it will act as a \"root\" path when joined with the url.\n const normalizedRelativePath = relativePath.replace(/^[\\\\/]*/, '');\n return new URL(normalizedRelativePath, url).href;\n } catch {\n // Fallback to simple concatenation if URL constructor fails\n return `${prefix}${relativePath}`;\n }\n};\n\nexport const decomposePath = (\n prefix: MinifiedPathPrefix,\n // This is coming from context.bundler.outDir, which is absolute.\n absoluteOutDir: string,\n sourcemapFilePath: string,\n): PartialSourcemap => {\n if (path.extname(sourcemapFilePath) !== '.map') {\n throw new Error(`The file ${chalk.green.bold(sourcemapFilePath)} is not a sourcemap.`);\n }\n\n const minifiedFilePath = sourcemapFilePath.replace(/\\.map$/, '');\n const relativePath = path.relative(absoluteOutDir, minifiedFilePath);\n const minifiedUrl = joinUrlOrPath(prefix, relativePath);\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport type SourcemapsFilesContext = {\n outputs?: Output[];\n outDir: string;\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsFilesContext,\n): Sourcemap[] => {\n if (!context.outputs || context.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.outputs\n .filter((file) => file.filepath.endsWith('.map'))\n .map((file) => file.filepath);\n\n const sourcemapFiles = sourcemapFilesList.map((sourcemapFilePath) => {\n return {\n ...decomposePath(options.minifiedPathPrefix, context.outDir, sourcemapFilePath),\n sourcemapFilePath,\n minifiedPathPrefix: options.minifiedPathPrefix,\n };\n });\n\n return sourcemapFiles;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { File } from 'buffer';\nimport fsp from 'fs/promises';\nimport fs from 'fs';\nimport { JsonStreamStringify } from 'json-stream-stringify';\nimport path from 'path';\nimport { Readable } from 'stream';\n\nimport type { FileValidity, LocalAppendOptions } from '../types';\n\n// Replacing fs-extra with local helpers.\n// Delete folders recursively.\nexport const rm = async (dir: string) => {\n return fsp.rm(dir, { force: true, maxRetries: 3, recursive: true });\n};\nexport const rmSync = (dir: string) => {\n return fs.rmSync(dir, { force: true, maxRetries: 3, recursive: true });\n};\n\n// Mkdir recursively.\nexport const mkdir = async (dir: string) => {\n return fsp.mkdir(dir, { recursive: true });\n};\n\nexport const mkdirSync = (dir: string) => {\n return fs.mkdirSync(dir, { recursive: true });\n};\n\n// Write a file but first ensure the directory exists.\nexport const outputFile = async (filepath: string, data: string) => {\n await mkdir(path.dirname(filepath));\n await fsp.writeFile(filepath, data, { encoding: 'utf-8' });\n};\n\nexport const outputFileSync = (filepath: string, data: string) => {\n mkdirSync(path.dirname(filepath));\n fs.writeFileSync(filepath, data, { encoding: 'utf-8' });\n};\n\n// Output a JSON file.\nexport const outputJson = async (filepath: string, data: any) => {\n await mkdir(path.dirname(filepath));\n // Use streams so it doesn't crash on very large data.\n const writable = fs.createWriteStream(filepath);\n const readable = new JsonStreamStringify(data, undefined, 2);\n const prom = new Promise<void>((resolve, reject) => {\n readable.on('end', () => {\n resolve();\n });\n\n readable.on('error', (err) => {\n reject(err);\n });\n });\n readable.pipe(writable);\n return prom;\n};\n\nexport const outputJsonSync = (filepath: string, data: any) => {\n // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n outputFileSync(filepath, dataString);\n};\n\n// Read a JSON file.\nexport const readJsonSync = (filepath: string) => {\n const data = fs.readFileSync(filepath, { encoding: 'utf-8' });\n return JSON.parse(data);\n};\n\n// Read a file.\nexport const readFile = (filepath: string) => {\n return fsp.readFile(filepath, { encoding: 'utf-8' });\n};\n\nexport const readFileSync = (filepath: string) => {\n return fs.readFileSync(filepath, { encoding: 'utf-8' });\n};\n\nexport const existsSync = (filepath: string) => {\n try {\n return fs.existsSync(filepath);\n } catch (error: any) {\n // If the file does not exist, return false.\n if (error.code === 'ENOENT') {\n return false;\n }\n // If some other error occurs, rethrow it.\n throw error;\n }\n};\n\n// Some other more specific helpers.\n\n// From a path, returns a File to use with native FormData and fetch.\nexport const getFile = async (filepath: string, options: LocalAppendOptions) => {\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n const blob = await fs.openAsBlob(filepath, { type: options.contentType });\n return new File([blob], options.filename);\n } else {\n // Support NodeJS 18-\n const stream = Readable.toWeb(fs.createReadStream(filepath));\n const blob = await new Response(stream).blob();\n const file = new File([blob], options.filename, { type: options.contentType });\n return file;\n }\n};\n\n// Verify that every files are available.\nexport const checkFile = async (filePath: string): Promise<FileValidity> => {\n const validity: FileValidity = {\n empty: false,\n exists: true,\n };\n\n try {\n const { size } = await fsp.stat(filePath);\n if (size === 0) {\n validity.empty = true;\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n validity.exists = false;\n } else {\n // Other kind of error\n throw error;\n }\n }\n\n return validity;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { checkFile } from '@dd/core/helpers/fs';\nimport type { FileValidity, LocalAppendOptions, RepositoryData } from '@dd/core/types';\nimport path from 'path';\n\nimport type { Sourcemap } from '../types';\n\nexport type Payload = {\n content: Map<string, MultipartValue>;\n errors: string[];\n warnings: string[];\n};\n\nexport type Metadata = {\n plugin_version: string;\n project_path: string;\n service: string;\n type: string;\n version: string;\n git_repository_url?: string;\n git_commit_sha?: string;\n};\n\ntype SourcemapValidity = {\n file: FileValidity;\n sourcemap: FileValidity;\n repeatedPrefix: string;\n};\n\nexport interface MultipartStringValue {\n type: 'string';\n value: string;\n options: LocalAppendOptions;\n}\n\nexport interface MultipartFileValue {\n type: 'file';\n path: string;\n options: LocalAppendOptions;\n}\n\nexport type MultipartValue = MultipartStringValue | MultipartFileValue;\n\nconst SLASH_RX = /[/]+|[\\\\]+/g;\nconst SLASH_TRIM_RX = /^[/]+|^[\\\\]+|[/]+$|[\\\\]+$/g;\n\n// Verify any repeated pattern between the path and prefix.\nexport const prefixRepeat = (filePath: string, prefix: string): string => {\n const pathParts = filePath.replace(SLASH_TRIM_RX, '').split(SLASH_RX);\n const prefixParts = prefix.replace(SLASH_TRIM_RX, '').split(SLASH_RX);\n const normalizedPath = pathParts.join('/');\n\n let result = '';\n\n for (let i = 0; i < prefixParts.length; i += 1) {\n // TODO: Check compatibility with Windows paths.\n const partialPrefix = prefixParts.slice(-i).join('/');\n if (normalizedPath.startsWith(partialPrefix)) {\n result = partialPrefix;\n }\n }\n\n return result;\n};\n\nconst getSourcemapValidity = async (\n sourcemap: Sourcemap,\n prefix: string,\n): Promise<SourcemapValidity> => {\n const [resultMinFile, resultSourcemap] = await Promise.all([\n checkFile(sourcemap.minifiedFilePath),\n checkFile(sourcemap.sourcemapFilePath),\n ]);\n\n return {\n file: resultMinFile,\n sourcemap: resultSourcemap,\n repeatedPrefix: prefixRepeat(sourcemap.relativePath, prefix),\n };\n};\n\nexport const getPayload = async (\n sourcemap: Sourcemap,\n metadata: Metadata,\n prefix: string,\n git?: RepositoryData,\n): Promise<Payload> => {\n const validity = await getSourcemapValidity(sourcemap, prefix);\n const errors: string[] = [];\n const warnings: string[] = [];\n const content = new Map<string, MultipartValue>([\n [\n 'event',\n {\n type: 'string',\n options: {\n contentType: 'application/json',\n filename: 'event',\n },\n value: JSON.stringify({\n ...metadata,\n minified_url: sourcemap.minifiedUrl,\n }),\n },\n ],\n [\n 'source_map',\n {\n type: 'file',\n path: sourcemap.sourcemapFilePath,\n options: { filename: 'source_map', contentType: 'application/json' },\n },\n ],\n [\n 'minified_file',\n {\n type: 'file',\n path: sourcemap.minifiedFilePath,\n options: { filename: 'minified_file', contentType: 'application/javascript' },\n },\n ],\n ]);\n\n // Add git payload if available.\n if (git) {\n try {\n content.set('repository', {\n type: 'string',\n options: {\n contentType: 'application/json',\n filename: 'repository',\n },\n value: JSON.stringify({\n data: [\n {\n files: git.trackedFilesMatcher.matchSourcemap(\n sourcemap.sourcemapFilePath,\n (reason) => {\n warnings.push(\n `${path.basename(sourcemap.sourcemapFilePath)}: \"${reason}\"`,\n );\n },\n ),\n hash: git.hash,\n repository_url: git.remote,\n },\n ],\n // NOTE: Make sure to update the version if the format of the JSON payloads changes in any way.\n version: 1,\n }),\n });\n } catch (error: any) {\n warnings.push(\n `Could not attach git data for sourcemap ${sourcemap.sourcemapFilePath}: ${error.message}`,\n );\n }\n }\n\n if (validity.file.empty) {\n errors.push(`Minified file is empty: ${sourcemap.minifiedFilePath}`);\n }\n if (!validity.file.exists) {\n errors.push(`Minified file not found: ${sourcemap.minifiedFilePath}`);\n }\n if (validity.sourcemap.empty) {\n errors.push(`Sourcemap file is empty: ${sourcemap.sourcemapFilePath}`);\n }\n if (!validity.sourcemap.exists) {\n errors.push(`Sourcemap file not found: ${sourcemap.sourcemapFilePath}`);\n }\n if (validity.repeatedPrefix) {\n warnings.push(\n `The minified file path contains a repeated pattern with the minified path prefix: ${validity.repeatedPrefix}`,\n );\n }\n\n return { content, errors, warnings };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getFile } from '@dd/core/helpers/fs';\nimport { doRequest, NB_RETRIES } from '@dd/core/helpers/request';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type { Logger, RepositoryData } from '@dd/core/types';\nimport chalk from 'chalk';\nimport PQueue from 'p-queue';\nimport { Readable } from 'stream';\nimport type { Gzip } from 'zlib';\nimport { createGzip } from 'zlib';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap } from '../types';\n\nimport type { Metadata, MultipartFileValue, Payload } from './payload';\nimport { getPayload } from './payload';\n\ntype DataResponse = { data: Gzip; headers: Record<string, string> };\n\nconst green = chalk.green.bold;\nconst yellow = chalk.yellow.bold;\nconst red = chalk.red.bold;\n\ntype FileMetadata = {\n sourcemap: string;\n file: string;\n};\n\nexport const SOURCEMAPS_API_SUBDOMAIN = 'sourcemap-intake';\nexport const SOURCEMAPS_API_PATH = 'api/v2/srcmap';\n\nexport const getIntakeUrl = (site: string) => {\n return (\n process.env.DATADOG_SOURCEMAP_INTAKE_URL ||\n `https://${SOURCEMAPS_API_SUBDOMAIN}.${site}/${SOURCEMAPS_API_PATH}`\n );\n};\n\n// Use a function to get new streams for each retry.\nexport const getData =\n (payload: Payload, defaultHeaders: Record<string, string> = {}) =>\n async (): Promise<DataResponse> => {\n const form = new FormData();\n const gz = createGzip();\n\n for (const [key, content] of payload.content) {\n const value =\n content.type === 'file'\n ? // eslint-disable-next-line no-await-in-loop\n await getFile(content.path, content.options)\n : new Blob([content.value], { type: content.options.contentType });\n\n form.append(key, value, content.options.filename);\n }\n\n // GZip data, we use a Request to serialize the data and transform it into a stream.\n const req = new Request('fake://url', { method: 'POST', body: form });\n const formStream = Readable.fromWeb(req.body!);\n const data = formStream.pipe(gz);\n\n const headers = {\n 'Content-Encoding': 'gzip',\n ...defaultHeaders,\n ...Object.fromEntries(req.headers.entries()),\n };\n\n return { data, headers };\n };\n\nexport type UploadContext = {\n apiKey?: string;\n bundlerName: string;\n site: string;\n version: string;\n outDir: string;\n};\n\nexport const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: UploadContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.apiKey) {\n errors.push({ error: new Error('No authentication token provided') });\n return { errors, warnings };\n }\n\n if (payloads.length === 0) {\n warnings.push('No sourcemaps to upload');\n return { errors, warnings };\n }\n\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const queue = new Queue({ concurrency: options.maxConcurrency });\n const defaultHeaders = {\n 'DD-EVP-ORIGIN': `${context.bundlerName}-build-plugin_sourcemaps`,\n 'DD-EVP-ORIGIN-VERSION': context.version,\n };\n\n const addPromises = [];\n\n for (const payload of payloads) {\n const metadata = {\n sourcemap: (payload.content.get('source_map') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n };\n\n log.debug(`Queuing ${green(metadata.sourcemap)} | ${green(metadata.file)}`);\n\n addPromises.push(\n queue.add(async () => {\n try {\n await doRequest({\n auth: { apiKey: context.apiKey },\n url: getIntakeUrl(context.site),\n method: 'POST',\n getData: getData(payload, defaultHeaders),\n // On retry we store the error as a warning.\n onRetry: (error: Error, attempt: number) => {\n const warningMessage = `Failed to upload ${yellow(metadata.sourcemap)} | ${yellow(metadata.file)}:\\n ${error.message}\\nRetrying ${attempt}/${NB_RETRIES}`;\n // This will be logged at the end of the process.\n warnings.push(warningMessage);\n log.debug(warningMessage);\n },\n });\n log.debug(`Sent ${green(metadata.sourcemap)} | ${green(metadata.file)}`);\n } catch (e: any) {\n errors.push({ metadata, error: e });\n // Depending on the configuration we throw or not.\n if (options.bailOnError === true) {\n throw e;\n }\n }\n }),\n );\n }\n\n await Promise.all(addPromises);\n await queue.onIdle();\n return { warnings, errors };\n};\n\nexport type SourcemapsSenderContext = UploadContext & {\n git?: RepositoryData;\n};\n\nexport const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsSenderContext,\n log: Logger,\n) => {\n const start = Date.now();\n const prefix = options.minifiedPathPrefix;\n\n const metadata: Metadata = {\n git_repository_url: context.git?.remote,\n git_commit_sha: context.git?.hash,\n plugin_version: context.version,\n project_path: context.outDir,\n service: options.service,\n type: 'js_sourcemap',\n version: options.releaseVersion,\n };\n\n const payloads = await Promise.all(\n sourcemaps.map((sourcemap) => getPayload(sourcemap, metadata, prefix, context.git)),\n );\n\n const errors = payloads.map((payload) => payload.errors).flat();\n const warnings = payloads.map((payload) => payload.warnings).flat();\n\n if (warnings.length > 0) {\n log.warn(`Warnings while preparing payloads:\\n - ${warnings.join('\\n - ')}`);\n }\n\n if (errors.length > 0) {\n const errorMsg = `Failed to prepare payloads, aborting upload :\\n - ${errors.join('\\n - ')}`;\n log.error(errorMsg);\n // Depending on the configuration we throw or not.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n return;\n }\n\n const { errors: uploadErrors, warnings: uploadWarnings } = await upload(\n payloads,\n options,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n version: context.version,\n outDir: context.outDir,\n site: context.site,\n },\n log,\n );\n\n log.info(\n `Done uploading ${green(sourcemaps.length.toString())} sourcemaps in ${green(formatDuration(Date.now() - start))}.`,\n );\n\n if (uploadErrors.length > 0) {\n const listOfErrors = ` - ${uploadErrors\n .map(({ metadata: fileMetadata, error }) => {\n if (fileMetadata) {\n return `${red(fileMetadata.file)} | ${red(fileMetadata.sourcemap)} : ${error.message}`;\n }\n return error.message;\n })\n .join('\\n - ')}`;\n\n const errorMsg = `Failed to upload some sourcemaps:\\n${listOfErrors}`;\n log.error(errorMsg);\n // Depending on the configuration we throw or not.\n // This should not be reached as we'd have thrown earlier.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n }\n\n if (uploadWarnings.length > 0) {\n log.warn(`Warnings while uploading sourcemaps:\\n - ${uploadWarnings.join('\\n - ')}`);\n }\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { outdent } from 'outdent';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Show a pretty summary of the configuration.\n const green = chalk.green.bold;\n const configurationString = Object.entries(options.sourcemaps)\n .map(([key, value]) => ` - ${key}: ${green(value.toString())}`)\n .join('\\n');\n\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n const summary = outdent`\n Uploading ${green(sourcemaps.length.toString())} sourcemaps with configuration:\n ${configurationString}\n `;\n\n log.info(summary);\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n site: context.site,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type {\n ErrorTrackingOptions,\n ErrorTrackingOptionsWithDefaults,\n SourcemapsOptionsWithDefaults,\n} from './types';\n\n// Deal with validation and defaults here.\nexport const validateOptions = (config: Options, log: Logger): ErrorTrackingOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sourcemapsResults = validateSourcemapsOptions(config);\n errors.push(...sourcemapsResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n // Build the final configuration.\n const toReturn: ErrorTrackingOptionsWithDefaults = {\n enable: !!config[CONFIG_KEY],\n ...config[CONFIG_KEY],\n sourcemaps: undefined,\n };\n\n // Fill in the defaults.\n if (sourcemapsResults.config) {\n toReturn.sourcemaps = sourcemapsResults.config;\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nconst validateMinifiedPathPrefix = (minifiedPathPrefix: string): boolean => {\n let host;\n try {\n const objUrl = new URL(minifiedPathPrefix!);\n host = objUrl.host;\n } catch {\n // Do nothing.\n }\n\n if (!host && !minifiedPathPrefix!.startsWith('/')) {\n return false;\n }\n\n return true;\n};\n\nexport const validateSourcemapsOptions = (\n config: Options,\n): ToReturn<SourcemapsOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: ErrorTrackingOptions = config[CONFIG_KEY] || {};\n const toReturn: ToReturn<SourcemapsOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.sourcemaps) {\n // Validate the configuration.\n if (!validatedOptions.sourcemaps.releaseVersion) {\n toReturn.errors.push(`${red('sourcemaps.releaseVersion')} is required.`);\n }\n if (!validatedOptions.sourcemaps.service) {\n toReturn.errors.push(`${red('sourcemaps.service')} is required.`);\n }\n if (!validatedOptions.sourcemaps.minifiedPathPrefix) {\n toReturn.errors.push(`${red('sourcemaps.minifiedPathPrefix')} is required.`);\n }\n\n // Validate the minifiedPathPrefix.\n if (validatedOptions.sourcemaps.minifiedPathPrefix) {\n if (!validateMinifiedPathPrefix(validatedOptions.sourcemaps.minifiedPathPrefix)) {\n toReturn.errors.push(\n `${red('sourcemaps.minifiedPathPrefix')} must be a valid URL or start with '/'.`,\n );\n }\n }\n\n // Add the defaults.\n const sourcemapsWithDefaults: SourcemapsOptionsWithDefaults = {\n bailOnError: false,\n dryRun: false,\n maxConcurrency: 20,\n ...validatedOptions.sourcemaps,\n };\n\n // Save the config.\n toReturn.config = sourcemapsWithDefaults;\n }\n\n return toReturn;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { BuildReport, GetPlugins, RepositoryData } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { uploadSourcemaps } from './sourcemaps';\nimport type { ErrorTrackingOptions, ErrorTrackingOptionsWithSourcemaps } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME } from './constants';\n\nexport type types = {\n // Add the types you'd like to expose here.\n ErrorTrackingOptions: ErrorTrackingOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n // Verify configuration.\n const timeOptions = log.time('validate options');\n const validatedOptions = validateOptions(options, log);\n timeOptions.end();\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return [];\n }\n\n let gitInfo: RepositoryData | undefined;\n let buildReport: BuildReport | undefined;\n\n const handleSourcemaps = async () => {\n if (!validatedOptions.sourcemaps) {\n return;\n }\n const totalTime = log.time('sourcemaps process');\n await uploadSourcemaps(\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n {\n apiKey: context.auth.apiKey,\n bundlerName: context.bundler.name,\n git: gitInfo,\n outDir: context.bundler.outDir,\n outputs: buildReport?.outputs || [],\n site: context.auth.site,\n version: context.version,\n },\n log,\n );\n totalTime.end();\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async git(repoData) {\n gitInfo = repoData;\n\n if (buildReport) {\n await handleSourcemaps();\n }\n },\n async buildReport(report) {\n buildReport = report;\n\n if (gitInfo || !shouldGetGitInfo(options)) {\n await handleSourcemaps();\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Metric } from '@dd/core/types';\n\nconst filterTreeMetrics = (metric: Metric): Metric | null =>\n // Remove tree metrics because way too verbose\n !/modules\\.tree\\.(count|size)$/.test(metric.metric) ? metric : null;\n\nconst filterSourcemapsAndNodeModules = (metric: Metric): Metric | null =>\n metric.tags.some(\n (tag: string) =>\n // Remove sourcemaps.\n /^assetName:.*\\.map$/.test(tag) ||\n // Remove third parties.\n /^moduleName:\\/node_modules/.test(tag),\n )\n ? null\n : metric;\n\nconst filterMetricsOnThreshold = (metric: Metric): Metric | null => {\n const thresholds = {\n size: 100000,\n count: 10,\n duration: 1000,\n };\n // Allow count for smaller results.\n if (/(entries|loaders|warnings|errors)\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Dependencies are huges, lets submit a bit less.\n if (/(modules\\.(dependencies|dependents)$)/.test(metric.metric)) {\n thresholds.count = 30;\n }\n // Dependency tree calculation can output a lot of metrics.\n if (/modules\\.tree\\.count$/.test(metric.metric)) {\n thresholds.count = 150;\n }\n if (/modules\\.tree\\.size$/.test(metric.metric)) {\n thresholds.size = 1500000;\n }\n // We want to track entry size whatever their size.\n if (/entries\\.size$/.test(metric.metric)) {\n thresholds.size = 0;\n }\n // We want to track entry module count whatever their number\n if (/entries\\.modules\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n const avg = metric.points.length\n ? metric.points.reduce((accumulator, currentPoint) => accumulator + currentPoint[1], 0) /\n metric.points.length\n : 0;\n return avg > thresholds[metric.type] ? metric : null;\n};\n\nexport const defaultFilters: ((metric: Metric) => Metric | null)[] = [\n filterTreeMetrics,\n filterSourcemapsAndNodeModules,\n filterMetricsOnThreshold,\n];\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'metrics' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-metrics-plugin` as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { OptionsWithDefaults, Metric, ValueContext, MetricToSend } from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/metrics-plugin/constants';\nimport type {\n Module,\n Compilation,\n MetricsOptionsWithDefaults,\n Filter,\n} from '@dd/metrics-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const getTimestamp = (timestamp?: number): number => {\n return Math.floor((timestamp || Date.now()) / 1000);\n};\n\nexport const validateOptions = (\n opts: OptionsWithDefaults,\n bundlerName: string,\n): MetricsOptionsWithDefaults => {\n const options = opts[CONFIG_KEY];\n\n const timestamp = getTimestamp(options?.timestamp);\n\n let prefix = options?.enableDefaultPrefix === false ? '' : `build.${bundlerName}`;\n if (options?.prefix) {\n prefix += prefix ? `.${options.prefix}` : options.prefix;\n }\n\n return {\n enable: !!opts[CONFIG_KEY],\n enableDefaultPrefix: true,\n enableTracing: false,\n filters: defaultFilters,\n tags: [],\n ...opts[CONFIG_KEY],\n timestamp,\n // Make it lowercase and remove any leading/closing dots.\n prefix: prefix.toLowerCase().replace(/(^\\.*|\\.*$)/g, ''),\n };\n};\n\nconst getMetric = (metric: MetricToSend, defaultTags: string[], prefix: string): MetricToSend => {\n return {\n ...metric,\n tags: [...metric.tags, ...defaultTags],\n metric: prefix ? `${prefix}.${metric.metric}` : metric.metric,\n };\n};\n\nexport const getMetricsToSend = (\n metrics: Set<Metric>,\n timestamp: number,\n filters: Filter[],\n defaultTags: string[],\n prefix: string,\n): Set<MetricToSend> => {\n const metricsToSend: Set<MetricToSend> = new Set();\n\n // Apply filters\n for (const metric of metrics) {\n let processedMetrics: MetricToSend = { ...metric, toSend: true };\n if (filters?.length) {\n for (const filter of filters) {\n const result = filter({\n metric: processedMetrics.metric,\n type: processedMetrics.type,\n points: processedMetrics.points,\n tags: processedMetrics.tags,\n });\n\n if (result) {\n // Keep the toSend value from the original metric.\n processedMetrics = { ...result, toSend: processedMetrics.toSend };\n } else {\n // Do not modify the metric but mark it as not to send.\n processedMetrics.toSend = false;\n }\n }\n }\n\n // We wrap the metric after the filters\n // to ensure we apply the right prefix and default tags\n // without being impacted by the filters.\n metricsToSend.add(getMetric(processedMetrics, defaultTags, prefix));\n }\n\n // Count only the metrics that pass the filters\n const count = Array.from(metricsToSend).filter((m) => m.toSend).length;\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n points: [[timestamp, count + 1]],\n tags: [],\n toSend: true,\n },\n defaultTags,\n prefix,\n ),\n );\n\n return metricsToSend;\n};\n\nexport const getPluginName = (opts: string | { name: string }) =>\n typeof opts === 'string' ? opts : opts.name;\n\n// We want to ensure cwd ends with a slash.\nconst formatCwd = (cwd: string = ''): string => {\n return cwd.endsWith('/') ? cwd : `${cwd}/`;\n};\n\n// Format a module name by trimming the user's specific part out.\nexport const getDisplayName = (name: string, cwd?: string) => {\n let toReturn: string = name;\n const nameSplit: string[] = name.split(formatCwd(cwd));\n if (cwd && nameSplit.length) {\n toReturn = nameSplit.pop()!;\n }\n\n return (\n toReturn\n // Remove loaders query\n .split('!')\n .pop()!\n // Remove everything in front of /node_modules\n .replace(/(.*)?\\/node_modules\\//, '/node_modules/')\n // Remove any prefixing ../\n .replace(/^((\\.)*\\/)+/, '')\n );\n};\n\nexport const formatModuleName = (name: string, context?: string) =>\n name\n // Remove loaders query\n .split('!')\n .pop()!\n // Webpack store its modules with a relative path\n // let's do the same so we can integrate better with it.\n .replace(formatCwd(context), './');\n\nexport const getModulePath = (module: Module, compilation: Compilation) => {\n let path: string | undefined = module.userRequest;\n if (!path) {\n let issuer;\n if (compilation.moduleGraph && typeof compilation.moduleGraph.getIssuer === 'function') {\n issuer = compilation.moduleGraph.getIssuer(module);\n } else {\n issuer = module.issuer;\n }\n\n path = issuer?.userRequest;\n\n if (!path) {\n // eslint-disable-next-line no-underscore-dangle\n path = module._identifier?.split('!').pop();\n }\n }\n return path || 'unknown';\n};\n\n// Find the module name and format it the same way as webpack.\nexport const getModuleName = (module: Module, compilation: Compilation, context?: string) => {\n let name: string = module.name || module.userRequest;\n if (!name) {\n name = getModulePath(module, compilation);\n }\n return formatModuleName(name || 'no-name', context);\n};\n\n// Format the loader's name by extracting it from the query.\n// \"[...]/node_modules/babel-loader/lib/index.js\" => babel-loader\nconst formatLoaderName = (loader: string) =>\n loader.replace(/^.*\\/node_modules\\/(@[a-z0-9][\\w-.]+\\/[a-z0-9][\\w-.]*|[^/]+).*$/, '$1');\n\n// Find a module's loaders names and format them.\nexport const getLoaderNames = (module: Module) =>\n (module.loaders || []).map((l: any) => l.loader || l).map(formatLoaderName);\n\nexport const getValueContext = (args: any[]): ValueContext[] => {\n return args.map((arg) => ({\n type: arg?.constructor?.name ?? typeof arg,\n name: arg?.name,\n value: typeof arg === 'string' ? arg : undefined,\n }));\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Output,\n TimingsMap,\n TimingsReport,\n} from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\n// How many items do we show in the top lists.\nconst TOP = 5;\n// How long a path can be before we truncate it.\nconst MAX_VALUE_LENGTH = 60;\n\nconst numColor = chalk.bold.red;\nconst nameColor = chalk.bold.cyan;\n\ntype ValuesToPrint = { name: string; top: boolean; values: { name: string; value: string }[] };\n\ntype FileReport = {\n name: string;\n aggregatedSize?: number;\n size: number;\n dependencies: Set<string>;\n dependents: Set<string>;\n};\n\n// Sort a collection by attribute\nconst sortDesc = (attr: ((arg: any) => any) | string) => (a: any, b: any) => {\n let aVal;\n let bVal;\n\n if (typeof attr === 'function') {\n aVal = attr(a);\n bVal = attr(b);\n } else {\n aVal = a[attr];\n bVal = b[attr];\n }\n\n if (aVal > bVal) {\n return -1;\n } else if (aVal < bVal) {\n return 1;\n } else {\n return 0;\n }\n};\n\nexport const getGeneralValues = (context: GlobalContext): ValuesToPrint[] => {\n const valuesToPrint: ValuesToPrint = {\n name: 'General Numbers',\n values: [],\n top: false,\n };\n\n const nbModules = context.build.inputs ? context.build.inputs.length : 0;\n const nbAssets = context.build.outputs ? context.build.outputs.length : 0;\n const nbWarnings = context.build.warnings.length;\n const nbErrors = context.build.errors.length;\n const nbEntries = context.build.entries ? context.build.entries.length : 0;\n\n if (context.build.start) {\n valuesToPrint.values.push({\n name: 'Overhead duration',\n value: formatDuration(context.build.start - context.start),\n });\n }\n\n if (context.build.duration) {\n valuesToPrint.values.push({\n name: 'Build duration',\n value: formatDuration(context.build.duration),\n });\n }\n\n if (context.build.writeDuration) {\n valuesToPrint.values.push({\n name: 'Write duration',\n value: formatDuration(context.build.writeDuration),\n });\n }\n\n valuesToPrint.values.push(\n {\n name: 'Number of modules',\n value: nbModules.toString(),\n },\n {\n name: 'Number of assets',\n value: nbAssets.toString(),\n },\n {\n name: 'Number of entries',\n value: nbEntries.toString(),\n },\n {\n name: 'Number of warnings',\n value: nbWarnings.toString(),\n },\n {\n name: 'Number of errors',\n value: nbErrors.toString(),\n },\n );\n\n return [valuesToPrint];\n};\n\nconst getAssetsValues = (context: GlobalContext): ValuesToPrint[] => {\n const assetSizesToPrint: ValuesToPrint = {\n name: 'Asset size',\n values: (context.build.outputs || [])\n // We don't want to report on sourcemaps here.\n .filter((output) => output.type !== 'map')\n .sort(sortDesc((output: Output) => output.size))\n .map((output) => ({\n name: output.name,\n value: prettyBytes(output.size),\n })),\n top: true,\n };\n\n const entrySizesToPrint: ValuesToPrint = {\n name: 'Entry aggregated size',\n values: (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: prettyBytes(entry.size),\n })),\n top: true,\n };\n\n const entryModulesToPrint: ValuesToPrint = {\n name: 'Entry number of modules',\n values:\n (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: entry.inputs.length.toString(),\n })) || [],\n top: true,\n };\n\n return [assetSizesToPrint, entrySizesToPrint, entryModulesToPrint];\n};\n\nconst getModulesValues = (context: GlobalContext): ValuesToPrint[] => {\n const dependentsToPrint: ValuesToPrint = {\n name: `Module total dependents`,\n values: [],\n top: true,\n };\n\n const dependenciesToPrint: ValuesToPrint = {\n name: `Module total dependencies`,\n values: [],\n top: true,\n };\n\n const sizesToPrint: ValuesToPrint = {\n name: `Module size`,\n values: [],\n top: true,\n };\n\n const aggregatedSizesToPrint: ValuesToPrint = {\n name: `Module aggregated size`,\n values: [],\n top: true,\n };\n\n const dependencies: Set<FileReport> = new Set();\n\n // Build our collections.\n const serializedReport = serializeBuildReport(context.build);\n const inputs: Map<string, FileReport> = new Map();\n const fileDependencies: Map<string, Set<string>> = new Map();\n const fileDependents: Map<string, Set<string>> = new Map();\n\n for (const input of serializedReport.inputs || []) {\n // We don't want to report on sourcemaps here.\n if (input.type === 'map') {\n continue;\n }\n\n const dependenciesSet = new Set(input.dependencies);\n const dependentsSet = new Set(input.dependents);\n\n // Create the sets for all the dependencies.\n for (const dep of dependenciesSet) {\n if (!fileDependents.has(dep)) {\n fileDependents.set(dep, new Set());\n }\n fileDependents.get(dep)!.add(input.filepath);\n }\n\n // Create the sets for all the dependents.\n for (const dep of dependentsSet) {\n if (!fileDependencies.has(dep)) {\n fileDependencies.set(dep, new Set());\n }\n fileDependencies.get(dep)!.add(input.filepath);\n }\n\n if (fileDependencies.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependencies = fileDependencies.get(input.filepath)!;\n for (const dep of existingDependencies) {\n dependenciesSet.add(dep);\n }\n }\n\n if (fileDependents.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependents = fileDependents.get(input.filepath)!;\n for (const dep of existingDependents) {\n dependentsSet.add(dep);\n }\n }\n\n fileDependencies.set(input.filepath, dependenciesSet);\n fileDependents.set(input.filepath, dependentsSet);\n\n inputs.set(input.filepath, {\n name: input.name,\n size: input.size,\n dependencies: dependenciesSet,\n dependents: dependentsSet,\n });\n }\n\n for (const [filepath, input] of inputs) {\n const inputDependencies = fileDependencies.get(filepath) || new Set();\n const inputDependents = fileDependents.get(filepath) || new Set();\n\n // Aggregate size.\n let aggregatedSize = input.size;\n for (const dep of inputDependencies) {\n aggregatedSize += inputs.get(dep)?.size || 0;\n }\n\n dependencies.add({\n name: input.name,\n size: input.size,\n aggregatedSize,\n dependents: inputDependents,\n dependencies: inputDependencies,\n });\n }\n\n if (!dependencies.size) {\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint];\n }\n\n const dependenciesArray = Array.from(dependencies);\n // Sort by dependents, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependents.size));\n dependentsToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependents.size.toString(),\n }));\n // Sort by dependencies, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependencies.size));\n dependenciesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependencies.size.toString(),\n }));\n // Sort by size, biggest first\n dependenciesArray.sort(sortDesc('size'));\n sizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.size),\n }));\n // Sort by aggregated size, biggest first\n dependenciesArray.sort(sortDesc('aggregatedSize'));\n aggregatedSizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.aggregatedSize || file.size),\n }));\n\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint, aggregatedSizesToPrint];\n};\n\nconst getTimingValues = (name: string, timings?: TimingsMap): ValuesToPrint[] => {\n if (!timings || !timings.size) {\n return [];\n }\n\n const times = Array.from(timings.values());\n // Sort by duration, longest first\n times.sort(sortDesc('duration'));\n const durationsToPrint: ValuesToPrint = {\n name: `${name} duration`,\n values: times.map((module) => ({\n name: module.name,\n value: formatDuration(module.duration),\n })),\n top: true,\n };\n\n // Sort by increment, biggest first\n times.sort(sortDesc('increment'));\n const hitsToPrint: ValuesToPrint = {\n name: `${name} hits`,\n values: times.map((module) => ({\n name: module.name,\n value: module.increment.toString(),\n })),\n top: true,\n };\n\n return [durationsToPrint, hitsToPrint];\n};\n\nconst renderValues = (values: ValuesToPrint[]): string => {\n let outputString = '';\n\n const titlePadding = 4;\n const valuePadding = 4;\n\n // Cleaning and preparing out the groups.\n for (const group of values) {\n // Only keep the top values if requested.\n if (group.top && group.values.length >= TOP) {\n group.values = group.values.slice(0, TOP);\n group.name = `Top ${TOP} ${group.name}`;\n }\n\n // Truncate values' names when they are way too long.\n for (const value of group.values) {\n value.name = truncateString(value.name, MAX_VALUE_LENGTH);\n }\n }\n\n // Calculating the width of the columns.\n const maxTitleWidth = Math.max(...values.map((val) => val.name.length));\n const maxNameWidth = Math.max(...values.flatMap((val) => val.values.map((v) => v.name.length)));\n const maxValueWidth = Math.max(\n ...values.flatMap((val) => val.values.map((v) => v.value.length)),\n );\n const totalWidth = Math.max(\n maxTitleWidth + titlePadding,\n maxNameWidth + maxValueWidth + valuePadding,\n );\n\n // Composing the output.\n for (const group of values) {\n if (group.values.length === 0) {\n continue;\n }\n\n const titlePad = totalWidth - (group.name.length + titlePadding);\n\n outputString += `\\n== ${group.name} ${'='.repeat(titlePad)}=\\n`;\n\n for (const value of group.values) {\n const valuePad = maxValueWidth - value.value.length;\n outputString += ` [${numColor(value.value)}] ${' '.repeat(valuePad)}${nameColor(value.name)}\\n`;\n }\n }\n\n return outputString;\n};\n\nexport const outputTexts = (globalContext: GlobalContext, log: Logger, timings?: TimingsReport) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (timings) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', timings.modules));\n }\n\n valuesToPrint.push(...getModulesValues(globalContext));\n valuesToPrint.push(...getAssetsValues(globalContext));\n valuesToPrint.push(...getGeneralValues(globalContext));\n\n const outputString = renderValues(valuesToPrint);\n\n log.info(outputString);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing, Value } from '@dd/core/types';\nimport { formatModuleName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\nconst loadersMap: Map<string, Timing> = new Map();\nconst pluginsMap: TimingsMap = new Map();\nconst modulesMap: TimingsMap = new Map();\n\nexport const wrapPlugins = (build: PluginBuild, context: string) => {\n const plugins = build.initialOptions.plugins;\n if (plugins) {\n // We clone plugins so we don't pass modified options to other plugins.\n const initialPlugins = plugins.map((plugin) => {\n return {\n ...plugin,\n };\n });\n for (const plugin of plugins) {\n const oldSetup = plugin.setup;\n plugin.setup = async (esbuild) => {\n const newBuildObject = getNewBuildObject(esbuild, plugin.name, context);\n await oldSetup({\n ...newBuildObject,\n // Use non-modified plugins for other plugins\n initialOptions: { ...newBuildObject.initialOptions, plugins: initialPlugins },\n });\n };\n }\n }\n};\n\nconst getNewBuildObject = (\n build: PluginBuild,\n pluginName: string,\n context: string,\n): PluginBuild => {\n const newBuildObject: any = Object.assign({}, build);\n for (const fn of FN_TO_WRAP) {\n newBuildObject[fn] = async (opts: any, cb: any) => {\n const pluginTiming: Timing = pluginsMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n pluginTiming.events[fn] = pluginTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const isLoader = fn === 'onLoad';\n const initialFunction: any = build[fn];\n return initialFunction(opts, async (...args: any[]) => {\n const modulePath = formatModuleName(args[0].path, context);\n const moduleTiming: Timing = modulesMap.get(modulePath) || {\n name: modulePath,\n increment: 0,\n duration: 0,\n events: {},\n };\n moduleTiming.events[fn] = moduleTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const start = performance.now();\n\n try {\n return await cb(...args);\n } finally {\n const end = performance.now();\n const duration = end - start;\n const statsObject: Value = {\n start,\n end,\n duration,\n context: getValueContext(args),\n };\n\n pluginTiming.events[fn].values.push(statsObject);\n pluginTiming.duration += duration;\n pluginTiming.increment += 1;\n pluginsMap.set(pluginName, pluginTiming);\n\n moduleTiming.events[fn].values.push(statsObject);\n moduleTiming.duration += duration;\n moduleTiming.increment += 1;\n modulesMap.set(modulePath, moduleTiming);\n\n // Only if we're in a loader function.\n if (isLoader) {\n const loaderTiming: Timing = loadersMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n loaderTiming.events[fn] = loaderTiming.events[fn] || {\n name: fn,\n values: [],\n };\n loaderTiming.events[fn].values.push(statsObject);\n loaderTiming.duration += duration;\n loaderTiming.increment += 1;\n loadersMap.set(pluginName, loaderTiming);\n }\n }\n });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap, loaders: loadersMap });\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.buildRoot);\n timeWrap.end();\n build.onEnd(async (result: BuildResult) => {\n if (!result.metafile) {\n logger.warn(\"Missing metafile, can't proceed with modules data.\");\n return;\n }\n\n const timeResult = logger.time('getting plugins results');\n const { plugins, loaders, modules } = getPluginsResults();\n timeResult.end();\n\n await globalContext.asyncHook('timings', {\n tapables: plugins,\n loaders,\n modules,\n });\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing } from '@dd/core/types';\nimport { getDisplayName, getModuleName, getLoaderNames } from '@dd/metrics-plugin/common/helpers';\nimport type { Module, Event, Compilation } from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Loaders {\n constructor(cwd: string) {\n this.cwd = cwd;\n }\n cwd: string;\n started: { [key: string]: Event } = {};\n finished: Event[] = [];\n\n startModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n const loaders = getLoaderNames(module);\n\n if (!loaders.length) {\n // Keep a track of modules without a loader.\n loaders.push('no-loader');\n }\n\n // Store the event until the module is complete.\n this.started[moduleName] = {\n module: getDisplayName(moduleName),\n timings: {\n start: performance.now(),\n duration: 0,\n end: 0,\n },\n loaders,\n };\n }\n\n doneModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n // Get the event for this module.\n const event = this.started[moduleName];\n\n if (!event) {\n return;\n }\n\n event.timings.end = performance.now();\n event.timings.duration = event.timings.end - event.timings.start;\n\n // Store the event.\n this.finished.push(event);\n\n // Delete the entry so another import\n // of the same module can be also reported.\n delete this.started[moduleName];\n }\n\n getResults(): {\n modules: TimingsMap;\n loaders: TimingsMap;\n } {\n const loaders: Map<string, Timing> = new Map();\n const modules: Map<string, Timing> = new Map();\n for (const event of this.finished) {\n const duration = event.timings.end! - event.timings.start;\n\n // Aggregate module timings\n const moduleTiming = modules.get(event.module) || {\n name: event.module,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n const eventName = event.loaders.join(',');\n moduleTiming.events[eventName] = moduleTiming.events[eventName] || {\n name: eventName,\n values: [],\n };\n\n moduleTiming.events[eventName].values.push(event.timings);\n moduleTiming.increment += 1;\n moduleTiming.duration += duration;\n modules.set(event.module, moduleTiming);\n\n // Aggregate loader timings\n for (const loader of event.loaders) {\n const loaderTiming = loaders.get(loader) || {\n name: loader,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n loaderTiming.increment += 1;\n loaderTiming.duration += duration;\n loaders.set(loader, loaderTiming);\n }\n }\n\n return { loaders, modules };\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, ValueContext, TAP_TYPES, Timing } from '@dd/core/types';\nimport { getPluginName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n} from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Tapables {\n constructor(cwd: Tapables['cwd']) {\n this.cwd = cwd;\n }\n cwd: string;\n monitoredTaps: MonitoredTaps = {};\n tapables: Tapable[] = [];\n hooks: Hooks = {};\n timings: TimingsMap = new Map();\n ignoredHooks = [\n // This one triggers a DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK warning.\n 'normalModuleLoader',\n ];\n\n saveResult(\n type: TAP_TYPES,\n pluginName: string,\n hookName: string,\n context: ValueContext[],\n start: number,\n end: number,\n ) {\n const timing: Timing = this.timings.get(pluginName) || {\n name: pluginName,\n duration: 0,\n increment: 0,\n events: {},\n };\n if (!timing.events[hookName]) {\n timing.events[hookName] = {\n name: hookName,\n values: [],\n };\n }\n\n timing.events[hookName].values.push({\n start,\n end,\n duration: end - start,\n context,\n type,\n });\n timing.duration += end - start;\n timing.increment += 1;\n this.timings.set(pluginName, timing);\n }\n\n getResults(): TapablesResult {\n const timings = this.timings;\n\n // Aggregate the durations for each plugin.\n for (const [tapableName, tapable] of this.timings) {\n const timing = tapable;\n timing.duration = Object.values(tapable.events)\n .map((hookArray) =>\n hookArray.values.reduce((previous, current) => {\n return previous + current.end - current.start;\n }, 0),\n )\n .reduce((previous, current) => previous + current, 0);\n timings.set(tapableName, timing);\n }\n\n return {\n monitoredTaps: this.monitoredTaps,\n tapables: this.tapables,\n hooks: this.hooks,\n timings,\n };\n }\n\n getPromiseTapPatch(type: TAP_TYPES, fn: TapPromise, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n const cb = () => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n };\n // Save the result whether it succeeds or not.\n returnValue.then(cb, cb);\n return returnValue;\n };\n }\n\n getAsyncTapPatch(type: TAP_TYPES, fn: TapAsync, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n // Callback is the last argument.\n const originalCB = args.pop();\n const newCB = (...a: [any]) => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return originalCB(...a);\n };\n return fn.apply(this, [...args, newCB]);\n };\n }\n\n getDefaultTapPatch(type: TAP_TYPES, fn: Tap, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return returnValue;\n };\n }\n\n // Patch the tap so we can report its execution duration.\n getTapPatch(type: TAP_TYPES, fn: (args: any) => any, pluginName: string, hookName: string) {\n switch (type) {\n case 'promise':\n return this.getPromiseTapPatch(type, fn, pluginName, hookName);\n case 'async':\n return this.getAsyncTapPatch(type, fn, pluginName, hookName);\n case 'default':\n default:\n return this.getDefaultTapPatch(type, fn, pluginName, hookName);\n }\n }\n\n newTap(\n type: TAP_TYPES,\n hookName: string,\n originalTap: Tap | TapAsync | TapPromise,\n scope: any,\n ) {\n return (options: any, fn: (args: any) => any) => {\n const pluginName = getPluginName(options);\n const key = `${hookName}-${pluginName}`;\n if (this.monitoredTaps[key]) {\n // Since it's monitored, fn is already patched.\n return originalTap.call(scope, options, fn);\n }\n this.monitoredTaps[key] = true;\n const newFn = this.getTapPatch(type, fn, pluginName, hookName);\n return originalTap.call(scope, options, newFn);\n };\n }\n\n replaceTaps(hookName: string, hook: Hook) {\n // Cover three types of tap.\n hook.tap = this.newTap('default', hookName, hook.tap!, hook);\n hook.tapAsync = this.newTap('async', hookName, hook.tapAsync!, hook);\n hook.tapPromise = this.newTap('promise', hookName, hook.tapPromise!, hook);\n }\n\n patchHook(tapableName: string, hookName: string, hook: Hook) {\n // Webpack specific, these _fakeHook are not writable.\n // eslint-disable-next-line no-underscore-dangle\n if (hook._fakeHook) {\n return;\n }\n\n // Skip the current plugin.\n if (tapableName.includes(PLUGIN_NAME)) {\n return;\n }\n\n if (!this.hooks[tapableName]) {\n this.hooks[tapableName] = [];\n }\n\n if (this.hooks[tapableName].includes(hookName)) {\n return;\n }\n\n this.hooks[tapableName].push(hookName);\n this.replaceTaps(hookName, hook);\n }\n\n patchHooks(tapable: Tapable) {\n const name = tapable.constructor.name;\n const hooksToPatch = Object.keys(tapable.hooks).filter((hookName) => {\n // Skip the ignored hooks.\n if (this.ignoredHooks.includes(hookName)) {\n return false;\n }\n\n // Skip the already patched hooks.\n if (this.hooks[name]?.includes(hookName)) {\n return false;\n }\n\n return true;\n });\n\n for (const hookName of hooksToPatch) {\n this.patchHook(name, hookName, tapable.hooks[hookName]);\n }\n }\n\n checkNewHooks() {\n // We reparse hooks in case new ones arrived.\n for (const tapable of this.tapables) {\n this.patchHooks(tapable);\n }\n }\n\n // Let's navigate through all the hooks we can find.\n throughHooks(tapable: Tapable) {\n if (!this.tapables.includes(tapable)) {\n this.tapables.push(tapable);\n }\n\n this.patchHooks(tapable);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type { Compilation } from '@dd/metrics-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.buildRoot);\n const loaders = new Loaders(globalContext.buildRoot);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack and rspack reconciliation.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack and rspack reconciliation.\n compiler.hooks.thisCompilation.tap(HOOK_OPTIONS, (compilation: Compilation) => {\n const compilationTime = log.time('parse compilation hooks');\n tapables.throughHooks(compilation);\n compilationTime.end();\n\n // TODO: Use log.time() to measure modules.\n compilation.hooks.buildModule.tap(HOOK_OPTIONS, (module) => {\n loaders.startModule(module, compilation);\n });\n\n compilation.hooks.succeedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n\n // NOTE: compilation.hooks.failedModule is not available in rspack as of 1.2.8\n // https://rspack.dev/api/plugin-api/compilation-hooks\n if (compilation.hooks.failedModule) {\n compilation.hooks.failedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n }\n });\n\n // We're losing some tracing from plugins by using `afterEmit` instead of `done` but\n // it allows us to centralize the common process better.\n // TODO: Use custom hooks to make this more reliable and not blocked by a race condition.\n compiler.hooks.afterEmit.tapPromise(HOOK_OPTIONS, async () => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n await globalContext.asyncHook('timings', {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\n });\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, GetPlugins, Metric, PluginOptions, TimingsReport } from '@dd/core/types';\n\nimport { getUniversalMetrics, getPluginMetrics, getLoaderMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getMetricsToSend, getTimestamp, validateOptions } from './common/helpers';\nimport { outputTexts } from './common/output/text';\nimport { sendMetrics } from './common/sender';\nimport { PLUGIN_NAME, CONFIG_KEY } from './constants';\nimport { getEsbuildPlugin } from './esbuild-plugin';\nimport type { Filter, MetricsOptions } from './types';\nimport { getWebpackPlugin } from './webpack-plugin';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n filters: defaultFilters,\n};\n\nexport type types = {\n Filter: Filter;\n Metric: Metric;\n MetricsOptions: MetricsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n\n const validatedOptions = validateOptions(options, context.bundler.name);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return plugins;\n }\n\n // Webpack and Esbuild specific plugins.\n // LEGACY\n const legacyPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: getEsbuildPlugin(context, log),\n webpack: getWebpackPlugin(context),\n rspack: getWebpackPlugin(context),\n };\n\n const timeBuild = log.time('build', { start: false });\n // Identify if we need the legacy plugin.\n const needLegacyPlugin =\n validatedOptions.enableTracing &&\n ['esbuild', 'webpack', 'rspack'].includes(context.bundler.name);\n let timingsReport: TimingsReport | undefined;\n let buildReport: BuildReport;\n\n const computeMetrics = async () => {\n context.build.end = Date.now();\n context.build.duration = context.build.end - context.build.start!;\n context.build.writeDuration = context.build.end - realBuildEnd;\n\n const timeMetrics = log.time(`aggregating metrics`);\n const timestamp = validatedOptions.timestamp;\n\n const universalMetrics = getUniversalMetrics(buildReport, timestamp);\n const pluginMetrics = getPluginMetrics(timingsReport?.tapables, timestamp);\n const loaderMetrics = getLoaderMetrics(timingsReport?.loaders, timestamp);\n\n const allMetrics = new Set([...universalMetrics, ...pluginMetrics, ...loaderMetrics]);\n\n const metricsToSend = getMetricsToSend(\n allMetrics,\n timestamp,\n validatedOptions.filters,\n validatedOptions.tags,\n validatedOptions.prefix,\n );\n\n await context.asyncHook('metrics', metricsToSend);\n\n timeMetrics.end();\n\n const timeReport = log.time('outputing report');\n outputTexts(context, log, timingsReport);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-metrics-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n // Set the timestamp to the build start if not provided.\n if (!options[CONFIG_KEY]?.timestamp) {\n validatedOptions.timestamp = getTimestamp(context.build.start);\n }\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n async timings(timings) {\n timingsReport = timings;\n // Once we have both reports, we can compute the metrics.\n if (buildReport) {\n await computeMetrics();\n }\n },\n\n async buildReport(report) {\n buildReport = report;\n // Once we have both reports (or we don't need the legacy plugin),\n // we can compute the metrics.\n if (timingsReport || !needLegacyPlugin) {\n await computeMetrics();\n }\n },\n };\n\n if (validatedOptions.enableTracing) {\n plugins.push(legacyPlugin);\n }\n\n plugins.push(universalPlugin);\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, Metric, TimingsMap } from '@dd/core/types';\n\nexport const getUniversalMetrics = (buildReport: BuildReport, timestamp: number): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n const inputs = buildReport.inputs || [];\n const outputs = buildReport.outputs || [];\n const entries = buildReport.entries || [];\n const nbWarnings = buildReport.warnings.length;\n const nbErrors = buildReport.errors.length;\n const duration = buildReport.duration;\n\n // Create some indexes to speed up the process.\n const entriesPerInput = new Map<string, string[]>();\n const assetsPerInput = new Map<string, string[]>();\n const entriesPerAsset = new Map<string, string[]>();\n\n for (const entry of entries) {\n for (const input of entry.inputs) {\n if (!entriesPerInput.has(input.filepath)) {\n entriesPerInput.set(input.filepath, []);\n }\n entriesPerInput.get(input.filepath)!.push(entry.name);\n }\n for (const output of entry.outputs) {\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (!entriesPerAsset.has(cleanAssetName)) {\n entriesPerAsset.set(cleanAssetName, []);\n }\n entriesPerAsset.get(cleanAssetName)!.push(entry.name);\n }\n }\n\n for (const output of outputs) {\n for (const input of output.inputs) {\n if (!assetsPerInput.has(input.filepath)) {\n assetsPerInput.set(input.filepath, []);\n }\n assetsPerInput.get(input.filepath)!.push(output.name);\n }\n }\n\n // Counts\n metrics\n .add({\n metric: 'assets.count',\n type: 'count',\n points: [[timestamp, outputs.length]],\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n points: [[timestamp, entries.length]],\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n points: [[timestamp, nbErrors]],\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n points: [[timestamp, inputs.length]],\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n points: [[timestamp, nbWarnings]],\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n points: [[timestamp, duration]],\n tags: [],\n });\n }\n\n // Modules\n for (const input of inputs) {\n const tags = [`moduleName:${input.name}`, `moduleType:${input.type}`];\n if (entriesPerInput.has(input.filepath)) {\n tags.push(\n ...entriesPerInput\n .get(input.filepath)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n\n if (assetsPerInput.has(input.filepath)) {\n tags.push(\n ...assetsPerInput.get(input.filepath)!.map((assetName) => `assetName:${assetName}`),\n );\n }\n metrics\n .add({\n metric: 'modules.size',\n type: 'size',\n points: [[timestamp, input.size]],\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n points: [[timestamp, input.dependencies.size]],\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n points: [[timestamp, input.dependents.size]],\n tags,\n });\n }\n\n // Assets\n for (const output of outputs) {\n const tags = [`assetName:${output.name}`, `assetType:${output.type}`];\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (entriesPerAsset.has(cleanAssetName)) {\n tags.push(\n ...entriesPerAsset\n .get(cleanAssetName)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n metrics\n .add({\n metric: 'assets.size',\n type: 'size',\n points: [[timestamp, output.size]],\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n points: [[timestamp, output.inputs.length]],\n tags,\n });\n }\n\n // Entries\n for (const entry of entries) {\n const tags = [`entryName:${entry.name}`];\n metrics\n .add({\n metric: 'entries.size',\n type: 'size',\n points: [[timestamp, entry.size]],\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n points: [[timestamp, entry.inputs.length]],\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n points: [[timestamp, entry.outputs.length]],\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const getPluginMetrics = (\n plugins: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!plugins) {\n return metrics;\n }\n\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n points: [[timestamp, plugins.size]],\n tags: [],\n });\n\n for (const plugin of plugins.values()) {\n let pluginDuration = 0;\n let pluginCount = 0;\n\n for (const hook of Object.values(plugin.events)) {\n let hookDuration = 0;\n pluginCount += hook.values.length;\n for (const v of hook.values) {\n const duration = v.end - v.start;\n hookDuration += duration;\n pluginDuration += duration;\n }\n metrics\n .add({\n metric: 'plugins.hooks.duration',\n type: 'duration',\n points: [[timestamp, hookDuration]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n points: [[timestamp, hook.values.length]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n });\n }\n\n metrics\n .add({\n metric: 'plugins.duration',\n type: 'duration',\n points: [[timestamp, pluginDuration]],\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n points: [[timestamp, pluginCount]],\n tags: [`pluginName:${plugin.name}`],\n });\n }\n\n return metrics;\n};\n\nexport const getLoaderMetrics = (\n loaders: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!loaders) {\n return metrics;\n }\n\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n points: [[timestamp, loaders.size]],\n tags: [],\n });\n\n for (const loader of loaders.values()) {\n metrics\n .add({\n metric: 'loaders.duration',\n type: 'duration',\n points: [[timestamp, loader.duration]],\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n points: [[timestamp, loader.increment]],\n tags: [`loaderName:${loader.name}`],\n });\n }\n\n return metrics;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { Logger, Metric, MetricToSend } from '@dd/core/types';\n\nexport const METRICS_API_PATH = 'api/v1/series';\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; site: string },\n log: Logger,\n) => {\n if (!auth.apiKey) {\n log.info(`Won't send metrics to Datadog: missing API Key.`);\n return;\n }\n if (!metrics.size) {\n log.info(`No metrics to send.`);\n return;\n }\n\n // Only send metrics that are to be sent.\n const metricsToSend: Metric[] = Array.from(metrics)\n .filter((metric) => metric.toSend)\n .map((metric) => {\n return {\n ...metric,\n toSend: undefined,\n };\n });\n\n const metricIterations: Map<string, number> = new Map();\n for (const metric of metricsToSend) {\n if (!metricIterations.has(metric.metric)) {\n metricIterations.set(metric.metric, 0);\n }\n metricIterations.set(metric.metric, metricIterations.get(metric.metric)! + 1);\n }\n\n const metricsNames = Array.from(metricIterations.entries())\n // Sort by metric name.\n .sort(([nameA], [nameB]) => nameA.localeCompare(nameB))\n .map(([name, count]) => `${name} - ${count}`);\n\n log.debug(`\nSending ${metricsToSend.length} metrics.\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `https://api.${auth.site}/${METRICS_API_PATH}?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: metricsToSend } satisfies {\n series: Metric[];\n }),\n }),\n }).catch((e) => {\n log.error(`Error sending metrics ${e}`);\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'output' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-output-plugin' as const;\nexport const FILE_KEYS = [\n 'build',\n 'bundler',\n 'dependencies',\n 'errors',\n 'logs',\n 'metrics',\n 'timings',\n 'warnings',\n] as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Options } from '@dd/core/types';\n\nimport { CONFIG_KEY } from './constants';\nimport type { FileKey, OutputOptions, OutputOptionsWithDefaults } from './types';\n\n// Sanitize the output path.\nconst sanitizeOutputPath = (key: FileKey, value: boolean | string) => {\n if (typeof value === 'string') {\n // Ensure we end with the correct extension.\n return value.replace(/(\\.json)?$/, '.json');\n }\n\n // Transform the value into a path.\n return value === true ? `${key}.json` : value;\n};\n\nconst validateFilesOptions = (\n files: OutputOptions['files'],\n): OutputOptionsWithDefaults['files'] => {\n // If no files object is provided, we'll output all files.\n const defaultValue = typeof files === 'undefined';\n\n const validatedFiles: OutputOptionsWithDefaults['files'] = {\n // Listing everything to keep TS happy.\n build: sanitizeOutputPath('build', files?.build ?? defaultValue),\n bundler: sanitizeOutputPath('bundler', files?.bundler ?? defaultValue),\n dependencies: sanitizeOutputPath('dependencies', files?.dependencies ?? defaultValue),\n errors: sanitizeOutputPath('errors', files?.errors ?? defaultValue),\n logs: sanitizeOutputPath('logs', files?.logs ?? defaultValue),\n metrics: sanitizeOutputPath('metrics', files?.metrics ?? defaultValue),\n timings: sanitizeOutputPath('timings', files?.timings ?? defaultValue),\n warnings: sanitizeOutputPath('warnings', files?.warnings ?? defaultValue),\n };\n\n return validatedFiles;\n};\n\n// Deal with validation and defaults here.\nexport const validateOptions = (options: Options): OutputOptionsWithDefaults => {\n const validatedOptions: OutputOptionsWithDefaults = {\n // By using an empty object, we consider the plugin as enabled.\n enable: !!options[CONFIG_KEY],\n path: './',\n ...options[CONFIG_KEY],\n files: validateFilesOptions(options[CONFIG_KEY]?.files),\n };\n\n return validatedOptions;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { outputJson } from '@dd/core/helpers/fs';\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport type { GetPlugins, Logger, PluginOptions } from '@dd/core/types';\nimport path from 'path';\nimport type { OutputBundle } from 'rollup';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { FileKey, FileValue, OutputOptions } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n OutputOptions: OutputOptions;\n};\n\nconst getXpackPlugin =\n (\n log: Logger,\n write: (getStats: () => any) => void,\n ): PluginOptions['webpack'] & PluginOptions['rspack'] =>\n (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\n write(() => {\n const statsTimer = log.time('stats serialization');\n const statsJson = stats.toJson({\n all: false,\n assets: true,\n children: true,\n chunks: true,\n chunkGroupAuxiliary: true,\n chunkGroupChildren: true,\n chunkGroups: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n relatedAssets: true,\n warnings: true,\n // These two add a massive amount of time to the serialization on big builds.\n reasons: false,\n chunkModules: false,\n });\n statsTimer.end();\n return statsJson;\n });\n });\n };\n\nconst getRollupPlugin = (\n write: (getOutputs: () => OutputBundle[]) => void,\n): PluginOptions['rollup'] & PluginOptions['vite'] => {\n const outputs: Set<OutputBundle> = new Set();\n return {\n buildStart() {\n // Clear set on build start.\n outputs.clear();\n },\n writeBundle(opts, bundle) {\n outputs.add(bundle);\n },\n closeBundle() {\n write(() => Array.from(outputs));\n },\n };\n};\n\nexport const getFilePath = (outDir: string, pathOption: string, filename: string): string => {\n // If we have an absolute path, we use it as is.\n const outputPath = path.isAbsolute(pathOption)\n ? pathOption\n : // Otherwise, we resolve it relative to the bundler output directory.\n path.resolve(outDir, pathOption);\n return path.resolve(outputPath, filename);\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n // Verify configuration.\n const validatedOptions = validateOptions(options);\n const log = context.getLogger(PLUGIN_NAME);\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return [];\n }\n\n const writeFile = (name: FileKey, data: any) => {\n const fileValue: FileValue = validatedOptions.files[name];\n if (!data || fileValue === false) {\n return;\n }\n\n const queuedWrite = async () => {\n const timeWrite = log.time(`output ${fileValue}`);\n const filePath = getFilePath(context.bundler.outDir, validatedOptions.path, fileValue);\n let error: unknown;\n\n try {\n const dataToWrite = typeof data === 'function' ? await data() : data;\n await outputJson(filePath, dataToWrite);\n } catch (e) {\n error = e;\n }\n\n if (error) {\n log.error(`Failed writing ${fileValue}: ${error}`);\n } else {\n log.info(`Wrote \"${filePath}\"`);\n }\n\n timeWrite.end();\n };\n // Do not make the file creations blocking.\n context.queue(queuedWrite());\n };\n\n return [\n {\n name: PLUGIN_NAME,\n buildReport(report) {\n const timeSerialization = log.time(`serialize report`);\n const serializedReport = serializeBuildReport(report);\n timeSerialization.end();\n writeFile('build', {\n bundler: serializedReport.bundler,\n metadata: serializedReport.metadata,\n start: serializedReport.start,\n end: serializedReport.end,\n duration: serializedReport.duration,\n writeDuration: serializedReport.writeDuration,\n entries: serializedReport.entries,\n outputs: serializedReport.outputs,\n });\n writeFile('logs', serializedReport.logs);\n writeFile('timings', serializedReport.timings);\n writeFile('dependencies', serializedReport.inputs);\n writeFile('errors', serializedReport.errors);\n writeFile('warnings', serializedReport.warnings);\n },\n metrics(metrics) {\n writeFile('metrics', () => Array.from(metrics));\n },\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n writeFile('bundler', result.metafile);\n });\n },\n },\n rspack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n rollup: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n vite: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n webpack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// This file is partially generated.\n// Anything between #imports-injection-marker and #types-injection-marker\n// will be updated using the 'yarn cli integrity' command.\nimport type { TrackedFilesMatcher } from '@dd/internal-git-plugin/trackedFilesMatcher';\n/* eslint-disable arca/import-ordering */\n// #imports-injection-marker\nimport type { ErrorTrackingOptions } from '@dd/error-tracking-plugin/types';\nimport type * as errorTracking from '@dd/error-tracking-plugin';\nimport type { MetricsOptions } from '@dd/metrics-plugin/types';\nimport type * as metrics from '@dd/metrics-plugin';\nimport type { OutputOptions } from '@dd/output-plugin/types';\nimport type * as output from '@dd/output-plugin';\nimport type { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\n// #imports-injection-marker\n/* eslint-enable arca/import-ordering */\nimport type { BodyInit } from 'undici-types';\nimport type { UnpluginOptions } from 'unplugin';\n\nimport type { ALL_ENVS, SUPPORTED_BUNDLERS } from './constants';\n\nexport type Assign<A, B> = Omit<A, keyof B> & B;\nexport type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };\nexport type IterableElement<IterableType extends Iterable<unknown>> =\n IterableType extends Iterable<infer ElementType> ? ElementType : never;\n\nexport interface RepositoryData {\n commit: {\n hash: string;\n message: string;\n author: {\n name: string;\n email: string;\n date: string;\n };\n committer: {\n name: string;\n email: string;\n date: string;\n };\n };\n hash: string;\n branch: string;\n remote: string;\n trackedFilesMatcher: TrackedFilesMatcher;\n}\n\nexport type FileReport = { filepath: string; name: string; size: number; type: string };\nexport type Input = FileReport & { dependencies: Set<Input>; dependents: Set<Input> };\nexport type Output = FileReport & { inputs: (Input | Output)[] };\nexport type Entry = Output & { outputs: Output[] };\n\nexport type SerializedEntry = Assign<Entry, { inputs: string[]; outputs: string[] }>;\nexport type SerializedInput = Assign<Input, { dependencies: string[]; dependents: string[] }>;\nexport type SerializedOutput = Assign<Output, { inputs: string[] }>;\n\nexport interface Metric {\n metric: string;\n type: 'count' | 'size' | 'duration';\n points: [number, number][];\n tags: string[];\n}\n\nexport interface MetricToSend extends Metric {\n toSend: boolean;\n}\n\nexport type Log = {\n bundler?: BundlerName;\n pluginName: string;\n type: LogLevel;\n message: string;\n time: number;\n};\nexport type LogTags = string[];\nexport type Timer = {\n label: string;\n pluginName: string;\n spans: { start: number; end?: number; tags: LogTags }[];\n tags: LogTags;\n total: number;\n logLevel: LogLevel;\n};\n\nexport type BuildMetadata = {\n name?: string;\n};\n\nexport type BuildReport = {\n bundler: GlobalData['bundler'];\n errors: GlobalStores['errors'];\n warnings: GlobalStores['warnings'];\n logs: GlobalStores['logs'];\n timings: GlobalStores['timings'];\n metadata: GlobalData['metadata'];\n entries?: Entry[];\n inputs?: Input[];\n outputs?: Output[];\n start?: number;\n end?: number;\n duration?: number;\n writeDuration?: number;\n};\n\n// A JSON safe version of the report.\nexport type SerializedBuildReport = Assign<\n BuildReport,\n {\n entries: SerializedEntry[];\n inputs: SerializedInput[];\n outputs: SerializedOutput[];\n }\n>;\n\nexport type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];\nexport type BundlerReport = GlobalData['bundler'] & {\n outDir: string;\n rawConfig?: any;\n};\n\nexport type InjectedValue = string | (() => Promise<string>);\nexport enum InjectPosition {\n BEFORE,\n MIDDLE,\n AFTER,\n}\nexport type ToInjectItem = {\n type: 'file' | 'code';\n value: InjectedValue;\n position?: InjectPosition;\n fallback?: ToInjectItem;\n};\n\nexport type TimeLogger = {\n timer: Timer;\n resume: (startTime?: number) => void;\n end: (endTime?: number) => void;\n pause: (pauseTime?: number, warn?: boolean) => void;\n tag: (tags: LogTags, opts?: { span?: boolean }) => void;\n};\n\n// The rest parameter is a LogLevel or a boolean to auto start the timer.\nexport type TimeLog = (\n label: string,\n opts?: { level?: LogLevel; start?: boolean | number; log?: boolean; tags?: LogTags },\n) => TimeLogger;\nexport type GetLogger = (name: string) => Logger;\nexport type LogOptions = { forward?: boolean };\nexport type LoggerFn = (text: any, opts?: LogOptions) => void;\nexport type Logger = {\n getLogger: GetLogger;\n time: TimeLog;\n error: LoggerFn;\n warn: LoggerFn;\n info: LoggerFn;\n debug: LoggerFn;\n};\ntype RestContext = string | string[] | number | boolean;\nexport type LogData = Record<string, RestContext | Record<string, RestContext>>;\nexport type DdLogOptions = {\n message: string;\n context?: LogData;\n};\nexport type Env = (typeof ALL_ENVS)[number];\nexport type TriggerHook<R> = <K extends keyof CustomHooks>(\n name: K,\n ...args: Parameters<NonNullable<CustomHooks[K]>>\n) => R;\nexport type GlobalContext = {\n asyncHook: TriggerHook<Promise<void[]>>;\n auth: AuthOptionsWithDefaults;\n build: BuildReport;\n bundler: BundlerReport;\n buildRoot: string;\n env: GlobalData['env'];\n getLogger: GetLogger;\n git?: RepositoryData;\n hook: TriggerHook<void>;\n inject: (item: ToInjectItem) => void;\n pluginNames: string[];\n plugins: (PluginOptions | CustomPluginOptions)[];\n queue: (promise: Promise<any>) => void;\n sendLog: (args: DdLogOptions) => Promise<void>;\n start: number;\n version: GlobalData['version'];\n};\n\nexport type FactoryMeta = {\n bundler: any;\n version: string;\n};\n\nexport type HookFn<T extends Array<any>> = (...args: T) => void;\nexport type AsyncHookFn<T extends Array<any>> = (...args: T) => Promise<void> | void;\nexport type CustomHooks = {\n asyncTrueEnd?: () => Promise<void> | void;\n buildRoot?: HookFn<[string]>;\n init?: HookFn<[GlobalContext]>;\n buildReport?: AsyncHookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n metrics?: AsyncHookFn<[Set<Metric>]>;\n syncTrueEnd?: () => void;\n timings?: AsyncHookFn<[TimingsReport]>;\n};\n\nexport type PluginOptions = Assign<\n UnpluginOptions & CustomHooks,\n {\n name: PluginName;\n }\n>;\n\nexport type CustomPluginOptions = Assign<\n PluginOptions,\n {\n name: string;\n }\n>;\n\nexport type GetPluginsArg = {\n bundler: any;\n context: GlobalContext;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n};\nexport type GetPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetCustomPlugins = (arg: GetPluginsArg) => CustomPluginOptions[];\nexport type GetInternalPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetWrappedPlugins = (arg: GetPluginsArg) => (PluginOptions | CustomPluginOptions)[];\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\nexport type AuthOptions = {\n apiKey?: string;\n appKey?: string;\n site?: string;\n};\n\nexport type AuthOptionsWithDefaults = WithRequired<AuthOptions, 'site'>;\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n enableGit?: boolean;\n logLevel?: LogLevel;\n}\n\nexport interface Options extends BaseOptions {\n // Each product should have a unique entry.\n // #types-injection-marker\n [errorTracking.CONFIG_KEY]?: ErrorTrackingOptions;\n [metrics.CONFIG_KEY]?: MetricsOptions;\n [output.CONFIG_KEY]?: OutputOptions;\n [rum.CONFIG_KEY]?: RumOptions;\n // #types-injection-marker\n customPlugins?: GetCustomPlugins;\n}\n\nexport type OptionsWithDefaults = Assign<\n Assign<Options, Required<BaseOptions>>,\n { auth: AuthOptionsWithDefaults }\n>;\n\nexport type PluginName = `datadog-${Lowercase<string>}-plugin`;\n\ntype Data = { data?: BodyInit; headers?: Record<string, string> };\nexport type RequestOpts = {\n url: string;\n auth?: Pick<AuthOptions, 'apiKey' | 'appKey'>;\n method?: string;\n getData?: () => Promise<Data> | Data;\n type?: 'json' | 'text';\n onRetry?: (error: Error, attempt: number) => void;\n retries?: number;\n minTimeout?: number;\n maxTimeout?: number;\n};\n\nexport type ResolvedEntry = { name?: string; resolved: string; original: string };\n\nexport interface LocalAppendOptions {\n contentType: string;\n filename: string;\n}\n\nexport type FileValidity = {\n empty: boolean;\n exists: boolean;\n};\n\nexport type GlobalData = {\n bundler: {\n name: BundlerName;\n version: string;\n };\n env: Env;\n metadata: BuildMetadata;\n packageName: string;\n version: string;\n};\n\nexport type GlobalStores = {\n errors: string[];\n logs: Log[];\n queue: Promise<any>[];\n timings: Timer[];\n warnings: string[];\n};\n\n/* Legacy Telemetry types */\nexport type TAP_TYPES = 'default' | 'async' | 'promise';\n\nexport interface ValueContext {\n type: string;\n name: string;\n value?: string;\n}\n\nexport interface Value {\n start: number;\n end: number;\n duration: number;\n context?: ValueContext[];\n type?: TAP_TYPES; // Only for webpack.\n}\n\nexport interface Timing {\n name: string;\n duration: number;\n increment: number;\n events: {\n [key: string]: {\n name: string;\n values: Value[];\n };\n };\n}\nexport type TimingsMap = Map<string, Timing>;\n\nexport interface TimingsReport {\n tapables?: TimingsMap;\n loaders?: TimingsMap;\n modules?: TimingsMap;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'rum' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-rum-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-rum-privacy-plugin' as const;\nexport const PRIVACY_HELPERS_FILE_NAME = 'privacy-helpers';\nexport const PRIVACY_HELPERS_MODULE_ID = `\\0datadog:${PRIVACY_HELPERS_FILE_NAME}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { buildTransformOptions } from './transform';\nimport type { PrivacyOptionsWithDefaults } from './types';\n\nexport const getPrivacyPlugin = (\n pluginOptions: PrivacyOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n\n const transformOptions = buildTransformOptions(\n pluginOptions.helperCodeExpression,\n context.bundler.name,\n );\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: pluginOptions.include,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n try {\n return instrument({ id, code }, transformOptions);\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { GlobalContext, InjectedValue } from '@dd/core/types';\n\nimport type { RumOptionsWithDefaults, RumOptionsWithSdk } from './types';\n\ntype RumAppResponse = {\n data: {\n attributes: {\n client_token: string;\n };\n };\n};\n\nconst getContent = (opts: RumOptionsWithDefaults) => {\n return `DD_RUM.init({${JSON.stringify(opts.sdk).replace(/(^{|}$)/g, '')}});\n`;\n};\n\nexport const getInjectionValue = (\n options: RumOptionsWithSdk,\n context: GlobalContext,\n): InjectedValue => {\n const sdkOpts = options.sdk;\n // We already have the clientToken, we can inject it directly.\n if (sdkOpts.clientToken) {\n return getContent(options);\n }\n\n // Let's try and fetch the clientToken from the API.\n if (!context.auth.apiKey || !context.auth.appKey) {\n throw new Error(\n 'Missing \"auth.apiKey\" and/or \"auth.appKey\" to fetch \"rum.sdk.clientToken\".',\n );\n }\n\n // Return the value as an async function so it gets resolved during buildStart.\n return async () => {\n let clientToken: string;\n try {\n // Fetch the client token from the API.\n const appResponse = await doRequest<RumAppResponse>({\n url: `https://api.${context.auth.site}/api/v2/rum/applications/${sdkOpts.applicationId}`,\n type: 'json',\n auth: context.auth,\n });\n\n clientToken = appResponse.data?.attributes?.client_token;\n } catch (e: any) {\n // Could not fetch the clientToken.\n // Let's crash the build.\n throw new Error(`Could not fetch the clientToken: ${e.message}`);\n }\n\n // Still no clientToken.\n if (!clientToken) {\n throw new Error('Missing clientToken in the API response.');\n }\n\n return getContent({\n ...options,\n sdk: {\n clientToken,\n ...sdkOpts,\n },\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options, OptionsWithDefaults } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';\n\nexport const validateOptions = (\n options: OptionsWithDefaults,\n log: Logger,\n): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options);\n\n errors.push(...sdkResults.errors);\n errors.push(...privacyResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n // Build the final configuration.\n const toReturn: RumOptionsWithDefaults = {\n enable: !!options[CONFIG_KEY],\n ...options[CONFIG_KEY],\n sdk: undefined,\n privacy: undefined,\n };\n\n // Fill in the defaults.\n if (sdkResults.config) {\n toReturn.sdk = sdkResults.config;\n }\n\n if (privacyResults.config) {\n toReturn.privacy = privacyResults.config;\n\n log.debug(\n `datadog-rum-privacy plugin options: ${JSON.stringify(toReturn.privacy, (_, value) => {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n })}`,\n { forward: true },\n );\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SDKOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SDKOptionsWithDefaults> = {\n errors: [],\n };\n if (!validatedOptions.sdk) {\n return toReturn;\n }\n\n // Validate the configuration.\n if (!validatedOptions.sdk.applicationId) {\n toReturn.errors.push(`Missing ${red('applicationId')} in the SDK configuration.`);\n }\n\n // Check if we have all we need to fetch the client token if necessary.\n if ((!options.auth.apiKey || !options.auth.appKey) && !validatedOptions.sdk.clientToken) {\n toReturn.errors.push(\n `Missing ${red('\"auth.apiKey\"')} and/or ${red('\"auth.appKey\"')} to fetch missing client token.`,\n );\n }\n\n const sdkWithDefault: SDKOptionsWithDefaults = {\n applicationId: 'unknown_application_id',\n allowUntrustedEvents: false,\n compressIntakeRequests: false,\n defaultPrivacyLevel: 'mask',\n enablePrivacyForActionName: false,\n sessionReplaySampleRate: 0,\n sessionSampleRate: 100,\n silentMultipleInit: false,\n site: 'datadoghq.com',\n startSessionReplayRecordingManually: false,\n storeContextsAcrossPages: false,\n telemetrySampleRate: 20,\n traceSampleRate: 100,\n trackingConsent: 'granted',\n trackLongTasks: false,\n trackResources: false,\n trackUserInteractions: false,\n trackViewsManually: false,\n };\n\n // Save the config.\n toReturn.config = {\n ...sdkWithDefault,\n ...validatedOptions.sdk,\n };\n\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOptionsWithDefaults> => {\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<PrivacyOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.privacy) {\n const privacyWithDefault: PrivacyOptionsWithDefaults = {\n // Exclude dependencies and preval files from being transformed. Files starting with\n // special characters are likely to be virtual libraries and are excluded to avoid loading them.\n exclude: [/\\/node_modules\\//, /\\.preval\\./, /^[!@#$%^&*()=+~`-]/],\n include: [/\\.(?:c|m)?(?:j|t)sx?$/],\n addToDictionaryFunctionName: '$',\n helperCodeExpression: `/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()`,\n };\n\n toReturn.config = {\n ...privacyWithDefault,\n ...validatedOptions.privacy,\n };\n }\n\n return toReturn;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginOptions, GetPlugins } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { getPrivacyPlugin } from './privacy';\nimport { getInjectionValue } from './sdk';\nimport type { RumOptions, RumOptionsWithSdk, RumPublicApi, RumInitConfiguration } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n RumOptions: RumOptions;\n RumPublicApi: RumPublicApi;\n RumInitConfiguration: RumInitConfiguration;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n // Verify configuration.\n const validatedOptions = validateOptions(options, log);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return plugins;\n }\n\n // NOTE: These files are built from \"@dd/tools/rollupConfig.mjs\" and available in the distributed package.\n if (validatedOptions.sdk) {\n // Inject the SDK from the CDN.\n context.inject({\n type: 'file',\n // Using MIDDLE otherwise it's not executed in context.\n position: InjectPosition.MIDDLE,\n // This file is being built alongside the bundler plugin.\n value: path.join(__dirname, './rum-browser-sdk.js'),\n });\n\n // Inject the SDK Initialization.\n context.inject({\n type: 'code',\n position: InjectPosition.MIDDLE,\n value: getInjectionValue(validatedOptions as RumOptionsWithSdk, context),\n });\n }\n\n if (validatedOptions.privacy) {\n // Add the privacy plugin.\n context.inject({\n type: 'file',\n position: InjectPosition.BEFORE,\n value: path.join(__dirname, './privacy-helpers.js'),\n });\n const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n plugins.push(privacyPlugin);\n }\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { InstrumentationOptions } from '@datadog/js-instrumentation-wasm';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(\n helperCodeExpression: string,\n bundlerName: string,\n): InstrumentationOptions {\n const transformOptions: InstrumentationOptions = {\n privacy: {\n addToDictionaryHelper: {\n expression: {\n code: helperCodeExpression,\n },\n },\n },\n };\n if (['esbuild', 'webpack', 'rspack'].includes(bundlerName)) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n return transformOptions;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-analytics-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getAnalyticsPlugins: GetInternalPlugins = ({ context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const buildStartFn = async () => {\n try {\n await context.sendLog({\n message: 'Build started',\n context: {\n plugins: context.pluginNames,\n },\n });\n } catch (e: unknown) {\n // We don't want to break anything in case of error.\n log.debug(`Could not submit data to Datadog: ${e}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n async buildStart() {\n // Only send logs in production.\n if (context.env !== 'production') {\n return;\n }\n\n // Use the queue so it doesn't block the build process.\n context.queue(buildStartFn());\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-async-queue-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME };\n\nexport const getAsyncQueuePlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context, stores } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const errors: string[] = [];\n\n // Initialize the queue function\n context.queue = (promise: Promise<any>) => {\n // Wrap the promise to catch errors immediately\n const wrappedPromise = promise.catch((error: any) => {\n errors.push(error.message || error.toString());\n });\n stores.queue.push(wrappedPromise);\n };\n\n return [\n {\n name: PLUGIN_NAME,\n asyncTrueEnd: async () => {\n // Await for all promises to finish processing.\n await Promise.all(stores.queue);\n if (errors.length > 0) {\n log.error(\n `Error occurred while processing async queue:\\n ${errors.join('\\n ')}`,\n );\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BundlerName, GlobalContext, Logger, ResolvedEntry } from '@dd/core/types';\nimport type { PluginBuild } from 'esbuild';\nimport { glob } from 'glob';\n\n// https://esbuild.github.io/api/#glob-style-entry-points\n// Exported only for testing purposes.\nexport const getAllEntryFiles = (filepath: string): string[] => {\n if (!filepath.includes('*')) {\n return [filepath];\n }\n\n const files = glob.sync(filepath);\n return files;\n};\n\n// Parse, resolve and return all the entries of esbuild.\nexport const getEsbuildEntries = async (\n build: PluginBuild,\n context: GlobalContext,\n log: Logger,\n): Promise<ResolvedEntry[]> => {\n const entries: { name?: string; resolved: string; original: string }[] = [];\n const entryPoints = build.initialOptions.entryPoints;\n const entryPaths: { name?: string; path: string }[] = [];\n const resolutionErrors: string[] = [];\n\n if (Array.isArray(entryPoints)) {\n for (const entry of entryPoints) {\n const fullPath = entry && typeof entry === 'object' ? entry.in : entry;\n entryPaths.push({ path: fullPath });\n }\n } else if (entryPoints && typeof entryPoints === 'object') {\n entryPaths.push(\n ...Object.entries(entryPoints).map(([name, filepath]) => ({ name, path: filepath })),\n );\n }\n\n // Resolve all the paths.\n const proms = entryPaths\n .flatMap((entry) =>\n getAllEntryFiles(entry.path).map<[{ name?: string; path: string }, string]>((p) => [\n entry,\n p,\n ]),\n )\n .map(async ([entry, p]) => {\n const result = await build.resolve(p, {\n kind: 'entry-point',\n resolveDir: context.buildRoot,\n });\n\n if (result.errors.length) {\n resolutionErrors.push(...result.errors.map((e) => e.text));\n }\n\n if (result.path) {\n // Store them for later use.\n entries.push({\n name: entry.name,\n resolved: result.path,\n original: entry.path,\n });\n }\n });\n\n for (const resolutionError of resolutionErrors) {\n log.error(resolutionError);\n }\n\n await Promise.all(proms);\n return entries;\n};\n\n// From a bundler's name, is it part of the \"xpack\" family?\nexport const isXpack = (bundlerName: BundlerName) => ['rspack', 'webpack'].includes(bundlerName);\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\nimport { existsSync } from './fs';\n\n// Will only prepend the cwd if not already there.\nexport const getAbsolutePath = (cwd: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath.startsWith(cwd) || path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.resolve(cwd, filepath);\n};\n\n// Find the highest package.json from the current directory.\nexport const getHighestPackageJsonDir = (currentDir: string): string | undefined => {\n let highestPackage;\n let current = getAbsolutePath(process.cwd(), currentDir);\n let currentDepth = current.split(path.sep).length;\n while (currentDepth > 0) {\n const packagePath = path.resolve(current, `package.json`);\n // Check if package.json exists in the current directory.\n if (existsSync(packagePath)) {\n highestPackage = current;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n currentDepth--;\n }\n return highestPackage;\n};\n\nexport const getClosest = (currentDir: string, filename: string) => {\n let closest;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closest) {\n const filepath = path.resolve(current, filename);\n // Check if it exists in the current directory.\n if (existsSync(filepath)) {\n closest = filepath;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n\n // Exit if we reach the root directory.\n if ([path.sep, ''].includes(current)) {\n break;\n }\n }\n return closest;\n};\n\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n return getClosest(currentDir, 'package.json');\n};\n\n// From a list of path, return the nearest common directory.\nexport const getNearestCommonDirectory = (dirs: string[], cwd?: string) => {\n const dirsToCompare = [...dirs];\n\n const splitPaths = dirsToCompare.map((dir) => {\n const absolutePath = getAbsolutePath(cwd || process.cwd(), dir);\n return absolutePath.split(path.sep);\n });\n\n // Use the shortest length for faster results.\n const minLength = splitPaths.length ? Math.min(...splitPaths.map((parts) => parts.length)) : 0;\n const commonParts = [];\n\n for (let i = 0; i < minLength; i++) {\n // We use the first path as our basis.\n const component = splitPaths[0][i];\n if (splitPaths.every((parts) => parts[i] === component)) {\n commonParts.push(component);\n } else {\n break;\n }\n }\n\n return commonParts.length > 0\n ? // Use \"|| path.sep\" to cover for the [''] case.\n commonParts.join(path.sep) || path.sep\n : path.sep;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\n// Will match any last part of a path after a dot or slash and is a word character.\nconst EXTENSION_RX = /\\.(?!.*(?:\\.|\\/|\\\\))(\\w{1,})/g;\n\n// Will match any type of query characters.\n// \"?\" or \"%3F\" (url encoded \"?\") or \"|\"\nconst QUERY_RX = /(\\?|%3F|\\|)+/gi;\n\nconst getExtension = (filepath: string) => {\n // Reset RX first.\n EXTENSION_RX.lastIndex = 0;\n return EXTENSION_RX.exec(filepath)?.[1];\n};\n\nexport const getType = (name: string): string => {\n if (name === 'unknown') {\n return name;\n }\n\n if (name.includes('webpack/runtime')) {\n return 'runtime';\n }\n\n return getExtension(cleanPath(name)) || 'unknown';\n};\n\nconst BUNDLER_SPECIFICS = ['unknown', 'commonjsHelpers.js', `vite${path.sep}preload-helper.js`];\n// Make list of paths unique, remove the current file and particularities.\nexport const cleanReport = <T = string>(\n report: Set<string>,\n filepath: string,\n filter?: (p: string) => T,\n) => {\n const cleanedReport: Set<T> = new Set();\n for (const reportFilepath of report) {\n const cleanedPath = cleanPath(reportFilepath);\n if (\n // Don't add injections.\n isInjectionFile(reportFilepath) ||\n // Don't add itself into it.\n cleanedPath === filepath ||\n // Remove common specific files injected by bundlers.\n BUNDLER_SPECIFICS.includes(cleanedPath)\n ) {\n continue;\n }\n\n if (filter) {\n const filteredValue = filter(cleanedPath);\n if (filteredValue) {\n cleanedReport.add(filteredValue);\n }\n } else {\n cleanedReport.add(cleanedPath as unknown as T);\n }\n }\n return cleanedReport;\n};\n\n// Clean a path from its query parameters and leading invisible characters.\n// Careful with this and webpack/rspack as loaders may add \"|\" before and after the filepath.\nexport const cleanPath = (filepath: string) => {\n return (\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading, invisible characters,\n // sometimes added in rollup by the commonjs plugin.\n .replace(/^[^\\w\\s.,!@#$%^&*()=+~`\\-/\\\\]+/, '')\n );\n};\n\n// From two file paths, remove the common path prefix.\nexport const removeCommonPrefix = (filepath1: string, filepath2: string) => {\n const filepath2Split = filepath2.split(path.sep);\n const commonPath = filepath1\n .split(path.sep)\n .filter((part, index) => part === filepath2Split[index])\n .join(path.sep);\n return filepath1.replace(commonPath, '');\n};\n\n// Extract a name from a path based on the context (outDir and cwd).\nexport const cleanName = (absoluteOutDir: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath === 'unknown') {\n return filepath;\n }\n\n if (filepath.includes('webpack/runtime')) {\n return filepath.replace('webpack/runtime/', '').replace(/ +/g, '-');\n }\n\n return (\n removeCommonPrefix(\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!,\n absoluteOutDir,\n )\n // Remove node_modules path.\n .split('node_modules')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading dots and slashes.\n .replace(/^((\\.\\.?)?[/\\\\])+/g, '')\n );\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n Output,\n PluginOptions,\n ResolvedEntry,\n} from '@dd/core/types';\nimport path from 'path';\n\nimport { cleanName, getType } from './helpers';\n\n// Re-index metafile data for easier access.\nconst reIndexMeta = <T>(obj: Record<string, T>, buildRoot: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(buildRoot, key);\n return [newKey, value];\n }),\n );\n\nexport const getEsbuildPlugin = (context: GlobalContext, log: Logger): PluginOptions['esbuild'] => {\n return {\n setup(build) {\n const entryNames = new Map();\n let resolvedEntries: ResolvedEntry[] = [];\n const timeBuildReport = log.time('build report', { start: false });\n\n build.onStart(async () => {\n // Start from a clean slate.\n entryNames.clear();\n resolvedEntries = [];\n\n timeBuildReport.resume();\n const timeEntries = log.time('process entries');\n // Store entry names based on the configuration.\n resolvedEntries.push(...(await getEsbuildEntries(build, context, log)));\n for (const entry of resolvedEntries) {\n const cleanedName = cleanName(context.bundler.outDir, entry.resolved);\n if (entry.name) {\n entryNames.set(cleanedName, entry.name);\n } else {\n entryNames.set(cleanedName, cleanedName);\n }\n }\n timeEntries.end();\n timeBuildReport.pause();\n });\n\n build.onEnd(async (result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const outDir = context.bundler.outDir;\n const buildRoot = context.buildRoot;\n for (const error of result.errors) {\n context.build.errors.push(error.text);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.text);\n }\n timeCollect.end();\n\n if (!result.metafile) {\n const warning = 'Missing metafile from build report.';\n context.build.warnings.push(warning);\n log.warn(warning);\n return;\n }\n\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n const timeIndex = log.time('indexing metafile data');\n const metaInputsIndexed = reIndexMeta(result.metafile.inputs, buildRoot);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, buildRoot);\n timeIndex.end();\n\n // From a proxy entry point, created by our injection plugin, get the real path.\n const getRealPathFromInjectionProxy = (entryPoint: string): string => {\n if (!isInjectionFile(entryPoint)) {\n return entryPoint;\n }\n\n const metaInput = metaInputsIndexed[getAbsolutePath(buildRoot, entryPoint)];\n if (!metaInput) {\n return entryPoint;\n }\n\n // Get the first non-injection import.\n const actualImport = metaInput.imports.find(\n (imp) => !isInjectionFile(imp.path),\n );\n if (!actualImport) {\n return entryPoint;\n }\n\n return actualImport.path;\n };\n\n // Loop through inputs.\n const timeInputs = log.time('looping through inputs');\n for (const [filename, input] of Object.entries(result.metafile.inputs)) {\n if (isInjectionFile(filename)) {\n continue;\n }\n\n const filepath = getAbsolutePath(buildRoot, filename);\n const name = cleanName(outDir, filename);\n\n const file: Input = {\n name,\n filepath,\n dependents: new Set(),\n dependencies: new Set(),\n size: input.bytes,\n type: getType(filename),\n };\n reportInputsIndexed[filepath] = file;\n inputs.push(file);\n }\n timeInputs.end();\n\n // Loop through outputs.\n const timeOutputs = log.time('looping through outputs');\n for (const [filename, output] of Object.entries(result.metafile.outputs)) {\n const fullPath = getAbsolutePath(buildRoot, filename);\n const cleanedName = cleanName(outDir, fullPath);\n // Get inputs of this output.\n const inputFiles: Input[] = [];\n for (const inputName of Object.keys(output.inputs)) {\n if (isInjectionFile(inputName)) {\n continue;\n }\n\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, inputName)];\n if (!inputFound) {\n log.debug(`Input ${inputName} not found for output ${cleanedName}`);\n continue;\n }\n\n inputFiles.push(inputFound);\n }\n\n // When splitting, esbuild creates an empty entryPoint wrapper for the chunk.\n // It has no inputs, but still relates to its entryPoint.\n if (output.entryPoint && !inputFiles.length) {\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, output.entryPoint)];\n if (!inputFound) {\n log.debug(\n `Input ${output.entryPoint} not found for output ${cleanedName}`,\n );\n continue;\n }\n inputFiles.push(inputFound);\n }\n\n const file: Output = {\n name: cleanedName,\n filepath: fullPath,\n inputs: inputFiles,\n size: output.bytes,\n type: getType(fullPath),\n };\n\n reportOutputsIndexed[fullPath] = file;\n\n // Store sourcemaps for later filling.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n }\n\n outputs.push(file);\n\n if (!output.entryPoint) {\n continue;\n }\n\n // The entryPoint may have been altered by our injection plugin.\n const inputFile =\n reportInputsIndexed[\n getAbsolutePath(\n buildRoot,\n getRealPathFromInjectionProxy(output.entryPoint),\n )\n ];\n\n if (inputFile) {\n // In the case of \"splitting: true\", all the files are considered entries to esbuild.\n // Not to us.\n // Verify we have listed it as an entry earlier.\n if (!entryNames.get(inputFile.name)) {\n continue;\n }\n\n const entry = {\n ...file,\n name: entryNames.get(inputFile.name) || inputFile.name,\n outputs: [file],\n size: file.size,\n };\n\n tempEntryFiles.push(entry);\n }\n }\n timeOutputs.end();\n\n // Loop through sourcemaps.\n const timeSourcemaps = log.time('looping through sourcemaps');\n for (const sourcemap of tempSourcemaps) {\n const outputFilepath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[outputFilepath];\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n\n // Build our references for the entries.\n const references = {\n inputs: {\n report: reportInputsIndexed,\n meta: metaInputsIndexed,\n },\n outputs: {\n report: reportOutputsIndexed,\n meta: metaOutputsIndexed,\n },\n };\n\n // There are some exceptions we want to ignore.\n const FILE_EXCEPTIONS_RX = /(<runtime>|https:|file:|data:|#)/g;\n const isFileSupported = (filePath: string) => {\n if (isInjectionFile(filePath) || filePath.match(FILE_EXCEPTIONS_RX)) {\n return false;\n }\n return true;\n };\n\n // Go through all imports.\n const getAllImports = <T extends Input | Output>(\n filePath: string,\n ref: typeof references.inputs | typeof references.outputs,\n allImports: Record<string, T> = {},\n ): Record<string, T> => {\n if (!isFileSupported(filePath)) {\n return allImports;\n }\n\n const file = ref.report[filePath];\n if (!file) {\n log.debug(`Could not find report's ${filePath}`);\n return allImports;\n }\n\n // Check if we already have processed it.\n if (allImports[file.filepath]) {\n return allImports;\n }\n\n allImports[file.filepath] = file as T;\n\n const metaFile = ref.meta[filePath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${filePath}`);\n return allImports;\n }\n\n // If there are no imports, we can return what we have.\n if (!metaFile.imports || !metaFile.imports.length) {\n return allImports;\n }\n\n for (const imported of metaFile.imports) {\n const isRelative = imported.path.match(/^\\.\\.?\\//);\n const root = isRelative ? path.dirname(filePath) : buildRoot;\n const absoluteImportPath = getAbsolutePath(root, imported.path);\n\n // We need to register external imports, as this is the first time we see them.\n if (imported.external) {\n if (isFileSupported(imported.path)) {\n // If it's an absolute external import,\n // we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteImportPath : imported.path;\n\n // But we can still add it to the report.\n const inputFile: Input = references.inputs.report[filepath] || {\n filepath,\n name: cleanName(outDir, imported.path),\n size: 0,\n type: 'external',\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if ('dependencies' in file) {\n // file is an Input, so we add the external to its dependencies,\n // and we add file to the external's dependents.\n inputFile.dependents.add(file);\n file.dependencies.add(inputFile);\n }\n\n if ('inputs' in file && !file.inputs.includes(inputFile)) {\n // file is an Output, so we add the external to its inputs.\n file.inputs.push(inputFile);\n }\n\n if (!inputs.includes(inputFile)) {\n inputs.push(inputFile);\n }\n\n references.inputs.report[filepath] = inputFile;\n allImports[inputFile.filepath] = inputFile as T;\n }\n // We can't follow external imports.\n continue;\n }\n\n // Look for the other inputs.\n getAllImports<T>(absoluteImportPath, ref, allImports);\n }\n\n return allImports;\n };\n\n // Loop through entries.\n const timeEntries = log.time('looping through entries');\n // TODO This is slightly underperformant due to getAllImports' recursivity.\n for (const entryFile of tempEntryFiles) {\n const entryInputs: Record<string, Input> = {};\n const entryOutputs: Record<string, Output> = {};\n\n // Do inputs for this entry.\n for (const input of entryFile.inputs) {\n getAllImports<Input>(input.filepath, references.inputs, entryInputs);\n }\n\n // Do outputs for this entry.\n for (const outputFile of entryFile.outputs) {\n getAllImports<Output>(\n outputFile.filepath,\n references.outputs,\n entryOutputs,\n );\n }\n\n entryFile.inputs = Object.values(entryInputs);\n entryFile.outputs = Object.values(entryOutputs);\n entryFile.size = entryFile.outputs.reduce(\n (acc, output) => acc + output.size,\n 0,\n );\n\n entries.push(entryFile);\n }\n timeEntries.end();\n\n // Loop through all inputs to aggregate dependencies and dependents.\n const timeDeps = log.time('aggregate dependencies and dependents');\n for (const input of inputs) {\n // The metafile does not contain external dependencies.\n // So we can only fill in their dependents.\n if (input.type === 'external') {\n continue;\n }\n\n const metaFile = references.inputs.meta[input.filepath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${input.name}`);\n continue;\n }\n\n for (const dependency of metaFile.imports) {\n if (!isFileSupported(dependency.path)) {\n continue;\n }\n\n const isRelative = dependency.path.match(/^\\.?\\.\\//);\n const root = isRelative ? path.dirname(input.filepath) : buildRoot;\n const absoluteDependencyPath = getAbsolutePath(root, dependency.path);\n\n let dependencyFile: Input | undefined;\n if (dependency.external) {\n // If it's an absolute external import, we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteDependencyPath : dependency.path;\n // In case of externals, we use their path directly.\n dependencyFile = references.inputs.report[filepath];\n } else {\n dependencyFile = references.inputs.report[absoluteDependencyPath];\n }\n\n if (!dependencyFile) {\n log.debug(\n `Could not find input file of ${dependency.path} imported from ${input.name}`,\n );\n continue;\n }\n\n input.dependencies.add(dependencyFile);\n // Add itself to the dependency's dependents.\n dependencyFile.dependents.add(input);\n }\n }\n timeDeps.end();\n\n context.build.outputs = outputs;\n context.build.inputs = inputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, Entry, GlobalContext, Input, Output, PluginOptions } from '@dd/core/types';\n\nimport { cleanName, cleanPath, cleanReport, getType } from './helpers';\n\nexport const getRollupPlugin = (context: GlobalContext, log: Logger): PluginOptions['rollup'] => {\n const timeModuleParsing = log.time('module parsing', { start: false });\n const timeBuildReport = log.time('build report', { start: false });\n const timeEntries = log.time('filling entries', { start: false });\n const timeInputsOutputs = log.time('filling inputs and outputs', { start: false });\n const timeCompleteDeps = log.time('completing dependencies and dependents', { start: false });\n const timeDeps = log.time('filling dependencies and dependents', { start: false });\n const timeSourcemaps = log.time('filling sourcemaps inputs', { start: false });\n\n const inputs: Map<string, Input> = new Map();\n const outputs: Map<string, Output> = new Map();\n const entries: Map<string, Entry> = new Map();\n const importsReport: Map<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = new Map();\n\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds.\n // It's useful with a dev server or a build with multiple outputs.\n importsReport.clear();\n inputs.clear();\n outputs.clear();\n entries.clear();\n },\n onLog(level, logItem) {\n if (level === 'warn') {\n context.build.warnings.push(logItem.message || logItem.toString());\n }\n },\n renderError(error) {\n if (error) {\n context.build.errors.push(error.message);\n }\n },\n moduleParsed(info) {\n timeModuleParsing.resume();\n // Store import infos.\n const cleanId = cleanPath(info.id);\n const report = importsReport.get(cleanId) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n // Clean new dependencies and dependents.\n const newDependencies = cleanReport(\n new Set([...info.dynamicallyImportedIds, ...info.importedIds]),\n cleanId,\n );\n\n const newDependents = cleanReport(\n new Set([...info.dynamicImporters, ...info.importers]),\n cleanId,\n );\n\n for (const dependent of newDependents) {\n report.dependents.add(dependent);\n }\n\n for (const dependency of newDependencies) {\n report.dependencies.add(dependency);\n }\n\n importsReport.set(cleanId, report);\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n // This can be called multiple times depending on the number of output configured.\n writeBundle(options, bundle) {\n timeBuildReport.resume();\n const outDir = options.dir\n ? getAbsolutePath(context.buildRoot, options.dir)\n : context.bundler.outDir;\n\n const tempEntryFiles: Set<Entry> = new Set();\n const tempSourcemaps: Set<Output> = new Set();\n const tempOutputsImports: Map<string, Output> = new Map();\n\n // Complete the importsReport with missing dependents and dependencies.\n timeCompleteDeps.resume();\n for (const [filepath, { dependencies, dependents }] of importsReport) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n const report = importsReport.get(cleanedDependency) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependents.has(filepath)) {\n continue;\n }\n\n report.dependents.add(filepath);\n importsReport.set(cleanedDependency, report);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n const report = importsReport.get(cleanedDependent) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependencies.has(filepath)) {\n continue;\n }\n\n report.dependencies.add(filepath);\n importsReport.set(cleanedDependent, report);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n timeInputsOutputs.resume();\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(outDir, filename);\n const size =\n 'code' in asset\n ? Buffer.byteLength(asset.code, 'utf8')\n : Buffer.byteLength(asset.source, 'utf8');\n\n const file: Output = outputs.get(filepath) || {\n name: filename,\n filepath,\n inputs: [],\n size,\n type: getType(filename),\n };\n\n // Store sourcemaps for later filling.\n // Because we may not have reported its input yet.\n if (file.type === 'map') {\n tempSourcemaps.add(file);\n }\n\n if ('modules' in asset) {\n for (const [modulepath, module] of Object.entries(asset.modules)) {\n // We don't want to include commonjs wrappers and proxies that are like:\n // \\u0000{{path}}?commonjs-proxy\n if (cleanPath(modulepath) !== modulepath) {\n continue;\n }\n const moduleFile: Input = inputs.get(modulepath) || {\n name: cleanName(outDir, modulepath),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: modulepath,\n // Since we store as input, we use the originalLength.\n size: module.originalLength,\n type: getType(modulepath),\n };\n file.inputs.push(moduleFile);\n inputs.set(moduleFile.filepath, moduleFile);\n }\n }\n\n // Add imports as inputs.\n // These are external imports since they are declared in the output file.\n if ('imports' in asset) {\n for (const importName of asset.imports) {\n const cleanedImport = cleanPath(importName);\n if (!importsReport.has(cleanedImport)) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports.set(getAbsolutePath(outDir, cleanedImport), file);\n continue;\n }\n\n if (inputs.has(cleanedImport)) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = inputs.get(cleanedImport) || {\n name: cleanName(outDir, importName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: cleanedImport,\n // Since it's external, we don't have the size.\n size: 0,\n type: 'external',\n };\n file.inputs.push(importFile);\n inputs.set(importFile.filepath, importFile);\n }\n }\n\n // Store entries for later filling.\n // As we may not have reported its outputs and inputs yet.\n if ('isEntry' in asset && asset.isEntry) {\n tempEntryFiles.add({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n outputs.set(file.filepath, file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of tempOutputsImports) {\n const outputReport = outputs.get(filepath);\n if (!outputReport) {\n log.debug(`Could not find the output report for ${filepath}.`);\n continue;\n }\n\n if (!output.inputs.includes(outputReport)) {\n output.inputs.push(outputReport);\n }\n }\n\n // Fill in inputs' dependencies and dependents.\n timeDeps.resume();\n for (const [filepath, input] of inputs) {\n const importReport = importsReport.get(filepath);\n if (!importReport) {\n log.debug(`Could not find the import report for ${input.name}.`);\n continue;\n }\n\n for (const dependency of importReport.dependencies) {\n const foundInput = inputs.get(dependency);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(outDir, dependency)} of ${input.name}`,\n );\n continue;\n }\n input.dependencies.add(foundInput);\n }\n\n for (const dependent of importReport.dependents) {\n const foundInput = inputs.get(dependent);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(outDir, dependent)} of ${input.name}`,\n );\n continue;\n }\n input.dependents.add(foundInput);\n }\n }\n timeDeps.end();\n\n // Fill in sourcemaps' inputs if necessary\n if (tempSourcemaps.size) {\n timeSourcemaps.resume();\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = outputs.get(outputPath);\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n }\n\n // Gather all outputs from a filepath, following imports.\n const getAllOutputs = (\n filepath: string,\n allOutputs: Map<string, Output> = new Map(),\n ) => {\n // We already processed it.\n if (allOutputs.has(filepath)) {\n return allOutputs;\n }\n const filename = cleanName(outDir, filepath);\n\n // Get its output.\n const foundOutput = outputs.get(filepath);\n if (!foundOutput) {\n // If it's been reported in the inputs, it means it's an external here.\n // Do not log about externals, we don't expect to find them.\n if (!inputs.has(filename)) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs.set(filepath, foundOutput);\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(outDir, filepath)];\n if (!asset) {\n log.debug(`Could not find asset for ${filename}`);\n return allOutputs;\n }\n\n // Imports are stored in two different places.\n const imports = [];\n if ('imports' in asset) {\n imports.push(...asset.imports);\n }\n if ('dynamicImports' in asset) {\n imports.push(...asset.dynamicImports);\n }\n\n for (const importName of imports) {\n getAllOutputs(getAbsolutePath(outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n timeEntries.resume();\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Array.from(entryOutputs.values());\n\n // NOTE: This might not be as accurate as expected, some inputs could be side-effects.\n // Rollup doesn't provide a way to get the imports of an input.\n entryFile.inputs = Array.from(\n new Set(entryFile.outputs.flatMap((output) => output.inputs)),\n );\n entryFile.size = entryFile.outputs.reduce((acc, output) => acc + output.size, 0);\n\n if (entries.has(entryFile.filepath)) {\n log.debug(\n `Entry \"${entryFile.name}\":\"${cleanName(outDir, entryFile.filepath)}\" already reported.`,\n );\n }\n\n entries.set(entryFile.filepath, entryFile);\n }\n timeEntries.pause();\n timeBuildReport.pause();\n },\n async closeBundle() {\n context.build.inputs = Array.from(inputs.values());\n context.build.outputs = Array.from(outputs.values());\n context.build.entries = Array.from(entries.values());\n\n timeEntries.end();\n timeBuildReport.end();\n\n await context.asyncHook('buildReport', context.build);\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n IterableElement,\n Output,\n PluginOptions,\n} from '@dd/core/types';\n\nimport { cleanName, cleanPath, getType } from './helpers';\n\nexport const getXpackPlugin =\n (\n context: GlobalContext,\n PLUGIN_NAME: string,\n log: Logger,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n let inputs: Input[] = [];\n let outputs: Output[] = [];\n let entries: Entry[] = [];\n\n // Types for the xpack hooks.\n type Compilation = Parameters<Parameters<typeof compiler.hooks.thisCompilation.tap>[1]>[0];\n type Module = IterableElement<Compilation['modules']>;\n type Dependency = IterableElement<IterableElement<Module['blocks']>['dependencies']>;\n type Chunk = IterableElement<Compilation['chunks']>;\n type IndexedModule = {\n identifier: Module['identifier'];\n dependencies: Dependency[];\n blocks: any[];\n externalType: unknown;\n external: unknown;\n };\n\n // Some indexes to help with the report generation.\n const reportInputsIndexed: Map<string, Input> = new Map();\n const reportOutputsIndexed: Map<string, Output> = new Map();\n const modulesPerFile: Map<string, Set<string>> = new Map();\n const moduleIndex: Map<string, IndexedModule> = new Map();\n\n // Some temporary holders to later fill in more data.\n const tempSourcemaps: Output[] = [];\n const tempDeps: Map<string, { dependencies: Set<string>; dependents: Set<string> }> =\n new Map();\n\n const timeBuildReport = log.time('build report', { start: false });\n\n const isModuleSupported = (moduleIdentifier?: string): boolean => {\n return (\n // Ignore unidentified modules and runtimes.\n !!moduleIdentifier &&\n !moduleIdentifier.startsWith('webpack/runtime') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack.\n * 1. Build a dependency graph from all the initial modules once they're finished\n * In afterEmit, modules are concatenated and obfuscated.\n * 2. Once the build is finished and emitted, we can compute the outputs and the entries.\n */\n\n // Clear the data in case we have multiple compilations (dev server, etc...).\n const clear = () => {\n inputs = [];\n outputs = [];\n entries = [];\n reportInputsIndexed.clear();\n reportOutputsIndexed.clear();\n moduleIndex.clear();\n tempDeps.clear();\n };\n\n const cleanExternalName = (name: string) => {\n // Removes \"external \" prefix and surrounding quotes from external dependency names\n // Example: 'external var \"lodash\"' -> 'lodash'\n return name.replace(/(^external[^\"]+\"|\"$)/g, '');\n };\n\n // Index the module by its identifier, resource, request, rawRequest, and userRequest.\n const getKeysToIndex = (mod: Module): Set<string> => {\n const indexes = new Set<string>();\n\n const keysOfModuleToIndexOn: string[] = [\n 'rawRequest',\n 'resource',\n 'request',\n 'userRequest',\n ];\n\n const indexValue = (value: string) => {\n const valueToIndex = cleanPath(value);\n indexes.add(valueToIndex);\n // RSpack only use \"external ...\" for external dependencies.\n // So we need to clean and add the actual name to the index too.\n if (valueToIndex.startsWith('external ')) {\n indexes.add(cleanExternalName(valueToIndex));\n }\n };\n\n // Start by indexing the identifier.\n indexValue(mod.identifier());\n\n // Then index all the other keys.\n for (const key of keysOfModuleToIndexOn) {\n const value = mod[key as keyof Module];\n if (key && key in mod && typeof value === 'string') {\n indexValue(value);\n }\n }\n\n return indexes;\n };\n\n const createIndexedModule = (mod: Module): IndexedModule => {\n const id = mod.identifier();\n return {\n identifier: () => id,\n dependencies: 'dependencies' in mod ? [...mod.dependencies] : [],\n blocks: 'blocks' in mod ? [...mod.blocks] : [],\n externalType: 'externalType' in mod ? mod.externalType : undefined,\n external: 'external' in mod ? mod.external : undefined,\n };\n };\n\n const indexModule = (mod: Module) => {\n const moduleToIndex = createIndexedModule(mod);\n const keysToIndex = getKeysToIndex(mod);\n for (const key of keysToIndex) {\n if (moduleIndex.has(key)) {\n // Update the existing module.\n const previousModule = moduleIndex.get(key)!;\n previousModule.dependencies.push(...(moduleToIndex.dependencies || []));\n previousModule.blocks.push(...(moduleToIndex.blocks || []));\n } else {\n moduleIndex.set(key, moduleToIndex);\n }\n }\n };\n\n // Aggregate all dependencies from a module.\n const getAllDependencies = (\n module: Module | Dependency | Module['blocks'][number],\n dependencies: Dependency[] = [],\n ) => {\n if ('dependencies' in module) {\n for (const dependency of module.dependencies) {\n dependencies.push(dependency);\n getAllDependencies(dependency, dependencies);\n }\n }\n\n if ('blocks' in module) {\n for (const block of module.blocks) {\n getAllDependencies(block, dependencies);\n }\n }\n\n return dependencies;\n };\n\n const getModuleFromDep = (mod: Module, dep: Dependency): IndexedModule | undefined => {\n if ('request' in dep && dep.request) {\n const cleanRequest = cleanPath(dep.request);\n if (moduleIndex.has(cleanRequest)) {\n return moduleIndex.get(cleanRequest);\n }\n if (mod.context) {\n const cleanedPath = getAbsolutePath(cleanPath(mod.context), cleanRequest);\n if (moduleIndex.has(cleanedPath)) {\n return moduleIndex.get(cleanedPath);\n }\n }\n }\n };\n\n const isExternal = (mod: Module | IndexedModule) => {\n if ('externalType' in mod && mod.externalType) {\n return true;\n }\n if ('external' in mod && mod.external) {\n return true;\n }\n if (mod.identifier?.().startsWith('external ')) {\n return true;\n }\n return false;\n };\n\n // Intercept the compilation to then get the modules.\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n clear();\n // Intercept the modules to build the dependency graph.\n compilation.hooks.finishModules.tap(\n PLUGIN_NAME,\n (finishedModules: Iterable<Module>) => {\n timeBuildReport.resume();\n const timeGraph = log.time('dependency graph');\n // First loop to create indexes.\n const timeIndex = log.time('indexing modules');\n for (const module of finishedModules) {\n indexModule(module);\n }\n timeIndex.end();\n\n // Second loop to create the dependency graph.\n const timeInputs = log.time('building inputs');\n for (const module of finishedModules) {\n const moduleIdentifier = module.identifier();\n const moduleName = cleanName(context.bundler.outDir, moduleIdentifier);\n const dependencies: Set<string> = new Set(\n getAllDependencies(module)\n .map((dep) => {\n const mod = getModuleFromDep(module, dep);\n\n // Ignore those we can't identify.\n if (!mod?.identifier()) {\n return false;\n }\n\n const identifier = mod.identifier();\n\n // Only what we support.\n if (!isModuleSupported(identifier)) {\n return false;\n }\n\n // Don't add itself as a dependency.\n if (identifier === moduleIdentifier) {\n return false;\n }\n\n return isExternal(mod)\n ? cleanExternalName(identifier)\n : identifier;\n })\n .filter(Boolean) as string[],\n );\n\n if (!isModuleSupported(moduleIdentifier)) {\n continue;\n }\n\n // Create dependents relationships.\n const moduleDeps = tempDeps.get(moduleIdentifier) || {\n dependents: new Set(),\n dependencies: new Set(),\n };\n for (const depIdentifier of dependencies) {\n const depDeps = tempDeps.get(depIdentifier) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n depDeps.dependents.add(moduleIdentifier);\n moduleDeps.dependencies.add(depIdentifier);\n tempDeps.set(depIdentifier, depDeps);\n }\n\n // Store the dependencies.\n tempDeps.set(moduleIdentifier, moduleDeps);\n\n // Store the inputs.\n const file: Input = isExternal(module)\n ? {\n size: 0,\n name: cleanExternalName(moduleName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: 'external',\n }\n : {\n size: module.size() || 0,\n name: moduleName,\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: getType(moduleIdentifier),\n };\n\n inputs.push(file);\n reportInputsIndexed.set(moduleIdentifier, file);\n\n // If it's an external dependency, we also need to index it by its cleaned name.\n if (isExternal(module)) {\n reportInputsIndexed.set(cleanExternalName(moduleIdentifier), file);\n }\n }\n timeInputs.end();\n\n // Assign dependencies and dependents.\n const timeAssign = log.time('assigning dependencies and dependents');\n for (const input of inputs) {\n const depsReport = tempDeps.get(input.filepath);\n\n if (!depsReport) {\n log.debug(`Could not find dependency report for ${input.name}`);\n continue;\n }\n\n for (const dependency of depsReport.dependencies) {\n const depInput = reportInputsIndexed.get(dependency);\n if (!depInput) {\n log.debug(`Could not find input of dependency ${dependency}`);\n continue;\n }\n input.dependencies.add(depInput);\n }\n\n for (const dependent of depsReport.dependents) {\n const depInput = reportInputsIndexed.get(dependent);\n if (!depInput) {\n log.debug(`Could not find input of dependent ${dependent}`);\n continue;\n }\n input.dependents.add(depInput);\n }\n }\n timeAssign.end();\n timeGraph.end();\n timeBuildReport.pause();\n },\n );\n });\n\n compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (result: Compilation) => {\n timeBuildReport.resume();\n const chunks = result.chunks;\n const assets = result.getAssets();\n\n const getChunkFiles = (chunk: Chunk) => {\n return [...(chunk.files || []), ...(chunk.auxiliaryFiles || [])].map((f: string) =>\n getAbsolutePath(context.bundler.outDir, f),\n );\n };\n\n const timeChunks = log.time('indexing chunks');\n const chunkGraph = result.chunkGraph;\n for (const chunk of chunks) {\n const files = getChunkFiles(chunk);\n\n const chunkModules =\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n (chunkGraph?.getChunkModules(chunk) || [])\n .flatMap((m) => {\n // modules exists but isn't in the types.\n return 'modules' in m && Array.isArray(m.modules)\n ? m.modules.map((m2) => m2.identifier())\n : m.identifier();\n })\n .filter(isModuleSupported);\n\n for (const file of files) {\n if (getType(file) === 'map') {\n continue;\n }\n const fileModules = modulesPerFile.get(file) || new Set();\n for (const module of chunkModules) {\n fileModules.add(module);\n }\n modulesPerFile.set(file, fileModules);\n }\n }\n timeChunks.end();\n\n // Build outputs\n const timeOutputs = log.time('building outputs');\n for (const asset of assets) {\n const file: Output = {\n size: asset.source.size() || 0,\n name: asset.name,\n inputs: [],\n filepath: getAbsolutePath(context.bundler.outDir, asset.name),\n type: getType(asset.name),\n };\n\n reportOutputsIndexed.set(file.filepath, file);\n outputs.push(file);\n\n // If it's a sourcemap, store it, we'll fill its input when we'll have\n // referenced all the outputs.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n continue;\n }\n\n // Add the inputs.\n const fileModules = modulesPerFile.get(file.filepath);\n if (!fileModules) {\n log.debug(`Could not find modules for ${file.name}`);\n continue;\n }\n\n for (const moduleIdentifier of fileModules) {\n const inputFound = reportInputsIndexed.get(moduleIdentifier);\n if (!inputFound) {\n log.debug(`Could not find input of ${moduleIdentifier}`);\n continue;\n }\n file.inputs.push(inputFound);\n }\n }\n timeOutputs.end();\n\n // Fill in inputs for sourcemaps.\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputFound = reportOutputsIndexed.get(\n sourcemap.filepath.replace(/\\.map$/, ''),\n );\n\n if (!outputFound) {\n log.debug(`Output not found for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(outputFound);\n }\n timeSourcemaps.end();\n\n // Build entries\n const timeEntries = log.time('building entries');\n for (const [name, entrypoint] of result.entrypoints) {\n const entryOutputs: Map<string, Output> = new Map();\n const entryInputs: Map<string, Input> = new Map();\n let size = 0;\n const entryFiles = entrypoint.chunks.flatMap(getChunkFiles);\n\n // FIXME This is not a 100% reliable way to get the entry filename.\n const entryFilename = entrypoint.chunks\n // Get the chunks that have entry modules.\n .filter(\n (chunk: Chunk) =>\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk) || false,\n )\n // Get the files of those chunks.\n .flatMap((c) => Array.from(c.files))\n // Filter the ones that includes the entry name.\n .filter(\n (f) => f.includes(name) || (entrypoint.name && f.includes(entrypoint.name)),\n )\n // Only keep JS files.\n .find((f) => getType(f) === 'js');\n\n for (const file of entryFiles) {\n const outputFound = reportOutputsIndexed.get(file);\n if (!file || !outputFound) {\n log.debug(`Could not find output of ${JSON.stringify(file)}`);\n continue;\n }\n if (outputFound.type !== 'map' && !entryOutputs.has(outputFound.name)) {\n entryOutputs.set(outputFound.name, outputFound);\n // We know it's not a map, so we cast it.\n for (const input of outputFound.inputs as Input[]) {\n if (!entryInputs.has(input.filepath)) {\n entryInputs.set(input.filepath, input);\n }\n }\n // We don't want to include sourcemaps in the sizing.\n size += outputFound.size;\n }\n }\n\n const file: Entry = {\n name,\n filepath: entryFilename\n ? getAbsolutePath(context.bundler.outDir, entryFilename)\n : 'unknown',\n size,\n inputs: Array.from(entryInputs.values()),\n outputs: Array.from(entryOutputs.values()),\n type: entryFilename ? getType(entryFilename) : 'unknown',\n };\n\n entries.push(file);\n }\n timeEntries.end();\n\n // Save everything in the context.\n for (const error of result.errors) {\n context.build.errors.push(error.message);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.message);\n }\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions } from '@dd/core/types';\n\nimport { getEsbuildPlugin } from './esbuild';\nimport { getRollupPlugin } from './rollup';\nimport { getXpackPlugin } from './xpack';\n\nexport const PLUGIN_NAME = 'datadog-build-report-plugin';\n\nexport const getBuildReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n esbuild: getEsbuildPlugin(context, log),\n rspack: getXpackPlugin(context, PLUGIN_NAME, log),\n webpack: getXpackPlugin(context, PLUGIN_NAME, log),\n // Vite and Rollup have the same API.\n vite: getRollupPlugin(context, log) as PluginOptions['vite'],\n rollup: getRollupPlugin(context, log),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath, getNearestCommonDirectory } from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\nimport type { InputOptions, OutputOptions } from 'rollup';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\nexport const getAbsoluteOutDir = (buildRoot: string, outDir?: string) => {\n if (!outDir) {\n return '';\n }\n\n return path.isAbsolute(outDir) ? outDir : path.resolve(buildRoot, outDir);\n};\n\nexport const getOutDirsFromOutputs = (\n outputOptions?: OutputOptions | OutputOptions[],\n): string[] => {\n if (!outputOptions) {\n return [];\n }\n\n const normalizedOutput = Array.isArray(outputOptions) ? outputOptions : [outputOptions];\n return normalizedOutput\n .map((o) => {\n if (o.dir) {\n return o.dir;\n }\n if (o.file) {\n return path.dirname(o.file);\n }\n })\n .filter(Boolean) as string[];\n};\n\nexport const getIndirsFromInputs = (options: InputOptions) => {\n const inDirs: Set<string> = new Set();\n\n if (options.input) {\n const normalizedInput = Array.isArray(options.input)\n ? options.input\n : typeof options.input === 'object'\n ? Object.values(options.input)\n : [options.input];\n\n for (const input of normalizedInput) {\n if (typeof input !== 'string') {\n throw new Error('Invalid input type');\n }\n inDirs.add(path.dirname(input));\n }\n }\n\n return Array.from(inDirs);\n};\n\nconst xpackPlugin: (context: GlobalContext) => PluginOptions['webpack'] & PluginOptions['rspack'] =\n (context) => (compiler) => {\n context.bundler.rawConfig = compiler.options;\n\n if (compiler.options.output?.path) {\n // While webpack doesn't allow for non-absolute paths,\n // rspack does, and will fallback to use process.cwd().\n context.bundler.outDir = getAbsoluteOutDir(process.cwd(), compiler.options.output.path);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.buildRoot = compiler.options.context;\n }\n context.hook('buildRoot', context.buildRoot);\n };\n\nconst vitePlugin = (context: GlobalContext): PluginOptions['vite'] => {\n return {\n configResolved(config) {\n context.bundler.rawConfig = config;\n // If we have the outDir configuration from Vite.\n let outDir = config.build?.outDir ?? 'dist';\n // We need to know if we have a rollup output configuration.\n // As it will override Vite's outDir and root.\n const output = config.build?.rollupOptions?.output as\n | OutputOptions\n | OutputOptions[]\n | undefined;\n\n const outDirs = getOutDirsFromOutputs(output);\n\n // Vite will fallback to process.cwd() if no root is provided.\n context.buildRoot = config.root ?? process.cwd();\n // Vite will fallback to process.cwd() if we have an output configuration with dirs.\n if (output && outDirs.length) {\n // Now compute the nearest common directory from the output directories.\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Make sure the outDir is absolute.\n context.bundler.outDir = getAbsoluteOutDir(context.buildRoot, outDir);\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n },\n };\n};\n\n// TODO: Add universal config report with list of plugins (names), loaders.\nexport const getBundlerReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const bundlerReportPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: {\n setup(build) {\n context.bundler.rawConfig = build.initialOptions;\n\n if (build.initialOptions.absWorkingDir) {\n context.buildRoot = build.initialOptions.absWorkingDir;\n }\n\n if (build.initialOptions.outdir) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n build.initialOptions.outdir,\n );\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n path.dirname(build.initialOptions.outfile),\n );\n }\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n },\n },\n webpack: xpackPlugin(context),\n rspack: xpackPlugin(context),\n vite: vitePlugin(context),\n rollup: {\n options(options) {\n // By default, with relative paths, rollup will use process.cwd() as the CWD.\n let outDir;\n if ('output' in options) {\n const outDirs = getOutDirsFromOutputs(\n options.output as OutputOptions | OutputOptions[],\n );\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Compute input directories if possible.\n const inDirs = getIndirsFromInputs(options);\n\n if (outDir) {\n context.bundler.outDir = getAbsolutePath(process.cwd(), outDir);\n const computedCwd = getNearestCommonDirectory(\n [outDir, ...inDirs],\n process.cwd(),\n );\n // If the computed CWD is the root directory, it means we could not compute it,\n // so we fallback to process.cwd().\n context.buildRoot = computedCwd === path.sep ? process.cwd() : computedCwd;\n } else {\n // Fallback to process.cwd()/dist as it is rollup's default.\n context.buildRoot = getNearestCommonDirectory(inDirs, process.cwd());\n context.bundler.outDir = path.resolve(process.cwd(), 'dist');\n }\n\n context.hook('buildRoot', context.buildRoot);\n },\n buildStart(options) {\n // Save the resolved options.\n context.bundler.rawConfig = options;\n },\n renderStart(outputOptions) {\n // Save the resolved options.\n context.bundler.rawConfig.outputs = context.bundler.rawConfig.outputs || [];\n context.bundler.rawConfig.outputs.push(outputOptions);\n context.hook('bundlerReport', context.bundler);\n\n // Verify that the output directory is the same as the one computed in the options hook.\n const outDirs = getOutDirsFromOutputs(outputOptions);\n // Rollup always uses process.cwd() as the CWD.\n const outDir = getNearestCommonDirectory(outDirs, process.cwd());\n if (!outDir.startsWith(context.bundler.outDir)) {\n log.info(\n 'The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.',\n );\n }\n },\n },\n };\n\n return [bundlerReportPlugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-custom-hooks-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, TriggerHook } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getCustomHooksPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const executeHooks =\n (async: boolean): TriggerHook<Promise<void[]> | void> =>\n (hookName, ...hookArgs) => {\n const timeHook = log.time(`execution | ${hookName}`, {\n tags: ['type:custom-hook', `hook:${hookName}`],\n });\n const errors: string[] = [];\n const proms: Promise<void>[] = [];\n\n for (const plugin of context.plugins) {\n if (!(hookName in plugin)) {\n continue;\n }\n\n const hookFn = plugin[hookName];\n if (typeof hookFn !== 'function') {\n errors.push(\n `Plugin \"${plugin.name}\" has an invalid hook type for \"${hookName}\". [${typeof hookFn}]`,\n );\n continue;\n }\n\n try {\n // Re-typing to take over typechecking.\n const result: any = hookFn(...(hookArgs as any[]));\n\n if (result instanceof Promise) {\n // Confirm that the result is not an unsupported Promise.\n if (!async) {\n errors.push(\n `Plugin \"${plugin.name}\" returned a promise on the non async hook \"${hookName}\".`,\n );\n }\n proms.push(result);\n }\n } catch (e) {\n errors.push(`Plugin \"${plugin.name}\" errored on hook \"${hookName}\". [${e}]`);\n }\n }\n\n if (errors.length > 0) {\n for (const error of errors) {\n log.error(error);\n }\n throw new Error(`Some plugins errored during the hook execution.`);\n }\n\n return Promise.all(proms).finally(() => timeHook.end());\n };\n\n // Define the hook functions.\n context.hook = executeHooks(false);\n // Define the asyncHook functions.\n context.asyncHook = executeHooks(true) as TriggerHook<Promise<void[]>>;\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFileSync } from '@dd/core/helpers/fs';\n\n// TrackedFilesMatcher can compute the list of tracked files related to a particular sourcemap.\n// The current implementation simply returns all tracked files whose filename is found inside\n// the sourcemap 'sources' field.\n// It is used so that we don't send every tracked files to the backend since most won't be of any use\n// for a particular sourcemap.\nexport class TrackedFilesMatcher {\n // A map with tracked filenames as key and the related tracked file paths as value.\n private trackedFilenames: Map<string, string[]>;\n\n constructor(trackedFiles: string[]) {\n this.trackedFilenames = new Map<string, string[]>();\n for (const f of trackedFiles) {\n const filename = this.getFilename(f);\n const list = this.trackedFilenames.get(filename);\n if (list) {\n list.push(f);\n } else {\n this.trackedFilenames.set(filename, new Array<string>(f));\n }\n }\n }\n\n private displaySource(src: string) {\n if (src.length <= 40) {\n return src;\n }\n return `[...]${src.slice(-35)}`;\n }\n\n // Looks up the sources declared in the sourcemap and return a list of related tracked files.\n public matchSourcemap(\n srcmapPath: string,\n onSourcesNotFound: (reason: string) => void,\n ): string[] | undefined {\n const buff = readFileSync(srcmapPath);\n const srcmapObj = JSON.parse(buff);\n if (!srcmapObj.sources) {\n onSourcesNotFound(`Missing 'sources' field in sourcemap.`);\n return undefined;\n }\n const sources = srcmapObj.sources as string[];\n if (sources.length === 0) {\n onSourcesNotFound(`Empty 'sources' field in sourcemap.`);\n return undefined;\n }\n const filtered = this.matchSources(sources);\n if (filtered.length === 0) {\n onSourcesNotFound(\n `${sources.map(this.displaySource).join(', ')} not in the tracked files.`,\n );\n return undefined;\n }\n\n return filtered;\n }\n\n public matchSources(sources: string[]): string[] {\n let filtered: string[] = [];\n const filenameAlreadyMatched = new Set<string>();\n for (const source of sources) {\n const filename = this.getFilename(source);\n if (filenameAlreadyMatched.has(filename)) {\n continue;\n }\n filenameAlreadyMatched.add(filename);\n const trackedFiles = this.trackedFilenames.get(filename);\n if (trackedFiles) {\n filtered = filtered.concat(trackedFiles);\n }\n }\n\n return filtered;\n }\n\n // Return a list of all tracked files\n public rawTrackedFilesList() {\n let rawList: string[] = [];\n this.trackedFilenames.forEach((value) => {\n rawList = rawList.concat(value);\n });\n\n return rawList;\n }\n\n // Extract the filename from a path.\n //\n // We are removing any suffix that is after the character '?'. The only reason this is done\n // is because we noticed that a non-negligible (~5%) amount of source paths from our customers\n // source maps contained query parameters.\n // We are assuming that the files may not actually be named with the interrogation mark but that\n // it is only an artifact of the build process. The query parameters look random. It looks\n // like it may be used as a trick to force a web browser to reload the file content.\n // The only side effect of doing that operation is that more tracked files paths may be sent\n // alongside the sourcemap which is not a problem.\n // Example: webpack:///./src/folder/ui/select.vue?821e\n private getFilename(s: string): string {\n let start = s.lastIndexOf('/');\n if (start === -1) {\n start = 0;\n } else {\n start++;\n }\n let end = s.lastIndexOf('?');\n if (end === -1 || end <= start) {\n end = s.length;\n }\n\n return s.substring(start, end);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { filterSensitiveInfoFromRepositoryUrl } from '@dd/core/helpers/strings';\nimport type { RepositoryData } from '@dd/core/types';\nimport type { SimpleGit, BranchSummary } from 'simple-git';\nimport { simpleGit } from 'simple-git';\n\nimport { TrackedFilesMatcher } from './trackedFilesMatcher';\n\n// Returns a configured SimpleGit.\nexport const newSimpleGit = async (cwd?: string): Promise<SimpleGit> => {\n const options = {\n baseDir: cwd || process.cwd(),\n binary: 'git',\n // We are invoking at most 3 git commands at the same time.\n maxConcurrentProcesses: 3,\n };\n try {\n // Attempt to set the baseDir to the root of the repository so the 'git ls-files' command\n // returns the tracked files paths relative to the root of the repository.\n const git = simpleGit(options);\n const root = await git.revparse('--show-toplevel');\n options.baseDir = root;\n } catch {\n // Ignore exception as it will fail if we are not inside a git repository.\n }\n\n return simpleGit(options);\n};\n\n// Returns the remote of the current repository.\nexport const gitRemote = async (git: SimpleGit): Promise<string> => {\n const remotes = await git.getRemotes(true);\n if (remotes.length === 0) {\n throw new Error('No git remotes available');\n }\n const defaultRemote = await getDefaultRemoteName(git);\n\n for (const remote of remotes) {\n if (remote.name === defaultRemote) {\n return filterSensitiveInfoFromRepositoryUrl(remote.refs.push);\n }\n }\n\n // Falling back to picking the first remote in the list if the default remote is not found.\n return filterSensitiveInfoFromRepositoryUrl(remotes[0].refs.push);\n};\n\nexport const getDefaultRemoteName = async (git: SimpleGit): Promise<string> => {\n try {\n return (await git.getConfig('clone.defaultRemoteName'))?.value ?? 'origin';\n } catch (e) {\n return 'origin';\n }\n};\n\n// Returns the hash of the current repository.\nexport const gitHash = async (git: SimpleGit): Promise<string> => git.revparse('HEAD');\n\n// Returns the tracked files of the current repository.\nexport const gitTrackedFiles = async (git: SimpleGit): Promise<string[]> => {\n const files = await git.raw('ls-files');\n\n return files.split(/\\r\\n|\\r|\\n/);\n};\n\nexport const gitBranch = async (git: SimpleGit): Promise<BranchSummary> => git.branch();\n\nexport const gitMessage = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%s']);\n\nexport const gitAuthorAndCommitter = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%an,%ae,%aI,%cn,%ce,%cI']);\n\nexport const gitRepositoryURL = async (git: SimpleGit): Promise<string> =>\n git.listRemote(['--get-url']);\n\n// Returns the current hash and remote as well as a TrackedFilesMatcher.\n//\n// To obtain the list of tracked files paths tied to a specific sourcemap, invoke the 'matchSourcemap' method.\nexport const getRepositoryData = async (git: SimpleGit): Promise<RepositoryData> => {\n // Invoke git commands to retrieve some informations and tracked files.\n // We're using Promise.all instead of Promise.allSettled since we want to fail early if\n // any of the promises fails.\n\n const proms: [\n ReturnType<typeof gitHash>,\n ReturnType<typeof gitBranch>,\n ReturnType<typeof gitMessage>,\n ReturnType<typeof gitAuthorAndCommitter>,\n ReturnType<typeof gitTrackedFiles>,\n ReturnType<typeof gitRemote>,\n ] = [\n gitHash(git),\n gitBranch(git),\n gitMessage(git),\n gitAuthorAndCommitter(git),\n gitTrackedFiles(git),\n gitRemote(git),\n ];\n\n const [hash, branch, message, authorAndCommitter, trackedFiles, remote] =\n await Promise.all(proms);\n\n const [authorName, authorEmail, authorDate, committerName, committerEmail, committerDate] =\n authorAndCommitter.split(',').map((item) => item.trim());\n\n const data: RepositoryData = {\n commit: {\n author: {\n name: authorName,\n email: authorEmail,\n date: authorDate,\n },\n committer: {\n name: committerName,\n email: committerEmail,\n date: committerDate,\n },\n message: message.trim(),\n hash,\n },\n hash,\n branch: branch.current,\n remote: remote.trim(),\n trackedFilesMatcher: new TrackedFilesMatcher(trackedFiles),\n };\n\n return data;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getClosest } from '@dd/core/helpers/paths';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\nimport path from 'path';\n\nimport { getRepositoryData, newSimpleGit } from './helpers';\n\nexport const PLUGIN_NAME = 'datadog-git-plugin';\n\nexport const getGitPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { options, context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const timeGit = log.time('get git information', { start: false });\n const processGit = async (gitDir: string) => {\n try {\n const repositoryData = await getRepositoryData(\n await newSimpleGit(path.dirname(gitDir!)),\n );\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\n } catch (e: any) {\n log.error(`Could not get git information: ${e.message}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n buildRoot(buildRoot) {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n timeGit.resume();\n // Add git information to the context.\n const gitDir = getClosest(buildRoot, '.git');\n if (!gitDir) {\n log.warn('No .git directory found, skipping git plugin.');\n return;\n }\n\n // buildRoot hook is sync because xpack can't make it async.\n // So we queue the async part of the plugin.\n context.queue(processGit(gitDir));\n } catch (e: any) {\n // We don't want to have the build fail for this.\n log.error(`Could not get git information: ${e.message}`);\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const PLUGIN_NAME = 'datadog-injection-plugin';\nexport const DISTANT_FILE_RX = /^https?:\\/\\//;\nexport const BEFORE_INJECTION = `// begin injection by Datadog build plugins`;\nexport const AFTER_INJECTION = `// end injection by Datadog build plugins`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { doRequest } from '@dd/core/helpers/request';\nimport { truncateString } from '@dd/core/helpers/strings';\nimport type { Logger, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\n\nimport { AFTER_INJECTION, BEFORE_INJECTION, DISTANT_FILE_RX } from './constants';\nimport type { ContentsToInject } from './types';\n\nconst MAX_TIMEOUT_IN_MS = 5000;\n\nexport const getInjectedValue = async (item: ToInjectItem): Promise<string> => {\n if (typeof item.value === 'function') {\n return item.value();\n }\n\n return item.value;\n};\n\nexport const processDistantFile = async (\n url: string,\n timeout: number = MAX_TIMEOUT_IN_MS,\n): Promise<string> => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n doRequest<string>({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url,\n }).finally(() => {\n if (timeout) {\n clearTimeout(timeoutId);\n }\n }),\n new Promise<string>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error('Timeout'));\n }, timeout);\n }),\n ]);\n};\n\nexport const processLocalFile = async (\n filepath: string,\n cwd: string = process.cwd(),\n): Promise<string> => {\n const absolutePath = getAbsolutePath(cwd, filepath);\n return readFile(absolutePath);\n};\n\nexport const processItem = async (\n item: ToInjectItem,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<string | undefined> => {\n let result: string | undefined;\n const value = await getInjectedValue(item);\n try {\n if (item.type === 'file') {\n if (value.match(DISTANT_FILE_RX)) {\n result = await processDistantFile(value);\n } else {\n result = await processLocalFile(value, cwd);\n }\n } else if (item.type === 'code') {\n // TODO: Confirm the code actually executes without errors.\n result = value;\n } else {\n throw new Error(`Invalid item type \"${item.type}\", only accepts \"code\" or \"file\".`);\n }\n } catch (error: any) {\n const itemId = `${item.type} - ${truncateString(value)}`;\n if (item.fallback) {\n // In case of any error, we'll fallback to next item in queue.\n log.info(`Fallback for \"${itemId}\": ${error.toString()}`);\n result = await processItem(item.fallback, log, cwd);\n } else {\n // Or return an empty string.\n log.warn(`Failed \"${itemId}\": ${error.toString()}`);\n }\n }\n\n return result;\n};\n\nexport const processInjections = async (\n toInject: Map<string, ToInjectItem>,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<Map<string, { position: InjectPosition; value: string }>> => {\n const toReturn: Map<string, { position: InjectPosition; value: string }> = new Map();\n\n // Processing sequentially all the items.\n for (const [id, item] of toInject.entries()) {\n // eslint-disable-next-line no-await-in-loop\n const value = await processItem(item, log, cwd);\n if (value) {\n toReturn.set(id, { value, position: item.position || InjectPosition.BEFORE });\n }\n }\n\n return toReturn;\n};\n\nexport const getContentToInject = (contentToInject: Map<string, string>) => {\n if (contentToInject.size === 0) {\n return '';\n }\n\n const stringToInject = Array.from(contentToInject.values())\n // Wrapping it in order to avoid variable name collisions.\n .map((content) => `(() => {${content}})();`)\n .join('\\n\\n');\n return `${BEFORE_INJECTION}\\n${stringToInject}\\n${AFTER_INJECTION}`;\n};\n\n// Prepare and fetch the content to inject.\nexport const addInjections = async (\n log: Logger,\n toInject: Map<string, ToInjectItem>,\n contentsToInject: ContentsToInject,\n cwd: string = process.cwd(),\n) => {\n const results = await processInjections(toInject, log, cwd);\n // Redistribute the content to inject in the right place.\n for (const [id, value] of results.entries()) {\n contentsToInject[value.position].set(id, value.value);\n }\n};\n\nexport interface NodeSystemError extends Error {\n code: string;\n}\n\nexport const isNodeSystemError = (e: unknown): e is NodeSystemError => {\n return e instanceof Error && 'code' in e;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { outputFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, PluginOptions, GlobalContext, ResolvedEntry } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, isNodeSystemError } from './helpers';\nimport type { ContentsToInject } from './types';\n\nconst fsp = fs.promises;\n\nexport const getEsbuildPlugin = (\n log: Logger,\n context: GlobalContext,\n contentsToInject: ContentsToInject,\n): PluginOptions['esbuild'] => ({\n setup(build) {\n const { onStart, onResolve, onLoad, onEnd, esbuild, initialOptions } = build;\n const entries: ResolvedEntry[] = [];\n // Use a narrower identifier to avoid cross build collisions.\n const id = context.bundler.name;\n const filePath = `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`;\n const tmpDir = fs.realpathSync(os.tmpdir());\n const absoluteFilePath = path.resolve(tmpDir, filePath);\n const injectionRx = new RegExp(`${filePath}$`);\n\n // InjectPosition.MIDDLE\n // Inject the file in the build using the \"inject\" option.\n // NOTE: This is made \"safer\" for sub-builds by actually creating the file.\n const initialInject = initialOptions.inject;\n initialOptions.inject = initialInject ? [...initialInject] : [];\n initialOptions.inject.push(absoluteFilePath);\n\n onStart(async () => {\n // Get all the entry points for later reference.\n entries.push(...(await getEsbuildEntries(build, context, log)));\n\n // Remove our injected file from the config, so we reduce our chances to leak our changes.\n build.initialOptions.inject = initialInject;\n\n try {\n // Create the MIDDLE file because esbuild will crash if it doesn't exist.\n // It seems to load entries outside of the onLoad hook once.\n await outputFile(absoluteFilePath, '');\n } catch (e: any) {\n log.error(`Could not create the files: ${e.message}`);\n }\n });\n\n onResolve(\n {\n filter: injectionRx,\n },\n async (args) => {\n // Mark the file as being injected by us.\n return { path: args.path, namespace: PLUGIN_NAME };\n },\n );\n\n onLoad(\n {\n filter: injectionRx,\n namespace: PLUGIN_NAME,\n },\n async () => {\n const content = getContentToInject(contentsToInject[InjectPosition.MIDDLE]);\n\n return {\n // We can't use an empty string otherwise esbuild will crash.\n contents: content || ' ',\n // Resolve the imports from the project's root.\n resolveDir: context.buildRoot,\n loader: 'js',\n };\n },\n );\n\n // InjectPosition.START and InjectPosition.END\n onEnd(async (result) => {\n if (!result.metafile) {\n log.warn('Missing metafile from build result.');\n return;\n }\n\n const banner = getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n const footer = getContentToInject(contentsToInject[InjectPosition.AFTER]);\n\n if (!banner && !footer) {\n // Nothing to inject.\n return;\n }\n\n // Rewrite outputs with the injected content.\n // Only keep the entry files.\n const outputs: string[] = Object.entries(result.metafile.outputs)\n .map(([p, o]) => {\n const entryPoint = o.entryPoint;\n if (!entryPoint) {\n return;\n }\n\n const entry = entries.find((e) => e.resolved.endsWith(entryPoint));\n if (!entry) {\n return;\n }\n\n return getAbsolutePath(context.buildRoot, p);\n })\n .filter(Boolean) as string[];\n\n // Write the content.\n const proms = outputs.map(async (output) => {\n try {\n const source = await fsp.readFile(output, 'utf-8');\n const data = await esbuild.transform(source, {\n loader: 'default',\n banner,\n footer,\n });\n\n // FIXME: Handle sourcemaps.\n await fsp.writeFile(output, data.code);\n } catch (e) {\n if (isNodeSystemError(e) && e.code === 'ENOENT') {\n // When we are using sub-builds, the entry file of sub-builds may not exist\n // Hence we should skip the file injection in this case.\n log.warn(`Could not inject content in ${output}: ${e}`);\n } else {\n throw e;\n }\n }\n });\n\n await Promise.all(proms);\n });\n },\n});\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\n\nimport { getContentToInject } from './helpers';\nimport type { ContentsToInject } from './types';\n\n// Use \"INJECTED_FILE\" so it get flagged by isInjectionFile().\nconst TO_INJECT_ID = INJECTED_FILE;\nconst TO_INJECT_SUFFIX = '?inject-proxy';\n\nexport const getRollupPlugin = (contentsToInject: ContentsToInject): PluginOptions['rollup'] => {\n return {\n banner(chunk) {\n if (chunk.isEntry) {\n // Can be empty.\n return getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n }\n return '';\n },\n async resolveId(source, importer, options) {\n if (isInjectionFile(source)) {\n // It is important that side effects are always respected for injections, otherwise using\n // \"treeshake.moduleSideEffects: false\" may prevent the injection from being included.\n return { id: source, moduleSideEffects: true };\n }\n if (options.isEntry && getContentToInject(contentsToInject[InjectPosition.MIDDLE])) {\n // Determine what the actual entry would have been.\n const resolution = await this.resolve(source, importer, options);\n // If it cannot be resolved or is external, just return it so that Rollup can display an error\n if (!resolution || resolution.external) {\n return resolution;\n }\n // In the load hook of the proxy, we need to know if the\n // entry has a default export. There, however, we no longer\n // have the full \"resolution\" object that may contain\n // meta-data from other plugins that is only added on first\n // load. Therefore we trigger loading here.\n const moduleInfo = await this.load(resolution);\n // We need to make sure side effects in the original entry\n // point are respected even for\n // treeshake.moduleSideEffects: false. \"moduleSideEffects\"\n // is a writable property on ModuleInfo.\n moduleInfo.moduleSideEffects = true;\n // It is important that the new entry does not start with\n // \\0 and has the same directory as the original one to not\n // mess up relative external import generation. Also\n // keeping the name and just adding a \"?query\" to the end\n // ensures that preserveModules will generate the original\n // entry name for this entry.\n return `${resolution.id}${TO_INJECT_SUFFIX}`;\n }\n return null;\n },\n load(id) {\n if (isInjectionFile(id)) {\n // Replace with injection content.\n return getContentToInject(contentsToInject[InjectPosition.MIDDLE]);\n }\n if (id.endsWith(TO_INJECT_SUFFIX)) {\n const entryId = id.slice(0, -TO_INJECT_SUFFIX.length);\n // We know ModuleInfo.hasDefaultExport is reliable because we awaited this.load in resolveId\n const info = this.getModuleInfo(entryId);\n let code = `import ${JSON.stringify(TO_INJECT_ID)};\\nexport * from ${JSON.stringify(entryId)};`;\n // Namespace reexports do not reexport default, so we need special handling here\n if (info?.hasDefaultExport) {\n code += `export { default } from ${JSON.stringify(entryId)};`;\n }\n return code;\n }\n return null;\n },\n footer(chunk) {\n if (chunk.isEntry) {\n // Can be empty.\n return getContentToInject(contentsToInject[InjectPosition.AFTER]);\n }\n return '';\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { outputFileSync, rmSync } from '@dd/core/helpers/fs';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, addInjections } from './helpers';\nimport type { ContentsToInject } from './types';\n\nexport const getXpackPlugin =\n (\n bundler: any,\n log: Logger,\n context: GlobalContext,\n toInject: Map<string, ToInjectItem>,\n contentsToInject: ContentsToInject,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n const cache = new WeakMap();\n // Use a narrower identifier to avoid cross build collisions.\n const ConcatSource = bundler.sources.ConcatSource;\n const id = context.bundler.name;\n const filePath = path.resolve(\n context.bundler.outDir,\n `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`,\n );\n\n // NOTE: RSpack MAY try to resolve the entry points before the loader is ready.\n // There must be some race condition around this, because it's not always failing.\n outputFileSync(filePath, '');\n // WARNING: Can't use shutdown.tapPromise as rspack would randomly crash the process.\n // Seems to be fixed in rspack@1.2.*\n // We also do it for webpack, as it fixes some resolution edge cases.\n const hookFn = () => {\n // Delete the file we created.\n rmSync(filePath);\n };\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n\n // Handle the InjectPosition.MIDDLE.\n type Entry = typeof compiler.options.entry;\n // TODO: Move this into @dd/core, add rspack/webpack types and tests.\n const injectEntry = (initialEntry: Entry): Entry => {\n const injectedEntry = {\n import: [filePath],\n };\n\n const objectInjection = (entry: Entry) => {\n for (const [entryKey, entryValue] of Object.entries(entry)) {\n if (typeof entryValue === 'object') {\n entryValue.import = entryValue.import || [];\n entryValue.import.unshift(filePath);\n } else if (typeof entryValue === 'string') {\n // @ts-expect-error - Badly typed for strings.\n entry[entryKey] = [filePath, entryValue];\n } else if (Array.isArray(entryValue)) {\n entryValue.unshift(filePath);\n } else {\n log.error(`Invalid entry type: ${typeof entryValue}`);\n }\n }\n };\n\n if (!initialEntry) {\n return {\n ddHelper: injectedEntry,\n };\n } else if (typeof initialEntry === 'function') {\n // @ts-expect-error - This is webpack / rspack typing conflict.\n return async () => {\n const originEntry = await initialEntry();\n objectInjection(originEntry);\n return originEntry;\n };\n } else if (typeof initialEntry === 'object') {\n objectInjection(initialEntry);\n } else if (typeof initialEntry === 'string') {\n // @ts-expect-error - Badly typed for strings.\n return [injectedEntry, initialEntry];\n } else {\n log.error(`Invalid entry type: ${typeof initialEntry}`);\n return initialEntry;\n }\n return initialEntry;\n };\n\n // We need to prepare the injections before the build starts.\n // Otherwise they'll be empty once resolved.\n compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {\n // Prepare the injections.\n await addInjections(log, toInject, contentsToInject, context.buildRoot);\n });\n\n // Handle the InjectPosition.START and InjectPosition.END.\n // This is a re-implementation of the BannerPlugin,\n // that is compatible with all versions of webpack and rspack,\n // with both banner and footer.\n compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {\n const hookCb = () => {\n const banner = getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n const footer = getContentToInject(contentsToInject[InjectPosition.AFTER]);\n\n for (const chunk of compilation.chunks) {\n if (!chunk.canBeInitial()) {\n continue;\n }\n\n for (const file of chunk.files) {\n compilation.updateAsset(file, (old) => {\n const cached = cache.get(old);\n\n // If anything changed, we need to re-create the source.\n if (!cached || cached.banner !== banner || cached.footer !== footer) {\n const source = new ConcatSource(banner, '\\n', old, '\\n', footer);\n\n // Cache the result.\n cache.set(old, { source, banner, footer });\n return source;\n }\n\n return cached.source;\n });\n }\n }\n };\n\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n });\n\n // We inject the new entry.\n const newEntry = injectEntry(compiler.options.entry);\n compiler.options.entry = newEntry;\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE_RX } from '@dd/core/constants';\nimport { isXpack } from '@dd/core/helpers/bundlers';\nimport { getUniqueId } from '@dd/core/helpers/strings';\nimport {\n InjectPosition,\n type GetInternalPlugins,\n type GetPluginsArg,\n type PluginOptions,\n type ToInjectItem,\n} from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getEsbuildPlugin } from './esbuild';\nimport { addInjections, getContentToInject } from './helpers';\nimport { getRollupPlugin } from './rollup';\nimport type { ContentsToInject } from './types';\nimport { getXpackPlugin } from './xpack';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getInjectionPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { bundler, context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n // Storage for all the injections.\n const injections: Map<string, ToInjectItem> = new Map();\n\n // Storage for all the positional contents we want to inject.\n const contentsToInject: ContentsToInject = {\n [InjectPosition.BEFORE]: new Map(),\n [InjectPosition.MIDDLE]: new Map(),\n [InjectPosition.AFTER]: new Map(),\n };\n\n context.inject = (item: ToInjectItem) => {\n injections.set(getUniqueId(), item);\n };\n\n const plugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'post',\n // Bundler specific part of the plugin.\n // We use it to:\n // - Inject the content in the right places, each bundler offers this differently.\n esbuild: getEsbuildPlugin(log, context, contentsToInject),\n webpack: getXpackPlugin(bundler, log, context, injections, contentsToInject),\n rspack: getXpackPlugin(bundler, log, context, injections, contentsToInject),\n rollup: getRollupPlugin(contentsToInject),\n vite: { ...(getRollupPlugin(contentsToInject) as PluginOptions['vite']), enforce: 'pre' },\n };\n\n // We need to handle the resolution in xpack,\n // and it's easier to use unplugin's hooks for it.\n if (isXpack(context.bundler.name)) {\n plugin.load = {\n filter: {\n id: INJECTED_FILE_RX,\n },\n handler() {\n return {\n code: getContentToInject(contentsToInject[InjectPosition.MIDDLE]),\n };\n },\n };\n } else {\n // In xpack, we need to prepare the injections BEFORE the build starts.\n // Otherwise, the bundler doesn't have the content when it needs it.\n // So we do it in their specific plugin.\n // Here for all the other non-xpack bundlers.\n plugin.buildStart = async () => {\n // Prepare the injections.\n await addInjections(log, injections, contentsToInject, context.buildRoot);\n };\n }\n\n return [plugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions, PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-true-end-plugin' as const;\n\nexport const getTrueEndPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const asyncHookFn = async () => {\n await context.asyncHook('asyncTrueEnd');\n };\n const syncHookFn = () => {\n context.hook('syncTrueEnd');\n };\n const bothHookFns = async () => {\n syncHookFn();\n await asyncHookFn();\n };\n\n const xpackPlugin: PluginOptions['rspack'] & PluginOptions['webpack'] = (compiler) => {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n };\n\n const rollupPlugin: PluginOptions['rollup'] & PluginOptions['vite'] = {\n async writeBundle() {\n // TODO: Need to fallback here in case the closeBundle isn't called.\n },\n async closeBundle() {\n await bothHookFns();\n },\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n webpack: xpackPlugin,\n esbuild: {\n setup(build) {\n // NOTE: \"onEnd\" is the best we can do for esbuild, but it's very far from being the \"true end\" of the build.\n build.onEnd(async () => {\n await asyncHookFn();\n });\n // NOTE: \"onDispose\" is strictly synchronous.\n build.onDispose(() => {\n syncHookFn();\n });\n },\n },\n vite: rollupPlugin,\n rollup: rollupPlugin,\n rspack: xpackPlugin,\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n/* eslint-disable arca/import-ordering, arca/newline-after-import-section */\n// This file is mostly generated.\n// Anything between\n// - #imports-injection-marker\n// - #types-export-injection-marker\n// - #internal-plugins-injection-marker\n// - #helpers-injection-marker\n// - #configs-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type {\n BundlerName,\n Env,\n FactoryMeta,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPlugins,\n GlobalContext,\n GlobalData,\n GlobalStores,\n Options,\n OptionsWithDefaults,\n} from '@dd/core/types';\nimport type { UnpluginContextMeta, UnpluginInstance } from 'unplugin';\nimport { createUnplugin } from 'unplugin';\nimport chalk from 'chalk';\n\nimport { validateOptions } from './validate';\nimport { getContext } from './helpers/context';\nimport { wrapGetPlugins } from './helpers/wrapPlugins';\nimport { ALL_ENVS, HOST_NAME } from '@dd/core/constants';\n// #imports-injection-marker\nimport * as errorTracking from '@dd/error-tracking-plugin';\nimport * as metrics from '@dd/metrics-plugin';\nimport * as output from '@dd/output-plugin';\nimport * as rum from '@dd/rum-plugin';\nimport { getAnalyticsPlugins } from '@dd/internal-analytics-plugin';\nimport { getAsyncQueuePlugins } from '@dd/internal-async-queue-plugin';\nimport { getBuildReportPlugins } from '@dd/internal-build-report-plugin';\nimport { getBundlerReportPlugins } from '@dd/internal-bundler-report-plugin';\nimport { getCustomHooksPlugins } from '@dd/internal-custom-hooks-plugin';\nimport { getGitPlugins } from '@dd/internal-git-plugin';\nimport { getInjectionPlugins } from '@dd/internal-injection-plugin';\nimport { getTrueEndPlugins } from '@dd/internal-true-end-plugin';\n// #imports-injection-marker\n// #types-export-injection-marker\nexport type { types as ErrorTrackingTypes } from '@dd/error-tracking-plugin';\nexport type { types as MetricsTypes } from '@dd/metrics-plugin';\nexport type { types as OutputTypes } from '@dd/output-plugin';\nexport type { types as RumTypes } from '@dd/rum-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [metrics.CONFIG_KEY]: metrics.helpers,\n // #helpers-injection-marker\n};\n\nexport const buildPluginFactory = ({\n bundler,\n version,\n}: FactoryMeta): UnpluginInstance<Options, true> => {\n const start = Date.now();\n return createUnplugin((opts: Options, unpluginMetaContext: UnpluginContextMeta) => {\n // TODO: Implement config overrides with environment variables.\n // TODO: Validate API Key and endpoint.\n // TODO: Inject a metric logger into the global context.\n\n const options: OptionsWithDefaults = validateOptions(opts);\n\n // Set the host name for the esbuild plugin.\n if (unpluginMetaContext.framework === 'esbuild') {\n unpluginMetaContext.esbuildHostName = HOST_NAME;\n }\n\n // Use \"production\" if there is no env passed.\n const passedEnv: Env = (process.env.BUILD_PLUGINS_ENV as Env) || 'production';\n // Fallback to \"development\" if the passed env is wrong.\n const env = ALL_ENVS.includes(passedEnv) ? passedEnv : 'development';\n // We need to account for how each bundler exposes its version.\n // - (webpack|esbuild|vite).version\n // - rollup.VERSION\n // - rspack.rspackVersion\n const bundlerVersion = bundler.rspackVersion || bundler.version || bundler.VERSION;\n const bundlerName = unpluginMetaContext.framework as BundlerName;\n\n const data: GlobalData = {\n bundler: {\n name: bundlerName,\n version: bundlerVersion,\n },\n env,\n metadata: options.metadata || {},\n packageName: `@datadog/${bundlerName}-plugin`,\n version,\n };\n\n const stores: GlobalStores = {\n errors: [],\n logs: [],\n queue: [],\n timings: [],\n warnings: [],\n };\n\n // Create the global context.\n const context: GlobalContext = getContext({\n start,\n options,\n data,\n stores,\n });\n\n const log = context.getLogger('factory');\n const timeInit = log.time('Plugins initialization', { start });\n\n context.pluginNames.push(HOST_NAME);\n\n const pluginsToAdd: [name: string, GetPlugins | GetCustomPlugins | GetInternalPlugins][] =\n [];\n\n // List of plugins to be returned.\n // We keep the UnpluginOptions type for the custom plugins.\n pluginsToAdd.push(\n // Prefill with our internal plugins.\n // #internal-plugins-injection-marker\n ['analytics', getAnalyticsPlugins],\n ['async-queue', getAsyncQueuePlugins],\n ['build-report', getBuildReportPlugins],\n ['bundler-report', getBundlerReportPlugins],\n ['custom-hooks', getCustomHooksPlugins],\n ['git', getGitPlugins],\n ['injection', getInjectionPlugins],\n ['true-end', getTrueEndPlugins],\n // #internal-plugins-injection-marker\n );\n\n // Add custom, on the fly plugins, if any.\n if (options.customPlugins) {\n pluginsToAdd.push(['custom', options.customPlugins]);\n }\n\n // Add the customer facing plugins.\n pluginsToAdd.push(\n // #configs-injection-marker\n ['error-tracking', errorTracking.getPlugins],\n ['metrics', metrics.getPlugins],\n ['output', output.getPlugins],\n ['rum', rum.getPlugins],\n // #configs-injection-marker\n );\n\n // Initialize all our plugins.\n for (const [name, getPlugins] of pluginsToAdd) {\n context.plugins.push(\n ...wrapGetPlugins(\n context,\n getPlugins,\n name,\n )({\n bundler,\n context,\n options,\n data,\n stores,\n }),\n );\n }\n\n // List all our plugins in the context.\n context.pluginNames.push(...context.plugins.map((plugin) => plugin.name));\n\n // Verify we don't have plugins with the same name, as they would override each other.\n const duplicates = new Set(\n context.pluginNames.filter(\n (name) => context.pluginNames.filter((n) => n === name).length > 1,\n ),\n );\n if (duplicates.size > 0) {\n throw new Error(\n `Duplicate plugin names: ${chalk.bold.red(Array.from(duplicates).join(', '))}`,\n );\n }\n\n context.hook('init', context);\n timeInit.end();\n\n return context.plugins;\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// This file is partially generated.\n// Anything between #types-export-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type { Options } from '@dd/core/types';\nimport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport * as vite from 'vite';\n\nimport pkg from '../package.json';\n\nexport type VitePluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogVitePlugin = factory.buildPluginFactory({\n bundler: vite,\n version: pkg.version,\n}).vite;\n\nexport const version = pkg.version;\nexport const helpers = factory.helpers;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport type {\n BuildReport,\n GlobalContext,\n GlobalData,\n GlobalStores,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nimport { getLoggerFactory } from './logger';\n\nexport const getContext = ({\n start,\n options,\n data,\n stores,\n}: {\n start: number;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n}): GlobalContext => {\n const buildRoot = process.cwd();\n const build: BuildReport = {\n errors: stores.errors,\n warnings: stores.warnings,\n logs: stores.logs,\n metadata: data.metadata,\n timings: stores.timings,\n bundler: data.bundler,\n };\n const context: GlobalContext = {\n auth: options.auth,\n pluginNames: [],\n bundler: {\n ...build.bundler,\n // This will be updated in the bundler-report plugin once we have the configuration.\n outDir: buildRoot,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n buildRoot,\n env: data.env,\n getLogger: getLoggerFactory(data, stores, options.logLevel),\n // This will be updated in the injection plugin on initialization.\n asyncHook: () => {\n throw new Error('AsyncHook function called before it was initialized.');\n },\n hook: () => {\n throw new Error('Hook function called before it was initialized.');\n },\n // This will be updated in the injection plugin on initialization.\n inject: () => {\n throw new Error('Inject function called before it was initialized.');\n },\n plugins: [],\n // This will be updated in the async-queue plugin on initialization.\n queue: () => {\n throw new Error('Queue function called before it was initialized.');\n },\n sendLog: getSendLog(data),\n start,\n version: data.version,\n };\n\n return context;\n};\n"],"names":["getEnvValue","key","process","env","INJECTED_FILE","INJECTED_FILE_RX","RegExp","ALL_ENVS","HOST_NAME","ERROR_CODES_NO_RETRY","doRequest","opts","auth","url","method","getData","type","retryOpts","retries","onRetry","maxTimeout","minTimeout","retry","async","bail","attempt","response","requestInit","duplex","requestHeaders","apiKey","appKey","data","headers","body","fetch","error","ok","errorMessage","status","statusText","includes","Error","result","json","text","getSendLog","message","context","payload","ddsource","packageName","service","team","version","bundler","name","metadata","JSON","stringify","cleanPluginName","replace","isInjectionFile","filename","serializeBuildReport","report","jsonReport","errors","warnings","logs","timings","start","end","duration","writeDuration","entries","inputs","outputs","entry","newEntry","map","file","filepath","push","input","newInput","dependencies","dependents","dependency","dependent","output","newOutput","shouldGetGitInfo","options","gitEnabledFromSourcemaps","errorTracking","sourcemaps","gitEnabledFromRoot","enableGit","formatDuration","days","Math","floor","d","Date","hours","getUTCHours","minutes","getUTCMinutes","seconds","getUTCSeconds","milliseconds","getUTCMilliseconds","timeString","trim","truncateString","str","maxLength","placeholder","length","stringLength","max","leftStop","min","rightStop","slice","filterSensitiveInfoFromRepositoryUrl","repositoryUrl","startsWith","URL","cleanPath","pathname","protocol","host","index","logPriority","debug","info","warn","none","cleanName","split","join","getLogFn","stores","logLevel","cleanedName","forward","color","c","dim","logFn","console","log","red","yellow","cyan","prefix","content","pluginName","time","now","forwardLog","sendLog","plugin","e","subLogger","queue","getTimeLogger","store","label","level","toLog","tags","timer","spans","total","getUncompleteSpans","filter","span","resume","startTime","pause","pauseTime","uncompleteSpans","param","endTime","reduce","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","getLoggerFactory","getLogger","subName","logger","HOOKS_TO_TRACE","wrapHook","hookName","hook","wrapWithTiming","fn","args","apply","this","Promise","finally","handler","wrapGetPlugins","getPlugins","arg","initTimer","wrappedPlugins","wrappedPlugin","wrapPlugin","pluginNames","CONFIG_KEY","PLUGIN_NAME","decomposePath","absoluteOutDir","sourcemapFilePath","path","extname","chalk","green","bold","minifiedFilePath","relativePath","relative","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","mkdir","dir","fsp","recursive","outputFileSync","dirname","fs","mkdirSync","writeFileSync","encoding","existsSync","code","getFile","openAsBlob","blob","contentType","File","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","pathParts","prefixParts","normalizedPath","i","partialPrefix","getPayload","sourcemap","git","resultMinFile","resultSourcemap","all","repeatedPrefix","getSourcemapValidity","Map","value","minified_url","set","files","trackedFilesMatcher","matchSourcemap","reason","basename","hash","repository_url","remote","defaultHeaders","form","FormData","gz","createGzip","Blob","append","req","Request","fromWeb","pipe","Object","fromEntries","sendSourcemaps","minifiedPathPrefix","git_repository_url","git_commit_sha","plugin_version","project_path","outDir","releaseVersion","payloads","flat","errorMsg","bailOnError","uploadErrors","uploadWarnings","PQueue","default","concurrency","maxConcurrency","bundlerName","addPromises","get","add","site","DATADOG_SOURCEMAP_INTAKE_URL","warningMessage","onIdle","upload","toString","fileMetadata","uploadSourcemaps","configurationString","sourcemapsTime","endsWith","getSourcemapsFiles","summary","outdent","sendTime","validateSourcemapsOptions","config","validatedOptions","toReturn","validateMinifiedPathPrefix","sourcemapsWithDefaults","dryRun","timeOptions","sourcemapsResults","enable","validateOptions","gitInfo","buildReport","handleSourcemaps","totalTime","enforce","repoData","defaultFilters","metric","test","some","thresholds","count","points","accumulator","currentPoint","getTimestamp","timestamp","getMetric","defaultTags","formatCwd","cwd","getDisplayName","pop","formatModuleName","getModuleName","module","compilation","userRequest","issuer","moduleGraph","getIssuer","_identifier","getModulePath","formatLoaderName","loader","getValueContext","constructor","numColor","nameColor","sortDesc","attr","a","b","aVal","bVal","getTimingValues","times","Array","from","values","sort","durationsToPrint","top","increment","outputTexts","globalContext","valuesToPrint","loaders","tapables","modules","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","Set","serializedReport","build","fileDependencies","fileDependents","dependenciesSet","dependentsSet","dep","has","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","prettyBytes","getModulesValues","nbModules","nbAssets","nbWarnings","nbErrors","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","flatMap","v","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","FN_TO_WRAP","loadersMap","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","cb","pluginTiming","events","isLoader","initialFunction","modulePath","moduleTiming","performance","statsObject","loaderTiming","getEsbuildPlugin","setup","initialOptions","metafile","timeWrap","plugins","initialPlugins","oldSetup","esbuild","wrapPlugins","buildRoot","onEnd","timeResult","asyncHook","Loaders","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","current","getPromiseTapPatch","checkNewHooks","returnValue","then","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","scope","call","newFn","replaceTaps","tap","tapAsync","tapPromise","patchHook","_fakeHook","patchHooks","hooksToPatch","keys","throughHooks","getWebpackPlugin","compiler","HOOK_OPTIONS","compilerTime","thisCompilation","compilationTime","buildModule","succeedModule","failedModule","afterEmit","tapableTimings","loadersTimings","modulesTimings","helpers","filters","realBuildEnd","enableDefaultPrefix","enableTracing","toLowerCase","legacyPlugin","webpack","rspack","timeBuild","needLegacyPlugin","timingsReport","computeMetrics","timeMetrics","universalMetrics","metrics","entriesPerInput","assetsPerInput","entriesPerAsset","cleanAssetName","entryName","assetName","getUniversalMetrics","pluginMetrics","pluginDuration","pluginCount","hookDuration","getPluginMetrics","loaderMetrics","getLoaderMetrics","metricsToSend","processedMetrics","toSend","m","getMetricsToSend","timeReport","timeSend","metricIterations","metricsNames","nameA","nameB","localeCompare","series","catch","sendMetrics","universalPlugin","buildStart","buildEnd","sanitizeOutputPath","validateFilesOptions","defaultValue","getXpackPlugin","write","done","stats","statsTimer","statsJson","toJson","assets","children","chunks","chunkGroupAuxiliary","chunkGroupChildren","chunkGroups","chunkRelations","entrypoints","ids","nestedModules","relatedAssets","reasons","chunkModules","getRollupPlugin","clear","writeBundle","bundle","closeBundle","writeFile","fileValue","timeWrite","pathOption","outputPath","isAbsolute","resolve","getFilePath","dataToWrite","writable","createWriteStream","readable","JsonStreamStringify","prom","reject","on","err","outputJson","queuedWrite","timeSerialization","getStats","rollup","getOutputs","vite","InjectPosition","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","attributes","client_token","validateSDKOptions","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacy","privacyWithDefault","exclude","include","addToDictionaryFunctionName","helperCodeExpression","sdkResults","privacyResults","_","inject","position","MIDDLE","__dirname","BEFORE","privacyPlugin","pluginOptions","transformOptions","addToDictionaryHelper","expression","inlineSourceMap","embedCodeInSourceMap","buildTransformOptions","transform","id","instrument","getPrivacyPlugin","getAnalyticsPlugins","buildStartFn","getAsyncQueuePlugins","promise","wrappedPromise","asyncTrueEnd","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","isArray","fullPath","in","proms","getAllEntryFiles","glob","sync","p","kind","resolveDir","resolved","original","resolutionError","getAbsolutePath","getNearestCommonDirectory","dirs","splitPaths","sep","minLength","parts","commonParts","component","every","EXTENSION_RX","QUERY_RX","getType","lastIndex","exec","BUNDLER_SPECIFICS","cleanReport","cleanedReport","reportFilepath","cleanedPath","shift","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","obj","entryNames","resolvedEntries","timeBuildReport","onStart","timeEntries","timeCollect","warning","tempEntryFiles","tempSourcemaps","reportInputsIndexed","reportOutputsIndexed","timeIndex","metaInputsIndexed","metaOutputsIndexed","getRealPathFromInjectionProxy","entryPoint","metaInput","actualImport","imports","find","imp","timeInputs","bytes","timeOutputs","inputFiles","inputName","inputFound","inputFile","timeSourcemaps","foundOutput","references","meta","FILE_EXCEPTIONS_RX","isFileSupported","match","getAllImports","ref","allImports","metaFile","imported","isRelative","root","absoluteImportPath","external","entryFile","entryInputs","entryOutputs","outputFile","timeDeps","absoluteDependencyPath","dependencyFile","timeModuleParsing","timeInputsOutputs","timeCompleteDeps","importsReport","onLog","logItem","renderError","moduleParsed","cleanId","newDependencies","dynamicallyImportedIds","importedIds","newDependents","dynamicImporters","importers","tempOutputsImports","cleanedDependency","cleanedDependent","asset","Buffer","byteLength","source","modulepath","moduleFile","originalLength","importName","cleanedImport","importFile","isEntry","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","modulesPerFile","moduleIndex","tempDeps","isModuleSupported","moduleIdentifier","cleanExternalName","indexModule","mod","moduleToIndex","identifier","blocks","externalType","createIndexedModule","keysToIndex","indexes","keysOfModuleToIndexOn","indexValue","valueToIndex","getKeysToIndex","previousModule","getAllDependencies","block","getModuleFromDep","request","cleanRequest","isExternal","finishModules","finishedModules","timeGraph","Boolean","moduleDeps","depIdentifier","depDeps","timeAssign","depsReport","depInput","getAssets","getChunkFiles","chunk","auxiliaryFiles","f","timeChunks","chunkGraph","getChunkModules","m2","fileModules","outputFound","entrypoint","entryFiles","entryFilename","getChunkEntryModulesIterable","getBuildReportPlugins","getAbsoluteOutDir","getOutDirsFromOutputs","outputOptions","o","xpackPlugin","rawConfig","vitePlugin","configResolved","rollupOptions","outDirs","getBundlerReportPlugins","absWorkingDir","outdir","outfile","inDirs","normalizedInput","getIndirsFromInputs","computedCwd","renderStart","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","TrackedFilesMatcher","trackedFiles","trackedFilenames","getFilename","list","displaySource","src","srcmapPath","onSourcesNotFound","buff","readFileSync","srcmapObj","parse","sources","filtered","matchSources","filenameAlreadyMatched","concat","rawTrackedFilesList","rawList","forEach","s","lastIndexOf","substring","gitRemote","remotes","getRemotes","defaultRemote","getDefaultRemoteName","refs","getConfig","gitHash","revparse","gitTrackedFiles","raw","gitBranch","branch","gitMessage","show","gitAuthorAndCommitter","getGitPlugins","timeGit","processGit","gitDir","repositoryData","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","item","commit","author","email","date","committer","getRepositoryData","baseDir","binary","maxConcurrentProcesses","simpleGit","newSimpleGit","currentDir","closest","getClosest","DISTANT_FILE_RX","processLocalFile","readFile","processItem","getInjectedValue","timeout","timeoutId","race","clearTimeout","setTimeout","processDistantFile","itemId","fallback","getContentToInject","contentToInject","addInjections","toInject","contentsToInject","results","processInjections","promises","onResolve","onLoad","tmpDir","realpathSync","os","tmpdir","absoluteFilePath","injectionRx","initialInject","namespace","contents","banner","footer","AFTER","isNodeSystemError","TO_INJECT_ID","TO_INJECT_SUFFIX","resolveId","importer","moduleSideEffects","resolution","load","entryId","getModuleInfo","hasDefaultExport","cache","WeakMap","ConcatSource","shutdown","rmSync","force","maxRetries","beforeRun","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","processAssets","canBeInitial","updateAsset","old","cached","initialEntry","injectedEntry","import","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","getTrueEndPlugins","asyncHookFn","syncHookFn","bothHookFns","rollupPlugin","onDispose","CONFIG_KEY$2","metrics.CONFIG_KEY","metrics.helpers","datadogVitePlugin","createUnplugin","unpluginMetaContext","defineProperty","enumerable","framework","esbuildHostName","passedEnv","BUILD_PLUGINS_ENV","bundlerVersion","rspackVersion","VERSION","getContext","timeInit","pluginsToAdd","customPlugins","errorTracking.getPlugins","metrics.getPlugins","output.getPlugins","rum.getPlugins","duplicates","n","factory.buildPluginFactory","pkg","factory.helpers"],"mappings":"2sBAMA,MAAMA,EAAeC,GACVC,QAAQC,IAAI,WAAWF,MAAUC,QAAQC,IAAI,MAAMF,KCHjDG,EAAgB,wBAChBC,EAAmB,IAAIC,OAAOF,GAE9BG,EAAW,CAAC,cAAe,aAAc,QAKzCC,EAAY,wBCHZC,EAAuB,CAAC,IAAK,IAAK,KAGlCC,EAAgBC,IACzB,MAAMC,KAAEA,MAAMC,EAAAC,O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C,WAAYE,KAKb97B,EAAQs9B,eACRD,EAAa/9B,KAAK,CAAC,SAAUU,EAAQs9B,gBAIzCD,EAAa/9B,KAET,CAAC,iBAAkBi+B,IACnB,CAAC,UAAWC,IACZ,CAAC,SAAUC,IACX,CAAC,MAAOC,KAKZ,IAAA,MAAY//B,EAAM0J,KAAeg2B,EAC7BlgC,EAAQ2a,QAAQxY,QACT8H,EACCjK,EACAkK,EACA1J,EAHDyJ,CAID,CACE1J,UACAP,UACA6C,UACA7D,OACAgH,YAMZhG,EAAQwK,YAAYrI,QAAQnC,EAAQ2a,QAAQ3Y,KAAKoF,GAAWA,EAAO5G,QAGnE,MAAMggC,EAAa,IAAIvpB,IACnBjX,EAAQwK,YAAYtC,QACf1H,GAASR,EAAQwK,YAAYtC,QAAQu4B,GAAMA,IAAMjgC,IAAM+D,OAAS,KAGzE,GAAIi8B,EAAWlzB,KAAO,EAClB,MAAM,IAAI5N,MACN,2BAA2BsL,EAAME,KAAKxE,IAAIsP,MAAMC,KAAKuqB,GAAY16B,KAAK,UAO9E,OAHA9F,EAAQwJ,KAAK,OAAQxJ,GACrBigC,EAASz+B,MAEFxB,EAAQ2a,OAAA,GAClB,ECjK4B+lB,CAA2B,CACxDngC,QAAS0kB,EACT3kB,QAASqgC,KACV1b,KAEU3kB,GAAUqgC,GACV7hB,GAAU8hB"}
1
+ {"version":3,"file":"index.js","sources":["../../../../factory/src/validate.ts","../../../../core/src/constants.ts","../../../../core/src/helpers/request.ts","../../../../core/src/helpers/log.ts","../../../../core/src/helpers/plugins.ts","../../../../core/src/helpers/strings.ts","../../../../factory/src/helpers/logger.ts","../../../../factory/src/helpers/wrapPlugins.ts","../../../../plugins/error-tracking/src/constants.ts","../../../../plugins/error-tracking/src/sourcemaps/files.ts","../../../../core/src/helpers/fs.ts","../../../../plugins/error-tracking/src/sourcemaps/payload.ts","../../../../plugins/error-tracking/src/sourcemaps/sender.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts","../../../../plugins/error-tracking/src/validate.ts","../../../../plugins/error-tracking/src/index.ts","../../../../plugins/metrics/src/common/filters.ts","../../../../plugins/metrics/src/constants.ts","../../../../plugins/metrics/src/common/helpers.ts","../../../../plugins/metrics/src/common/output/text.ts","../../../../plugins/metrics/src/esbuild-plugin/plugins.ts","../../../../plugins/metrics/src/esbuild-plugin/index.ts","../../../../plugins/metrics/src/webpack-plugin/loaders.ts","../../../../plugins/metrics/src/webpack-plugin/tapables.ts","../../../../plugins/metrics/src/webpack-plugin/index.ts","../../../../plugins/metrics/src/index.ts","../../../../plugins/metrics/src/common/aggregator.ts","../../../../plugins/metrics/src/common/sender.ts","../../../../plugins/output/src/constants.ts","../../../../plugins/output/src/validate.ts","../../../../plugins/output/src/index.ts","../../../../core/src/types.ts","../../../../plugins/rum/src/constants.ts","../../../../plugins/rum/src/privacy/constants.ts","../../../../plugins/rum/src/privacy/index.ts","../../../../plugins/rum/src/sdk.ts","../../../../plugins/rum/src/validate.ts","../../../../plugins/rum/src/index.ts","../../../../plugins/rum/src/privacy/transform.ts","../../../../plugins/analytics/src/constants.ts","../../../../plugins/analytics/src/index.ts","../../../../plugins/async-queue/src/constants.ts","../../../../plugins/async-queue/src/index.ts","../../../../core/src/helpers/bundlers.ts","../../../../core/src/helpers/paths.ts","../../../../plugins/build-report/src/helpers.ts","../../../../plugins/build-report/src/esbuild.ts","../../../../plugins/build-report/src/rollup.ts","../../../../plugins/build-report/src/xpack.ts","../../../../plugins/build-report/src/index.ts","../../../../plugins/bundler-report/src/index.ts","../../../../plugins/custom-hooks/src/constants.ts","../../../../plugins/custom-hooks/src/index.ts","../../../../plugins/git/src/trackedFilesMatcher.ts","../../../../plugins/git/src/helpers.ts","../../../../plugins/git/src/index.ts","../../../../plugins/injection/src/constants.ts","../../../../plugins/injection/src/helpers.ts","../../../../plugins/injection/src/esbuild.ts","../../../../plugins/injection/src/rollup.ts","../../../../plugins/injection/src/xpack.ts","../../../../plugins/injection/src/index.ts","../../../../plugins/true-end/src/index.ts","../../../../factory/src/index.ts","../../src/index.ts","../../../../factory/src/helpers/context.ts"],"sourcesContent":["// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { AuthOptionsWithDefaults, Options, OptionsWithDefaults } from '@dd/core/types';\n\nconst getEnvValue = (key: string) => {\n return process.env[`DATADOG_${key}`] || process.env[`DD_${key}`];\n};\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n const auth: AuthOptionsWithDefaults = {\n // DATADOG_SITE env var takes precedence over configuration\n site: getEnvValue('SITE') || options.auth?.site || 'datadoghq.com',\n };\n\n // Prevent these from being accidentally logged.\n Object.defineProperty(auth, 'apiKey', {\n value: getEnvValue('API_KEY') || options.auth?.apiKey,\n enumerable: false,\n });\n\n Object.defineProperty(auth, 'appKey', {\n value: getEnvValue('APP_KEY') || options.auth?.appKey,\n enumerable: false,\n });\n\n return {\n enableGit: true,\n logLevel: 'warn',\n metadata: {},\n ...options,\n auth,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const INJECTED_FILE = '__datadog-helper-file';\nexport const INJECTED_FILE_RX = new RegExp(INJECTED_FILE);\n\nexport const ALL_ENVS = ['development', 'production', 'test'] as const;\nexport const ALL_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack', 'rolldown', 'farm'];\nexport const SUPPORTED_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack'] as const;\nexport const ENV_VAR_REQUESTED_BUNDLERS = 'PLAYWRIGHT_REQUESTED_BUNDLERS';\n\nexport const HOST_NAME = 'datadog-build-plugins';\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport retry from 'async-retry';\nimport type { RequestInit } from 'undici-types';\n\nimport type { RequestOpts } from '../types';\n\nexport const ERROR_CODES_NO_RETRY = [400, 403, 413];\nexport const NB_RETRIES = 5;\n// Do a retriable fetch.\nexport const doRequest = <T>(opts: RequestOpts): Promise<T> => {\n const { auth, url, method = 'GET', getData, type = 'text' } = opts;\n const retryOpts: retry.Options = {\n retries: opts.retries === 0 ? 0 : opts.retries || NB_RETRIES,\n onRetry: opts.onRetry,\n maxTimeout: opts.maxTimeout,\n minTimeout: opts.minTimeout,\n };\n\n return retry(async (bail: (e: Error) => void, attempt: number) => {\n let response: Response;\n try {\n const requestInit: RequestInit = {\n method,\n // This is needed for sending body in NodeJS' Fetch.\n // https://github.com/nodejs/node/issues/46221\n duplex: 'half',\n };\n let requestHeaders: RequestInit['headers'] = {\n 'X-Datadog-Origin': 'build-plugins',\n };\n\n // Do auth if present.\n if (auth?.apiKey) {\n requestHeaders['DD-API-KEY'] = auth.apiKey;\n }\n\n if (auth?.appKey) {\n requestHeaders['DD-APPLICATION-KEY'] = auth.appKey;\n }\n\n if (typeof getData === 'function') {\n const { data, headers } = await getData();\n requestInit.body = data;\n requestHeaders = { ...requestHeaders, ...headers };\n }\n\n response = await fetch(url, { ...requestInit, headers: requestHeaders });\n } catch (error: any) {\n // We don't want to retry if there is a non-fetch related error.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n\n if (!response.ok) {\n // Not instantiating the error here, as it will make Jest throw in the tests.\n const errorMessage = `HTTP ${response.status} ${response.statusText}`;\n if (ERROR_CODES_NO_RETRY.includes(response.status)) {\n bail(new Error(errorMessage));\n // bail(error) throws so the return is never executed.\n return {} as T;\n } else {\n // Trigger the retry.\n throw new Error(errorMessage);\n }\n }\n\n try {\n let result;\n // Await it so we catch any parsing error and bail.\n if (type === 'json') {\n result = await response.json();\n } else {\n result = await response.text();\n }\n\n return result as T;\n } catch (error: any) {\n // We don't want to retry on parsing errors.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n }, retryOpts);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '../constants';\nimport type { GlobalData, DdLogOptions } from '../types';\n\nimport { doRequest } from './request';\n\nexport const INTAKE_PATH = 'v1/input/pub44d5f4eb86e1392037b7501f7adc540e';\nexport const INTAKE_HOST = 'browser-http-intake.logs.datadoghq.com';\n\nexport const getSendLog =\n (data: GlobalData) =>\n ({ message, context }: DdLogOptions): Promise<void> => {\n return doRequest({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url: `https://${INTAKE_HOST}/${INTAKE_PATH}`,\n method: 'POST',\n type: 'json',\n getData: async () => {\n const payload = {\n ddsource: data.packageName || HOST_NAME,\n message,\n service: 'build-plugins',\n team: 'language-foundations',\n env: data.env,\n version: data.version,\n bundler: {\n name: data.bundler.name,\n version: data.bundler.version,\n },\n metadata: data.metadata,\n ...context,\n };\n return {\n data: JSON.stringify(payload),\n headers: {\n 'Content-Type': 'application/json',\n },\n };\n },\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n Input,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\n\nexport const cleanPluginName = (name: string) => {\n // Will remove the \"@dd/\", \"@dd/datadog-\", \"@dd/internal-\", \"datadog-\" prefixes and the \"-plugin\" suffix.\n return name.replace(/^@dd\\/(datadog-|internal-)?|^datadog-|-plugin$/g, '');\n};\n\n// Is the file coming from the injection plugin?\nexport const isInjectionFile = (filename: string) => filename.includes(INJECTED_FILE);\n\n// Returns an object that is safe to serialize to JSON.\n// Mostly useful for debugging and testing.\nexport const serializeBuildReport = (report: BuildReport): SerializedBuildReport => {\n // Report is an object that self reference some of its values.\n // To make it JSON serializable, we need to remove the self references\n // and replace them with strings, we'll use \"filepath\" to still have them uniquely identifiable.\n const jsonReport: SerializedBuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n entries: [],\n inputs: [],\n outputs: [],\n };\n\n for (const entry of report.entries || []) {\n const newEntry: SerializedEntry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs.map((file: FileReport) => file.filepath);\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.entries.push(newEntry);\n }\n\n for (const input of report.inputs || []) {\n const newInput: SerializedInput = { ...input, dependencies: [], dependents: [] };\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n newInput.dependencies.push(dependency.filepath);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n newInput.dependents.push(dependent.filepath);\n }\n }\n jsonReport.inputs.push(newInput);\n }\n\n for (const output of report.outputs || []) {\n const newOutput: SerializedOutput = { ...output, inputs: [] };\n if (output.inputs) {\n newOutput.inputs = output.inputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.outputs.push(newOutput);\n }\n\n return jsonReport;\n};\n\n// Returns an object that is unserialized from serializeBuildReport().\n// Mostly useful for debugging and testing.\nexport const unserializeBuildReport = (report: SerializedBuildReport): BuildReport => {\n const buildReport: BuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n };\n\n const reportInputs = report.inputs || [];\n const reportOutputs = report.outputs || [];\n\n const entries: Entry[] = [];\n\n // Prefill inputs and outputs as they are sometimes self-referencing themselves.\n const indexedInputs: Map<string, Input> = new Map();\n const inputs: Input[] = reportInputs.map<Input>((input) => {\n const newInput: Input = {\n ...input,\n // Keep them empty for now, we'll fill them later.\n dependencies: new Set(),\n dependents: new Set(),\n };\n indexedInputs.set(input.filepath, newInput);\n return newInput;\n });\n\n const indexedOutputs: Map<string, Output> = new Map();\n const outputs: Output[] = reportOutputs.map<Output>((output) => {\n const newOutput: Output = { ...output, inputs: [] };\n indexedOutputs.set(output.filepath, newOutput);\n return newOutput;\n });\n\n // Fill in the inputs' dependencies and dependents.\n for (const input of reportInputs) {\n const newInput: Input = indexedInputs.get(input.filepath)!;\n\n // Re-assign the dependencies and dependents to the actual objects.\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n const newDependency = indexedInputs.get(dependency)!;\n newInput.dependencies.add(newDependency);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n const newDependent = indexedInputs.get(dependent)!;\n newInput.dependents.add(newDependent);\n }\n }\n }\n\n // Fill in the outputs' inputs.\n for (const output of reportOutputs) {\n const newOutput: Output = indexedOutputs.get(output.filepath)!;\n if (output.inputs) {\n // Re-assign the inputs to the actual objects.\n newOutput.inputs = output.inputs\n .map<\n // Can be either an input or an output (for sourcemaps).\n Input | Output | undefined\n >((filepath: string) => indexedInputs.get(filepath) || indexedOutputs.get(filepath))\n .filter(Boolean) as (Input | Output)[];\n }\n }\n\n for (const entry of report.entries || []) {\n const newEntry: Entry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs\n .map((filepath: string) => indexedInputs.get(filepath))\n .filter(Boolean) as (Output | Input)[];\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs\n .map((filepath: string) => indexedOutputs.get(filepath))\n .filter(Boolean) as Output[];\n }\n entries.push(newEntry);\n }\n\n return {\n ...buildReport,\n entries,\n inputs,\n outputs,\n };\n};\n\n// Verify that we should get the git information based on the options.\n// Only get git information if sourcemaps are enabled and git is enabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n // If we don't have sourcemaps enabled, we don't need git.\n const gitEnabledFromSourcemaps = !!options.errorTracking?.sourcemaps;\n // If we have the 'enableGit' configuration at the root, use it and default to `true`.\n const gitEnabledFromRoot = options.enableGit ?? true;\n return gitEnabledFromSourcemaps && gitEnabledFromRoot;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// Format a duration 0h 0m 0s 0ms\nexport const formatDuration = (duration: number) => {\n const days = Math.floor(duration / 1000 / 60 / 60 / 24);\n const usedDuration = duration - days * 24 * 60 * 60 * 1000;\n const d = new Date(usedDuration);\n const hours = d.getUTCHours();\n const minutes = d.getUTCMinutes();\n const seconds = d.getUTCSeconds();\n const milliseconds = d.getUTCMilliseconds();\n const timeString =\n `${days ? `${days}d ` : ''}${hours ? `${hours}h ` : ''}${minutes ? `${minutes}m ` : ''}${\n seconds ? `${seconds}s` : ''\n }`.trim();\n // Split here so we can show 0ms in case we have a duration of 0.\n return `${timeString}${!timeString || milliseconds ? ` ${milliseconds}ms` : ''}`.trim();\n};\n\n// Truncate a string to a certain length.\n// Placing a [...] placeholder in the middle.\n// \"A way too long sentence could be truncated a bit.\" => \"A way too[...]could be truncated a bit.\"\nexport const truncateString = (\n str: string,\n maxLength: number = 60,\n placeholder: string = '[...]',\n) => {\n if (str.length <= maxLength) {\n return str;\n }\n\n // We want to keep at the very least 4 characters.\n const stringLength = Math.max(4, maxLength - placeholder.length);\n\n // We want to keep most of the end of the string, hence the 10 chars top limit for left.\n const leftStop = Math.min(10, Math.floor(stringLength / 2));\n const rightStop = stringLength - leftStop;\n\n return `${str.slice(0, leftStop)}${placeholder}${str.slice(-rightStop)}`;\n};\n\n// Remove the sensitive information from a repository URL.\nexport const filterSensitiveInfoFromRepositoryUrl = (repositoryUrl: string = '') => {\n try {\n // Keep empty strings and git@ URLs as they are.\n if (!repositoryUrl || repositoryUrl.startsWith('git@')) {\n return repositoryUrl;\n }\n\n const url = new URL(repositoryUrl);\n\n // Construct clean URL with protocol, host and pathname (if not root)\n const cleanPath = url.pathname === '/' ? '' : url.pathname;\n const protocol = url.protocol ? `${url.protocol}//` : '';\n return `${protocol}${url.host}${cleanPath}`;\n } catch {\n return repositoryUrl;\n }\n};\n\nlet index = 0;\nexport const getUniqueId = () => `${Date.now()}.${performance.now()}.${++index}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type {\n GetLogger,\n GlobalData,\n GlobalStores,\n LogLevel,\n LogOptions,\n TimeLog,\n TimeLogger,\n Timer,\n} from '@dd/core/types';\nimport c from 'chalk';\n\nconst logPriority: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n};\n\n// Which separator to use for plugin names.\nexport const NAME_SEP = '>';\n\nconst cleanName = (name: string) => {\n return name.split(NAME_SEP).map(cleanPluginName).join(NAME_SEP);\n};\n\ntype LogFn = (text: any, type?: LogLevel, opts?: LogOptions) => void;\n\nexport const getLogFn = (\n name: string,\n data: GlobalData,\n stores: GlobalStores,\n logLevel: LogLevel,\n): LogFn => {\n // Will remove any \"datadog-\" prefix and \"-plugin\" suffix in the name string.\n const cleanedName = cleanName(name);\n return (text, type = 'debug', { forward } = {}) => {\n // By default (debug) we print dimmed.\n let color = c.dim;\n let logFn = console.log;\n\n if (type === 'error') {\n color = c.red;\n logFn = console.error;\n } else if (type === 'warn') {\n color = c.yellow;\n logFn = console.warn;\n } else if (type === 'info') {\n color = c.cyan;\n logFn = console.log;\n }\n\n const buildName = data.metadata?.name ? `${data.metadata.name}|` : '';\n const prefix = `[${buildName}${type}|${data.bundler.name}|${cleanedName}]`;\n\n // Keep a trace of the log in the build report.\n const content = typeof text === 'string' ? text : JSON.stringify(text, null, 2);\n stores.logs.push({\n bundler: data.bundler.name,\n pluginName: name,\n type,\n message: content,\n time: Date.now(),\n });\n\n if (type === 'error') {\n stores.errors.push(content);\n }\n if (type === 'warn') {\n stores.warnings.push(content);\n }\n\n if (forward) {\n const forwardLog = async () => {\n try {\n const sendLog = getSendLog(data);\n await sendLog({ message: content, context: { plugin: name, status: type } });\n } catch (e) {\n // Log the error using the parent logger.\n const subLogger = getLogFn(name, data, stores, logLevel);\n subLogger(`Error forwarding log: ${e}`, 'debug');\n }\n };\n stores.queue.push(forwardLog());\n }\n\n // Only log if the log level is high enough.\n if (logPriority[type] >= logPriority[logLevel]) {\n logFn(`${color(prefix)} ${content}`);\n }\n };\n};\n\nexport const getTimeLogger = (\n name: string,\n store: GlobalStores['timings'],\n log: LogFn,\n): TimeLog => {\n return (label, opts = {}) => {\n const { level = 'debug', start = true, log: toLog = true, tags = [] } = opts;\n const timer: Timer = {\n pluginName: name,\n label,\n spans: [],\n tags: [...tags, `plugin:${name}`, `level:${level}`],\n logLevel: level,\n total: 0,\n };\n\n // Add it to the build report.\n store.push(timer);\n\n const getUncompleteSpans = () => timer.spans.filter((span) => !span.end);\n\n // Push a new span.\n const resume: TimeLogger['resume'] = (startTime?: number) => {\n // Ignore if there is already an ongoing span.\n const uncompleteSpans = getUncompleteSpans();\n if (uncompleteSpans.length) {\n return;\n }\n\n // Log the start if it's the first span.\n if (!timer.spans.length && toLog) {\n log(c.dim(`[${c.cyan(label)}] : start`), 'debug');\n }\n\n // Add the new span.\n timer.spans.push({\n start: startTime || Date.now(),\n tags: [`plugin:${name}`],\n });\n };\n\n // Complete all the uncompleted spans.\n const pause: TimeLogger['pause'] = (pauseTime?: number, warn: boolean = true) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n if (warn) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\n }\n return;\n }\n\n if (uncompleteSpans.length > 1) {\n log(`Timer ${c.cyan(label)} has more than one ongoing span.`, 'debug');\n }\n\n for (const span of uncompleteSpans) {\n span.end = pauseTime || Date.now();\n }\n };\n\n // End the timer and add it to the build report.\n const end: TimeLogger['end'] = (endTime?: number) => {\n // We don't want to log a warning if the timer is already paused.\n pause(endTime, false);\n // Compute the total duration.\n const duration = timer.spans.reduce((acc, span) => acc + (span.end! - span.start), 0);\n timer.total = duration;\n if (toLog) {\n log(`[${c.cyan(label)}] : ${c.cyan(formatDuration(duration))}`, level);\n }\n };\n\n // Add a tag to the timer or the ongoing spans.\n const tag: TimeLogger['tag'] = (tagsToAdd, tagOpts = {}) => {\n const { span = false } = tagOpts;\n if (span) {\n const uncompleteSpans = getUncompleteSpans();\n for (const uncompleteSpan of uncompleteSpans) {\n uncompleteSpan.tags.push(...tagsToAdd);\n }\n } else {\n timer.tags.push(...tagsToAdd);\n }\n };\n\n // Auto start the timer.\n if (start) {\n let param: number | undefined;\n if (typeof start === 'number') {\n param = start;\n }\n resume(param);\n }\n\n const timeLogger: TimeLogger = {\n timer,\n resume,\n end,\n pause,\n tag,\n };\n\n return timeLogger;\n };\n};\n\nexport const getLoggerFactory =\n (data: GlobalData, stores: GlobalStores, logLevel: LogLevel = 'warn'): GetLogger =>\n (name) => {\n const log = getLogFn(name, data, stores, logLevel);\n return {\n getLogger: (subName: string) => {\n const logger = getLoggerFactory(data, stores, logLevel);\n return logger(`${cleanName(name)}${NAME_SEP}${subName}`);\n },\n time: getTimeLogger(name, stores.timings, log),\n error: (text: any, opts?: LogOptions) => log(text, 'error', opts),\n warn: (text: any, opts?: LogOptions) => log(text, 'warn', opts),\n info: (text: any, opts?: LogOptions) => log(text, 'info', opts),\n debug: (text: any, opts?: LogOptions) => log(text, 'debug', opts),\n };\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '@dd/core/constants';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport type {\n CustomPluginOptions,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPluginsArg,\n GetPlugins,\n GlobalContext,\n Logger,\n PluginOptions,\n GetWrappedPlugins,\n CustomHooks,\n} from '@dd/core/types';\nimport type { UnpluginOptions } from 'unplugin';\n\n// Unplugin universal hooks.\nconst UNPLUGIN_HOOKS = [\n 'buildEnd',\n 'buildStart',\n 'load',\n 'resolveId',\n 'transform',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['buildRoot', 'init', 'buildReport', 'bundlerReport', 'git'] as const;\n\n// All the hooks that we want to trace.\nconst HOOKS_TO_TRACE = [...UNPLUGIN_HOOKS, ...CUSTOM_HOOKS];\n\n// Represents the hook names a plugin can have (including those we're not tracing).\ntype PluginHookName = keyof (PluginOptions | CustomPluginOptions);\n// Represents the custom hook names.\ntype CustomHookName = (typeof CUSTOM_HOOKS)[number];\n// Represents the unplugin hook names.\ntype UnpluginHookName = (typeof UNPLUGIN_HOOKS)[number];\n// Represents the hook names that we want to trace.\ntype HookName = CustomHookName | UnpluginHookName;\n// Represents the hook handler that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = <T extends HookFn>(\n pluginName: string,\n hookName: HookName,\n hook: T,\n log: Logger,\n): T => {\n // Create a wrapper function that adds timing to any hook function\n const wrapWithTiming = <F extends (...args: any[]) => any>(fn: F): F => {\n return function (this: any, ...args) {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n const result = fn.apply(this, args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n } as F;\n };\n\n // Handle object hooks (with filter/handler pattern)\n if (typeof hook === 'object' && hook !== null && 'handler' in hook) {\n return {\n ...hook,\n handler: wrapWithTiming(hook.handler),\n };\n }\n\n // Handle function hooks\n return wrapWithTiming(hook) as T;\n};\n\nexport const wrapPlugin = (plugin: PluginOptions | CustomPluginOptions, log: Logger) => {\n const wrappedPlugin: PluginOptions | CustomPluginOptions = {\n ...plugin,\n };\n const name = cleanPluginName(plugin.name);\n\n // Wrap all the hooks that we want to trace.\n for (const hookName of HOOKS_TO_TRACE) {\n const hook = plugin[hookName];\n if (hook) {\n wrappedPlugin[hookName as PluginHookName] = wrapHook(name, hookName, hook, log);\n }\n }\n\n return wrappedPlugin;\n};\n\nexport const wrapGetPlugins = (\n context: GlobalContext,\n getPlugins: GetPlugins | GetCustomPlugins | GetInternalPlugins,\n name: string,\n): GetWrappedPlugins => {\n const log = context.getLogger(HOST_NAME);\n // Return the getPlugins function wrapped, so we can measure the initialization time.\n return (arg: GetPluginsArg) => {\n // Start our timer.\n const initTimer = log.time(`hook | init ${name}`, { log: false });\n\n // Wrap all the plugins that are returned by the initial getPlugins function.\n const wrappedPlugins = getPlugins(arg).map((plugin) => wrapPlugin(plugin, log));\n\n // Tag our timer with the plugin names.\n const pluginNames = wrappedPlugins.map((plugin) => `plugin:${plugin.name}`);\n initTimer.tag(pluginNames);\n\n // End of initialization.\n initTimer.end();\n return wrappedPlugins;\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'errorTracking' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-error-tracking-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport path from 'path';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap, MinifiedPathPrefix } from '../types';\n\ntype PartialSourcemap = Pick<Sourcemap, 'minifiedFilePath' | 'minifiedUrl' | 'relativePath'>;\n\n// Helper function to safely join URLs or paths\nexport const joinUrlOrPath = (prefix: MinifiedPathPrefix, relativePath: string): string => {\n // Prefix is a path.\n if (prefix.startsWith('/')) {\n // Simply join the prefix with the relative path.\n return path.join(prefix, relativePath);\n }\n\n // Prefix is a URL.\n try {\n // Ensure it ends with a slash for deterministic URL path joining.\n const normalizedPrefix = prefix.replace(/\\/*$/, '/');\n const url = new URL(normalizedPrefix);\n // Ensure the relative path does not start with a slash\n // otherwise it will act as a \"root\" path when joined with the url.\n const normalizedRelativePath = relativePath.replace(/^[\\\\/]*/, '');\n return new URL(normalizedRelativePath, url).href;\n } catch {\n // Fallback to simple concatenation if URL constructor fails\n return `${prefix}${relativePath}`;\n }\n};\n\nexport const decomposePath = (\n prefix: MinifiedPathPrefix,\n // This is coming from context.bundler.outDir, which is absolute.\n absoluteOutDir: string,\n sourcemapFilePath: string,\n): PartialSourcemap => {\n if (path.extname(sourcemapFilePath) !== '.map') {\n throw new Error(`The file ${chalk.green.bold(sourcemapFilePath)} is not a sourcemap.`);\n }\n\n const minifiedFilePath = sourcemapFilePath.replace(/\\.map$/, '');\n const relativePath = path.relative(absoluteOutDir, minifiedFilePath);\n const minifiedUrl = joinUrlOrPath(prefix, relativePath);\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport type SourcemapsFilesContext = {\n outputs?: Output[];\n outDir: string;\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsFilesContext,\n): Sourcemap[] => {\n if (!context.outputs || context.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.outputs\n .filter((file) => file.filepath.endsWith('.map'))\n .map((file) => file.filepath);\n\n const sourcemapFiles = sourcemapFilesList.map((sourcemapFilePath) => {\n return {\n ...decomposePath(options.minifiedPathPrefix, context.outDir, sourcemapFilePath),\n sourcemapFilePath,\n minifiedPathPrefix: options.minifiedPathPrefix,\n };\n });\n\n return sourcemapFiles;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { File } from 'buffer';\nimport fsp from 'fs/promises';\nimport fs from 'fs';\nimport { JsonStreamStringify } from 'json-stream-stringify';\nimport path from 'path';\nimport { Readable } from 'stream';\n\nimport type { FileValidity, LocalAppendOptions } from '../types';\n\n// Replacing fs-extra with local helpers.\n// Delete folders recursively.\nexport const rm = async (dir: string) => {\n return fsp.rm(dir, { force: true, maxRetries: 3, recursive: true });\n};\nexport const rmSync = (dir: string) => {\n return fs.rmSync(dir, { force: true, maxRetries: 3, recursive: true });\n};\n\n// Mkdir recursively.\nexport const mkdir = async (dir: string) => {\n return fsp.mkdir(dir, { recursive: true });\n};\n\nexport const mkdirSync = (dir: string) => {\n return fs.mkdirSync(dir, { recursive: true });\n};\n\n// Write a file but first ensure the directory exists.\nexport const outputFile = async (filepath: string, data: string) => {\n await mkdir(path.dirname(filepath));\n await fsp.writeFile(filepath, data, { encoding: 'utf-8' });\n};\n\nexport const outputFileSync = (filepath: string, data: string) => {\n mkdirSync(path.dirname(filepath));\n fs.writeFileSync(filepath, data, { encoding: 'utf-8' });\n};\n\n// Output a JSON file.\nexport const outputJson = async (filepath: string, data: any) => {\n await mkdir(path.dirname(filepath));\n // Use streams so it doesn't crash on very large data.\n const writable = fs.createWriteStream(filepath);\n const readable = new JsonStreamStringify(data, undefined, 2);\n const prom = new Promise<void>((resolve, reject) => {\n readable.on('end', () => {\n resolve();\n });\n\n readable.on('error', (err) => {\n reject(err);\n });\n });\n readable.pipe(writable);\n return prom;\n};\n\nexport const outputJsonSync = (filepath: string, data: any) => {\n // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n outputFileSync(filepath, dataString);\n};\n\n// Read a JSON file.\nexport const readJsonSync = (filepath: string) => {\n const data = fs.readFileSync(filepath, { encoding: 'utf-8' });\n return JSON.parse(data);\n};\n\n// Read a file.\nexport const readFile = (filepath: string) => {\n return fsp.readFile(filepath, { encoding: 'utf-8' });\n};\n\nexport const readFileSync = (filepath: string) => {\n return fs.readFileSync(filepath, { encoding: 'utf-8' });\n};\n\nexport const existsSync = (filepath: string) => {\n try {\n return fs.existsSync(filepath);\n } catch (error: any) {\n // If the file does not exist, return false.\n if (error.code === 'ENOENT') {\n return false;\n }\n // If some other error occurs, rethrow it.\n throw error;\n }\n};\n\n// Some other more specific helpers.\n\n// From a path, returns a File to use with native FormData and fetch.\nexport const getFile = async (filepath: string, options: LocalAppendOptions) => {\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n const blob = await fs.openAsBlob(filepath, { type: options.contentType });\n return new File([blob], options.filename);\n } else {\n // Support NodeJS 18-\n const stream = Readable.toWeb(fs.createReadStream(filepath));\n const blob = await new Response(stream).blob();\n const file = new File([blob], options.filename, { type: options.contentType });\n return file;\n }\n};\n\n// Verify that every files are available.\nexport const checkFile = async (filePath: string): Promise<FileValidity> => {\n const validity: FileValidity = {\n empty: false,\n exists: true,\n };\n\n try {\n const { size } = await fsp.stat(filePath);\n if (size === 0) {\n validity.empty = true;\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n validity.exists = false;\n } else {\n // Other kind of error\n throw error;\n }\n }\n\n return validity;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { checkFile } from '@dd/core/helpers/fs';\nimport type { FileValidity, LocalAppendOptions, RepositoryData } from '@dd/core/types';\nimport path from 'path';\n\nimport type { Sourcemap } from '../types';\n\nexport type Payload = {\n content: Map<string, MultipartValue>;\n errors: string[];\n warnings: string[];\n};\n\nexport type Metadata = {\n plugin_version: string;\n project_path: string;\n service: string;\n type: string;\n version: string;\n git_repository_url?: string;\n git_commit_sha?: string;\n};\n\ntype SourcemapValidity = {\n file: FileValidity;\n sourcemap: FileValidity;\n repeatedPrefix: string;\n};\n\nexport interface MultipartStringValue {\n type: 'string';\n value: string;\n options: LocalAppendOptions;\n}\n\nexport interface MultipartFileValue {\n type: 'file';\n path: string;\n options: LocalAppendOptions;\n}\n\nexport type MultipartValue = MultipartStringValue | MultipartFileValue;\n\nconst SLASH_RX = /[/]+|[\\\\]+/g;\nconst SLASH_TRIM_RX = /^[/]+|^[\\\\]+|[/]+$|[\\\\]+$/g;\n\n// Verify any repeated pattern between the path and prefix.\nexport const prefixRepeat = (filePath: string, prefix: string): string => {\n const pathParts = filePath.replace(SLASH_TRIM_RX, '').split(SLASH_RX);\n const prefixParts = prefix.replace(SLASH_TRIM_RX, '').split(SLASH_RX);\n const normalizedPath = pathParts.join('/');\n\n let result = '';\n\n for (let i = 0; i < prefixParts.length; i += 1) {\n // TODO: Check compatibility with Windows paths.\n const partialPrefix = prefixParts.slice(-i).join('/');\n if (normalizedPath.startsWith(partialPrefix)) {\n result = partialPrefix;\n }\n }\n\n return result;\n};\n\nconst getSourcemapValidity = async (\n sourcemap: Sourcemap,\n prefix: string,\n): Promise<SourcemapValidity> => {\n const [resultMinFile, resultSourcemap] = await Promise.all([\n checkFile(sourcemap.minifiedFilePath),\n checkFile(sourcemap.sourcemapFilePath),\n ]);\n\n return {\n file: resultMinFile,\n sourcemap: resultSourcemap,\n repeatedPrefix: prefixRepeat(sourcemap.relativePath, prefix),\n };\n};\n\nexport const getPayload = async (\n sourcemap: Sourcemap,\n metadata: Metadata,\n prefix: string,\n git?: RepositoryData,\n): Promise<Payload> => {\n const validity = await getSourcemapValidity(sourcemap, prefix);\n const errors: string[] = [];\n const warnings: string[] = [];\n const content = new Map<string, MultipartValue>([\n [\n 'event',\n {\n type: 'string',\n options: {\n contentType: 'application/json',\n filename: 'event',\n },\n value: JSON.stringify({\n ...metadata,\n minified_url: sourcemap.minifiedUrl,\n }),\n },\n ],\n [\n 'source_map',\n {\n type: 'file',\n path: sourcemap.sourcemapFilePath,\n options: { filename: 'source_map', contentType: 'application/json' },\n },\n ],\n [\n 'minified_file',\n {\n type: 'file',\n path: sourcemap.minifiedFilePath,\n options: { filename: 'minified_file', contentType: 'application/javascript' },\n },\n ],\n ]);\n\n // Add git payload if available.\n if (git) {\n try {\n content.set('repository', {\n type: 'string',\n options: {\n contentType: 'application/json',\n filename: 'repository',\n },\n value: JSON.stringify({\n data: [\n {\n files: git.trackedFilesMatcher.matchSourcemap(\n sourcemap.sourcemapFilePath,\n (reason) => {\n warnings.push(\n `${path.basename(sourcemap.sourcemapFilePath)}: \"${reason}\"`,\n );\n },\n ),\n hash: git.hash,\n repository_url: git.remote,\n },\n ],\n // NOTE: Make sure to update the version if the format of the JSON payloads changes in any way.\n version: 1,\n }),\n });\n } catch (error: any) {\n warnings.push(\n `Could not attach git data for sourcemap ${sourcemap.sourcemapFilePath}: ${error.message}`,\n );\n }\n }\n\n if (validity.file.empty) {\n errors.push(`Minified file is empty: ${sourcemap.minifiedFilePath}`);\n }\n if (!validity.file.exists) {\n errors.push(`Minified file not found: ${sourcemap.minifiedFilePath}`);\n }\n if (validity.sourcemap.empty) {\n errors.push(`Sourcemap file is empty: ${sourcemap.sourcemapFilePath}`);\n }\n if (!validity.sourcemap.exists) {\n errors.push(`Sourcemap file not found: ${sourcemap.sourcemapFilePath}`);\n }\n if (validity.repeatedPrefix) {\n warnings.push(\n `The minified file path contains a repeated pattern with the minified path prefix: ${validity.repeatedPrefix}`,\n );\n }\n\n return { content, errors, warnings };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getFile } from '@dd/core/helpers/fs';\nimport { doRequest, NB_RETRIES } from '@dd/core/helpers/request';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type { Logger, RepositoryData } from '@dd/core/types';\nimport chalk from 'chalk';\nimport PQueue from 'p-queue';\nimport { Readable } from 'stream';\nimport type { Gzip } from 'zlib';\nimport { createGzip } from 'zlib';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap } from '../types';\n\nimport type { Metadata, MultipartFileValue, Payload } from './payload';\nimport { getPayload } from './payload';\n\ntype DataResponse = { data: Gzip; headers: Record<string, string> };\n\nconst green = chalk.green.bold;\nconst yellow = chalk.yellow.bold;\nconst red = chalk.red.bold;\n\ntype FileMetadata = {\n sourcemap: string;\n file: string;\n};\n\nexport const SOURCEMAPS_API_SUBDOMAIN = 'sourcemap-intake';\nexport const SOURCEMAPS_API_PATH = 'api/v2/srcmap';\n\nexport const getIntakeUrl = (site: string) => {\n return (\n process.env.DATADOG_SOURCEMAP_INTAKE_URL ||\n `https://${SOURCEMAPS_API_SUBDOMAIN}.${site}/${SOURCEMAPS_API_PATH}`\n );\n};\n\n// Use a function to get new streams for each retry.\nexport const getData =\n (payload: Payload, defaultHeaders: Record<string, string> = {}) =>\n async (): Promise<DataResponse> => {\n const form = new FormData();\n const gz = createGzip();\n\n for (const [key, content] of payload.content) {\n const value =\n content.type === 'file'\n ? // eslint-disable-next-line no-await-in-loop\n await getFile(content.path, content.options)\n : new Blob([content.value], { type: content.options.contentType });\n\n form.append(key, value, content.options.filename);\n }\n\n // GZip data, we use a Request to serialize the data and transform it into a stream.\n const req = new Request('fake://url', { method: 'POST', body: form });\n const formStream = Readable.fromWeb(req.body!);\n const data = formStream.pipe(gz);\n\n const headers = {\n 'Content-Encoding': 'gzip',\n ...defaultHeaders,\n ...Object.fromEntries(req.headers.entries()),\n };\n\n return { data, headers };\n };\n\nexport type UploadContext = {\n apiKey?: string;\n bundlerName: string;\n site: string;\n version: string;\n outDir: string;\n};\n\nexport const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: UploadContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.apiKey) {\n errors.push({ error: new Error('No authentication token provided') });\n return { errors, warnings };\n }\n\n if (payloads.length === 0) {\n warnings.push('No sourcemaps to upload');\n return { errors, warnings };\n }\n\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const queue = new Queue({ concurrency: options.maxConcurrency });\n const intakeUrl = getIntakeUrl(context.site);\n const defaultHeaders = {\n 'DD-EVP-ORIGIN': `${context.bundlerName}-build-plugin_sourcemaps`,\n 'DD-EVP-ORIGIN-VERSION': context.version,\n };\n\n // Show a pretty summary of the configuration.\n const configurationString = Object.entries({\n ...options,\n intakeUrl,\n outDir: context.outDir,\n defaultHeaders: `\\n${JSON.stringify(defaultHeaders, null, 2)}`,\n })\n .map(([key, value]) => ` - ${key}: ${green(value.toString())}`)\n .join('\\n');\n\n const summary = `\\nUploading ${green(payloads.length.toString())} sourcemaps with configuration:\\n${configurationString}`;\n\n log.info(summary);\n\n const addPromises = [];\n\n for (const payload of payloads) {\n const metadata = {\n sourcemap: (payload.content.get('source_map') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n };\n\n addPromises.push(\n queue.add(async () => {\n try {\n await doRequest({\n auth: { apiKey: context.apiKey },\n url: intakeUrl,\n method: 'POST',\n getData: getData(payload, defaultHeaders),\n // On retry we store the error as a warning.\n onRetry: (error: Error, attempt: number) => {\n const warningMessage = `Failed to upload ${yellow(metadata.sourcemap)} | ${yellow(metadata.file)}:\\n ${error.message}\\nRetrying ${attempt}/${NB_RETRIES}`;\n // This will be logged at the end of the process.\n warnings.push(warningMessage);\n log.debug(warningMessage);\n },\n });\n } catch (e: any) {\n errors.push({ metadata, error: e });\n // Depending on the configuration we throw or not.\n if (options.bailOnError === true) {\n throw e;\n }\n }\n }),\n );\n }\n\n log.debug(`Queued ${green(payloads.length.toString())} uploads.`);\n\n await Promise.all(addPromises);\n await queue.onIdle();\n return { warnings, errors };\n};\n\nexport type SourcemapsSenderContext = UploadContext & {\n git?: RepositoryData;\n};\n\nexport const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsSenderContext,\n log: Logger,\n) => {\n const start = Date.now();\n const prefix = options.minifiedPathPrefix;\n\n const metadata: Metadata = {\n git_repository_url: context.git?.remote,\n git_commit_sha: context.git?.hash,\n plugin_version: context.version,\n project_path: context.outDir,\n service: options.service,\n type: 'js_sourcemap',\n version: options.releaseVersion,\n };\n\n const payloads = await Promise.all(\n sourcemaps.map((sourcemap) => getPayload(sourcemap, metadata, prefix, context.git)),\n );\n\n const errors = payloads.map((payload) => payload.errors).flat();\n const warnings = payloads.map((payload) => payload.warnings).flat();\n\n if (warnings.length > 0) {\n log.warn(`Warnings while preparing payloads:\\n - ${warnings.join('\\n - ')}`);\n }\n\n if (errors.length > 0) {\n const errorMsg = `Failed to prepare payloads, aborting upload :\\n - ${errors.join('\\n - ')}`;\n log.error(errorMsg);\n // Depending on the configuration we throw or not.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n return;\n }\n\n const { errors: uploadErrors, warnings: uploadWarnings } = await upload(\n payloads,\n options,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n version: context.version,\n outDir: context.outDir,\n site: context.site,\n },\n log,\n );\n\n log.info(\n `Done uploading ${green(`${sourcemaps.length - uploadErrors.length}/${sourcemaps.length}`)} sourcemaps in ${green(formatDuration(Date.now() - start))}.`,\n );\n\n if (uploadErrors.length > 0) {\n const listOfErrors = ` - ${uploadErrors\n .map(({ metadata: fileMetadata, error }) => {\n const errorToPrint = error.cause || error.stack || error.message;\n if (fileMetadata) {\n return `${red(fileMetadata.file)} | ${red(fileMetadata.sourcemap)} :\\n${errorToPrint}`;\n }\n return errorToPrint;\n })\n .join('\\n - ')}`;\n\n const errorMsg = `Failed to upload some sourcemaps:\\n${listOfErrors}`;\n log.error(errorMsg);\n\n // Depending on the configuration we throw or not.\n // This should not be reached as we'd have thrown earlier.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n }\n\n if (uploadWarnings.length > 0) {\n log.warn(`Warnings while uploading sourcemaps:\\n - ${uploadWarnings.join('\\n - ')}`);\n }\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n site: context.site,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type {\n ErrorTrackingOptions,\n ErrorTrackingOptionsWithDefaults,\n SourcemapsOptionsWithDefaults,\n} from './types';\n\n// Deal with validation and defaults here.\nexport const validateOptions = (config: Options, log: Logger): ErrorTrackingOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sourcemapsResults = validateSourcemapsOptions(config);\n errors.push(...sourcemapsResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n // Build the final configuration.\n const toReturn: ErrorTrackingOptionsWithDefaults = {\n enable: !!config[CONFIG_KEY],\n ...config[CONFIG_KEY],\n sourcemaps: undefined,\n };\n\n // Fill in the defaults.\n if (sourcemapsResults.config) {\n toReturn.sourcemaps = sourcemapsResults.config;\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nconst validateMinifiedPathPrefix = (minifiedPathPrefix: string): boolean => {\n let host;\n try {\n const objUrl = new URL(minifiedPathPrefix!);\n host = objUrl.host;\n } catch {\n // Do nothing.\n }\n\n if (!host && !minifiedPathPrefix!.startsWith('/')) {\n return false;\n }\n\n return true;\n};\n\nexport const validateSourcemapsOptions = (\n config: Options,\n): ToReturn<SourcemapsOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: ErrorTrackingOptions = config[CONFIG_KEY] || {};\n const toReturn: ToReturn<SourcemapsOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.sourcemaps) {\n // Validate the configuration.\n if (!validatedOptions.sourcemaps.releaseVersion) {\n toReturn.errors.push(`${red('sourcemaps.releaseVersion')} is required.`);\n }\n if (!validatedOptions.sourcemaps.service) {\n toReturn.errors.push(`${red('sourcemaps.service')} is required.`);\n }\n if (!validatedOptions.sourcemaps.minifiedPathPrefix) {\n toReturn.errors.push(`${red('sourcemaps.minifiedPathPrefix')} is required.`);\n }\n\n // Validate the minifiedPathPrefix.\n if (validatedOptions.sourcemaps.minifiedPathPrefix) {\n if (!validateMinifiedPathPrefix(validatedOptions.sourcemaps.minifiedPathPrefix)) {\n toReturn.errors.push(\n `${red('sourcemaps.minifiedPathPrefix')} must be a valid URL or start with '/'.`,\n );\n }\n }\n\n // Add the defaults.\n const sourcemapsWithDefaults: SourcemapsOptionsWithDefaults = {\n bailOnError: false,\n dryRun: false,\n maxConcurrency: 20,\n ...validatedOptions.sourcemaps,\n };\n\n // Save the config.\n toReturn.config = sourcemapsWithDefaults;\n }\n\n return toReturn;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { BuildReport, GetPlugins, RepositoryData } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { uploadSourcemaps } from './sourcemaps';\nimport type { ErrorTrackingOptions, ErrorTrackingOptionsWithSourcemaps } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME } from './constants';\n\nexport type types = {\n // Add the types you'd like to expose here.\n ErrorTrackingOptions: ErrorTrackingOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n // Verify configuration.\n const timeOptions = log.time('validate options');\n const validatedOptions = validateOptions(options, log);\n timeOptions.end();\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return [];\n }\n\n let gitInfo: RepositoryData | undefined;\n let buildReport: BuildReport | undefined;\n\n const handleSourcemaps = async () => {\n if (!validatedOptions.sourcemaps) {\n return;\n }\n const totalTime = log.time('sourcemaps process');\n await uploadSourcemaps(\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n {\n apiKey: context.auth.apiKey,\n bundlerName: context.bundler.name,\n git: gitInfo,\n outDir: context.bundler.outDir,\n outputs: buildReport?.outputs || [],\n site: context.auth.site,\n version: context.version,\n },\n log,\n );\n totalTime.end();\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async git(repoData) {\n gitInfo = repoData;\n\n if (buildReport) {\n await handleSourcemaps();\n }\n },\n async buildReport(report) {\n buildReport = report;\n\n if (gitInfo || !shouldGetGitInfo(options)) {\n await handleSourcemaps();\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Metric } from '@dd/core/types';\n\nconst filterTreeMetrics = (metric: Metric): Metric | null =>\n // Remove tree metrics because way too verbose\n !/modules\\.tree\\.(count|size)$/.test(metric.metric) ? metric : null;\n\nconst filterSourcemapsAndNodeModules = (metric: Metric): Metric | null =>\n metric.tags.some(\n (tag: string) =>\n // Remove sourcemaps.\n /^assetName:.*\\.map$/.test(tag) ||\n // Remove third parties.\n /^moduleName:\\/node_modules/.test(tag),\n )\n ? null\n : metric;\n\nconst filterMetricsOnThreshold = (metric: Metric): Metric | null => {\n const thresholds = {\n size: 100000,\n count: 10,\n duration: 1000,\n };\n // Allow count for smaller results.\n if (/(entries|loaders|warnings|errors)\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Dependencies are huges, lets submit a bit less.\n if (/(modules\\.(dependencies|dependents)$)/.test(metric.metric)) {\n thresholds.count = 30;\n }\n // Dependency tree calculation can output a lot of metrics.\n if (/modules\\.tree\\.count$/.test(metric.metric)) {\n thresholds.count = 150;\n }\n if (/modules\\.tree\\.size$/.test(metric.metric)) {\n thresholds.size = 1500000;\n }\n // We want to track entry size whatever their size.\n if (/entries\\.size$/.test(metric.metric)) {\n thresholds.size = 0;\n }\n // We want to track entry module count whatever their number\n if (/entries\\.modules\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n const avg = metric.points.length\n ? metric.points.reduce((accumulator, currentPoint) => accumulator + currentPoint[1], 0) /\n metric.points.length\n : 0;\n return avg > thresholds[metric.type] ? metric : null;\n};\n\nexport const defaultFilters: ((metric: Metric) => Metric | null)[] = [\n filterTreeMetrics,\n filterSourcemapsAndNodeModules,\n filterMetricsOnThreshold,\n];\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'metrics' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-metrics-plugin` as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { OptionsWithDefaults, Metric, ValueContext, MetricToSend } from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/metrics-plugin/constants';\nimport type {\n Module,\n Compilation,\n MetricsOptionsWithDefaults,\n Filter,\n} from '@dd/metrics-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const getTimestamp = (timestamp?: number): number => {\n return Math.floor((timestamp || Date.now()) / 1000);\n};\n\nexport const validateOptions = (\n opts: OptionsWithDefaults,\n bundlerName: string,\n): MetricsOptionsWithDefaults => {\n const options = opts[CONFIG_KEY];\n\n const timestamp = getTimestamp(options?.timestamp);\n\n let prefix = options?.enableDefaultPrefix === false ? '' : `build.${bundlerName}`;\n if (options?.prefix) {\n prefix += prefix ? `.${options.prefix}` : options.prefix;\n }\n\n return {\n enable: !!opts[CONFIG_KEY],\n enableDefaultPrefix: true,\n enableTracing: false,\n filters: defaultFilters,\n tags: [],\n ...opts[CONFIG_KEY],\n timestamp,\n // Make it lowercase and remove any leading/closing dots.\n prefix: prefix.toLowerCase().replace(/(^\\.*|\\.*$)/g, ''),\n };\n};\n\nconst getMetric = (metric: MetricToSend, defaultTags: string[], prefix: string): MetricToSend => {\n return {\n ...metric,\n tags: [...metric.tags, ...defaultTags],\n metric: prefix ? `${prefix}.${metric.metric}` : metric.metric,\n };\n};\n\nexport const getMetricsToSend = (\n metrics: Set<Metric>,\n timestamp: number,\n filters: Filter[],\n defaultTags: string[],\n prefix: string,\n): Set<MetricToSend> => {\n const metricsToSend: Set<MetricToSend> = new Set();\n\n // Apply filters\n for (const metric of metrics) {\n let processedMetrics: MetricToSend = { ...metric, toSend: true };\n if (filters?.length) {\n for (const filter of filters) {\n const result = filter({\n metric: processedMetrics.metric,\n type: processedMetrics.type,\n points: processedMetrics.points,\n tags: processedMetrics.tags,\n });\n\n if (result) {\n // Keep the toSend value from the original metric.\n processedMetrics = { ...result, toSend: processedMetrics.toSend };\n } else {\n // Do not modify the metric but mark it as not to send.\n processedMetrics.toSend = false;\n }\n }\n }\n\n // We wrap the metric after the filters\n // to ensure we apply the right prefix and default tags\n // without being impacted by the filters.\n metricsToSend.add(getMetric(processedMetrics, defaultTags, prefix));\n }\n\n // Count only the metrics that pass the filters\n const count = Array.from(metricsToSend).filter((m) => m.toSend).length;\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n points: [[timestamp, count + 1]],\n tags: [],\n toSend: true,\n },\n defaultTags,\n prefix,\n ),\n );\n\n return metricsToSend;\n};\n\nexport const getPluginName = (opts: string | { name: string }) =>\n typeof opts === 'string' ? opts : opts.name;\n\n// We want to ensure cwd ends with a slash.\nconst formatCwd = (cwd: string = ''): string => {\n return cwd.endsWith('/') ? cwd : `${cwd}/`;\n};\n\n// Format a module name by trimming the user's specific part out.\nexport const getDisplayName = (name: string, cwd?: string) => {\n let toReturn: string = name;\n const nameSplit: string[] = name.split(formatCwd(cwd));\n if (cwd && nameSplit.length) {\n toReturn = nameSplit.pop()!;\n }\n\n return (\n toReturn\n // Remove loaders query\n .split('!')\n .pop()!\n // Remove everything in front of /node_modules\n .replace(/(.*)?\\/node_modules\\//, '/node_modules/')\n // Remove any prefixing ../\n .replace(/^((\\.)*\\/)+/, '')\n );\n};\n\nexport const formatModuleName = (name: string, context?: string) =>\n name\n // Remove loaders query\n .split('!')\n .pop()!\n // Webpack store its modules with a relative path\n // let's do the same so we can integrate better with it.\n .replace(formatCwd(context), './');\n\nexport const getModulePath = (module: Module, compilation: Compilation) => {\n let path: string | undefined = module.userRequest;\n if (!path) {\n let issuer;\n if (compilation.moduleGraph && typeof compilation.moduleGraph.getIssuer === 'function') {\n issuer = compilation.moduleGraph.getIssuer(module);\n } else {\n issuer = module.issuer;\n }\n\n path = issuer?.userRequest;\n\n if (!path) {\n // eslint-disable-next-line no-underscore-dangle\n path = module._identifier?.split('!').pop();\n }\n }\n return path || 'unknown';\n};\n\n// Find the module name and format it the same way as webpack.\nexport const getModuleName = (module: Module, compilation: Compilation, context?: string) => {\n let name: string = module.name || module.userRequest;\n if (!name) {\n name = getModulePath(module, compilation);\n }\n return formatModuleName(name || 'no-name', context);\n};\n\n// Format the loader's name by extracting it from the query.\n// \"[...]/node_modules/babel-loader/lib/index.js\" => babel-loader\nconst formatLoaderName = (loader: string) =>\n loader.replace(/^.*\\/node_modules\\/(@[a-z0-9][\\w-.]+\\/[a-z0-9][\\w-.]*|[^/]+).*$/, '$1');\n\n// Find a module's loaders names and format them.\nexport const getLoaderNames = (module: Module) =>\n (module.loaders || []).map((l: any) => l.loader || l).map(formatLoaderName);\n\nexport const getValueContext = (args: any[]): ValueContext[] => {\n return args.map((arg) => ({\n type: arg?.constructor?.name ?? typeof arg,\n name: arg?.name,\n value: typeof arg === 'string' ? arg : undefined,\n }));\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Output,\n TimingsMap,\n TimingsReport,\n} from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\n// How many items do we show in the top lists.\nconst TOP = 5;\n// How long a path can be before we truncate it.\nconst MAX_VALUE_LENGTH = 60;\n\nconst numColor = chalk.bold.red;\nconst nameColor = chalk.bold.cyan;\n\ntype ValuesToPrint = { name: string; top: boolean; values: { name: string; value: string }[] };\n\ntype FileReport = {\n name: string;\n aggregatedSize?: number;\n size: number;\n dependencies: Set<string>;\n dependents: Set<string>;\n};\n\n// Sort a collection by attribute\nconst sortDesc = (attr: ((arg: any) => any) | string) => (a: any, b: any) => {\n let aVal;\n let bVal;\n\n if (typeof attr === 'function') {\n aVal = attr(a);\n bVal = attr(b);\n } else {\n aVal = a[attr];\n bVal = b[attr];\n }\n\n if (aVal > bVal) {\n return -1;\n } else if (aVal < bVal) {\n return 1;\n } else {\n return 0;\n }\n};\n\nexport const getGeneralValues = (context: GlobalContext): ValuesToPrint[] => {\n const valuesToPrint: ValuesToPrint = {\n name: 'General Numbers',\n values: [],\n top: false,\n };\n\n const nbModules = context.build.inputs ? context.build.inputs.length : 0;\n const nbAssets = context.build.outputs ? context.build.outputs.length : 0;\n const nbWarnings = context.build.warnings.length;\n const nbErrors = context.build.errors.length;\n const nbEntries = context.build.entries ? context.build.entries.length : 0;\n\n if (context.build.start) {\n valuesToPrint.values.push({\n name: 'Overhead duration',\n value: formatDuration(context.build.start - context.start),\n });\n }\n\n if (context.build.duration) {\n valuesToPrint.values.push({\n name: 'Build duration',\n value: formatDuration(context.build.duration),\n });\n }\n\n if (context.build.writeDuration) {\n valuesToPrint.values.push({\n name: 'Write duration',\n value: formatDuration(context.build.writeDuration),\n });\n }\n\n valuesToPrint.values.push(\n {\n name: 'Number of modules',\n value: nbModules.toString(),\n },\n {\n name: 'Number of assets',\n value: nbAssets.toString(),\n },\n {\n name: 'Number of entries',\n value: nbEntries.toString(),\n },\n {\n name: 'Number of warnings',\n value: nbWarnings.toString(),\n },\n {\n name: 'Number of errors',\n value: nbErrors.toString(),\n },\n );\n\n return [valuesToPrint];\n};\n\nconst getAssetsValues = (context: GlobalContext): ValuesToPrint[] => {\n const assetSizesToPrint: ValuesToPrint = {\n name: 'Asset size',\n values: (context.build.outputs || [])\n // We don't want to report on sourcemaps here.\n .filter((output) => output.type !== 'map')\n .sort(sortDesc((output: Output) => output.size))\n .map((output) => ({\n name: output.name,\n value: prettyBytes(output.size),\n })),\n top: true,\n };\n\n const entrySizesToPrint: ValuesToPrint = {\n name: 'Entry aggregated size',\n values: (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: prettyBytes(entry.size),\n })),\n top: true,\n };\n\n const entryModulesToPrint: ValuesToPrint = {\n name: 'Entry number of modules',\n values:\n (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: entry.inputs.length.toString(),\n })) || [],\n top: true,\n };\n\n return [assetSizesToPrint, entrySizesToPrint, entryModulesToPrint];\n};\n\nconst getModulesValues = (context: GlobalContext): ValuesToPrint[] => {\n const dependentsToPrint: ValuesToPrint = {\n name: `Module total dependents`,\n values: [],\n top: true,\n };\n\n const dependenciesToPrint: ValuesToPrint = {\n name: `Module total dependencies`,\n values: [],\n top: true,\n };\n\n const sizesToPrint: ValuesToPrint = {\n name: `Module size`,\n values: [],\n top: true,\n };\n\n const aggregatedSizesToPrint: ValuesToPrint = {\n name: `Module aggregated size`,\n values: [],\n top: true,\n };\n\n const dependencies: Set<FileReport> = new Set();\n\n // Build our collections.\n const serializedReport = serializeBuildReport(context.build);\n const inputs: Map<string, FileReport> = new Map();\n const fileDependencies: Map<string, Set<string>> = new Map();\n const fileDependents: Map<string, Set<string>> = new Map();\n\n for (const input of serializedReport.inputs || []) {\n // We don't want to report on sourcemaps here.\n if (input.type === 'map') {\n continue;\n }\n\n const dependenciesSet = new Set(input.dependencies);\n const dependentsSet = new Set(input.dependents);\n\n // Create the sets for all the dependencies.\n for (const dep of dependenciesSet) {\n if (!fileDependents.has(dep)) {\n fileDependents.set(dep, new Set());\n }\n fileDependents.get(dep)!.add(input.filepath);\n }\n\n // Create the sets for all the dependents.\n for (const dep of dependentsSet) {\n if (!fileDependencies.has(dep)) {\n fileDependencies.set(dep, new Set());\n }\n fileDependencies.get(dep)!.add(input.filepath);\n }\n\n if (fileDependencies.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependencies = fileDependencies.get(input.filepath)!;\n for (const dep of existingDependencies) {\n dependenciesSet.add(dep);\n }\n }\n\n if (fileDependents.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependents = fileDependents.get(input.filepath)!;\n for (const dep of existingDependents) {\n dependentsSet.add(dep);\n }\n }\n\n fileDependencies.set(input.filepath, dependenciesSet);\n fileDependents.set(input.filepath, dependentsSet);\n\n inputs.set(input.filepath, {\n name: input.name,\n size: input.size,\n dependencies: dependenciesSet,\n dependents: dependentsSet,\n });\n }\n\n for (const [filepath, input] of inputs) {\n const inputDependencies = fileDependencies.get(filepath) || new Set();\n const inputDependents = fileDependents.get(filepath) || new Set();\n\n // Aggregate size.\n let aggregatedSize = input.size;\n for (const dep of inputDependencies) {\n aggregatedSize += inputs.get(dep)?.size || 0;\n }\n\n dependencies.add({\n name: input.name,\n size: input.size,\n aggregatedSize,\n dependents: inputDependents,\n dependencies: inputDependencies,\n });\n }\n\n if (!dependencies.size) {\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint];\n }\n\n const dependenciesArray = Array.from(dependencies);\n // Sort by dependents, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependents.size));\n dependentsToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependents.size.toString(),\n }));\n // Sort by dependencies, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependencies.size));\n dependenciesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependencies.size.toString(),\n }));\n // Sort by size, biggest first\n dependenciesArray.sort(sortDesc('size'));\n sizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.size),\n }));\n // Sort by aggregated size, biggest first\n dependenciesArray.sort(sortDesc('aggregatedSize'));\n aggregatedSizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.aggregatedSize || file.size),\n }));\n\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint, aggregatedSizesToPrint];\n};\n\nconst getTimingValues = (name: string, timings?: TimingsMap): ValuesToPrint[] => {\n if (!timings || !timings.size) {\n return [];\n }\n\n const times = Array.from(timings.values());\n // Sort by duration, longest first\n times.sort(sortDesc('duration'));\n const durationsToPrint: ValuesToPrint = {\n name: `${name} duration`,\n values: times.map((module) => ({\n name: module.name,\n value: formatDuration(module.duration),\n })),\n top: true,\n };\n\n // Sort by increment, biggest first\n times.sort(sortDesc('increment'));\n const hitsToPrint: ValuesToPrint = {\n name: `${name} hits`,\n values: times.map((module) => ({\n name: module.name,\n value: module.increment.toString(),\n })),\n top: true,\n };\n\n return [durationsToPrint, hitsToPrint];\n};\n\nconst renderValues = (values: ValuesToPrint[]): string => {\n let outputString = '';\n\n const titlePadding = 4;\n const valuePadding = 4;\n\n // Cleaning and preparing out the groups.\n for (const group of values) {\n // Only keep the top values if requested.\n if (group.top && group.values.length >= TOP) {\n group.values = group.values.slice(0, TOP);\n group.name = `Top ${TOP} ${group.name}`;\n }\n\n // Truncate values' names when they are way too long.\n for (const value of group.values) {\n value.name = truncateString(value.name, MAX_VALUE_LENGTH);\n }\n }\n\n // Calculating the width of the columns.\n const maxTitleWidth = Math.max(...values.map((val) => val.name.length));\n const maxNameWidth = Math.max(...values.flatMap((val) => val.values.map((v) => v.name.length)));\n const maxValueWidth = Math.max(\n ...values.flatMap((val) => val.values.map((v) => v.value.length)),\n );\n const totalWidth = Math.max(\n maxTitleWidth + titlePadding,\n maxNameWidth + maxValueWidth + valuePadding,\n );\n\n // Composing the output.\n for (const group of values) {\n if (group.values.length === 0) {\n continue;\n }\n\n const titlePad = totalWidth - (group.name.length + titlePadding);\n\n outputString += `\\n== ${group.name} ${'='.repeat(titlePad)}=\\n`;\n\n for (const value of group.values) {\n const valuePad = maxValueWidth - value.value.length;\n outputString += ` [${numColor(value.value)}] ${' '.repeat(valuePad)}${nameColor(value.name)}\\n`;\n }\n }\n\n return outputString;\n};\n\nexport const outputTexts = (globalContext: GlobalContext, log: Logger, timings?: TimingsReport) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (timings) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', timings.modules));\n }\n\n valuesToPrint.push(...getModulesValues(globalContext));\n valuesToPrint.push(...getAssetsValues(globalContext));\n valuesToPrint.push(...getGeneralValues(globalContext));\n\n const outputString = renderValues(valuesToPrint);\n\n log.info(outputString);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing, Value } from '@dd/core/types';\nimport { formatModuleName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\nconst loadersMap: Map<string, Timing> = new Map();\nconst pluginsMap: TimingsMap = new Map();\nconst modulesMap: TimingsMap = new Map();\n\nexport const wrapPlugins = (build: PluginBuild, context: string) => {\n const plugins = build.initialOptions.plugins;\n if (plugins) {\n // We clone plugins so we don't pass modified options to other plugins.\n const initialPlugins = plugins.map((plugin) => {\n return {\n ...plugin,\n };\n });\n for (const plugin of plugins) {\n const oldSetup = plugin.setup;\n plugin.setup = async (esbuild) => {\n const newBuildObject = getNewBuildObject(esbuild, plugin.name, context);\n await oldSetup({\n ...newBuildObject,\n // Use non-modified plugins for other plugins\n initialOptions: { ...newBuildObject.initialOptions, plugins: initialPlugins },\n });\n };\n }\n }\n};\n\nconst getNewBuildObject = (\n build: PluginBuild,\n pluginName: string,\n context: string,\n): PluginBuild => {\n const newBuildObject: any = Object.assign({}, build);\n for (const fn of FN_TO_WRAP) {\n newBuildObject[fn] = async (opts: any, cb: any) => {\n const pluginTiming: Timing = pluginsMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n pluginTiming.events[fn] = pluginTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const isLoader = fn === 'onLoad';\n const initialFunction: any = build[fn];\n return initialFunction(opts, async (...args: any[]) => {\n const modulePath = formatModuleName(args[0].path, context);\n const moduleTiming: Timing = modulesMap.get(modulePath) || {\n name: modulePath,\n increment: 0,\n duration: 0,\n events: {},\n };\n moduleTiming.events[fn] = moduleTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const start = performance.now();\n\n try {\n return await cb(...args);\n } finally {\n const end = performance.now();\n const duration = end - start;\n const statsObject: Value = {\n start,\n end,\n duration,\n context: getValueContext(args),\n };\n\n pluginTiming.events[fn].values.push(statsObject);\n pluginTiming.duration += duration;\n pluginTiming.increment += 1;\n pluginsMap.set(pluginName, pluginTiming);\n\n moduleTiming.events[fn].values.push(statsObject);\n moduleTiming.duration += duration;\n moduleTiming.increment += 1;\n modulesMap.set(modulePath, moduleTiming);\n\n // Only if we're in a loader function.\n if (isLoader) {\n const loaderTiming: Timing = loadersMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n loaderTiming.events[fn] = loaderTiming.events[fn] || {\n name: fn,\n values: [],\n };\n loaderTiming.events[fn].values.push(statsObject);\n loaderTiming.duration += duration;\n loaderTiming.increment += 1;\n loadersMap.set(pluginName, loaderTiming);\n }\n }\n });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap, loaders: loadersMap });\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.buildRoot);\n timeWrap.end();\n build.onEnd(async (result: BuildResult) => {\n if (!result.metafile) {\n logger.warn(\"Missing metafile, can't proceed with modules data.\");\n return;\n }\n\n const timeResult = logger.time('getting plugins results');\n const { plugins, loaders, modules } = getPluginsResults();\n timeResult.end();\n\n await globalContext.asyncHook('timings', {\n tapables: plugins,\n loaders,\n modules,\n });\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing } from '@dd/core/types';\nimport { getDisplayName, getModuleName, getLoaderNames } from '@dd/metrics-plugin/common/helpers';\nimport type { Module, Event, Compilation } from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Loaders {\n constructor(cwd: string) {\n this.cwd = cwd;\n }\n cwd: string;\n started: { [key: string]: Event } = {};\n finished: Event[] = [];\n\n startModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n const loaders = getLoaderNames(module);\n\n if (!loaders.length) {\n // Keep a track of modules without a loader.\n loaders.push('no-loader');\n }\n\n // Store the event until the module is complete.\n this.started[moduleName] = {\n module: getDisplayName(moduleName),\n timings: {\n start: performance.now(),\n duration: 0,\n end: 0,\n },\n loaders,\n };\n }\n\n doneModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n // Get the event for this module.\n const event = this.started[moduleName];\n\n if (!event) {\n return;\n }\n\n event.timings.end = performance.now();\n event.timings.duration = event.timings.end - event.timings.start;\n\n // Store the event.\n this.finished.push(event);\n\n // Delete the entry so another import\n // of the same module can be also reported.\n delete this.started[moduleName];\n }\n\n getResults(): {\n modules: TimingsMap;\n loaders: TimingsMap;\n } {\n const loaders: Map<string, Timing> = new Map();\n const modules: Map<string, Timing> = new Map();\n for (const event of this.finished) {\n const duration = event.timings.end! - event.timings.start;\n\n // Aggregate module timings\n const moduleTiming = modules.get(event.module) || {\n name: event.module,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n const eventName = event.loaders.join(',');\n moduleTiming.events[eventName] = moduleTiming.events[eventName] || {\n name: eventName,\n values: [],\n };\n\n moduleTiming.events[eventName].values.push(event.timings);\n moduleTiming.increment += 1;\n moduleTiming.duration += duration;\n modules.set(event.module, moduleTiming);\n\n // Aggregate loader timings\n for (const loader of event.loaders) {\n const loaderTiming = loaders.get(loader) || {\n name: loader,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n loaderTiming.increment += 1;\n loaderTiming.duration += duration;\n loaders.set(loader, loaderTiming);\n }\n }\n\n return { loaders, modules };\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, ValueContext, TAP_TYPES, Timing } from '@dd/core/types';\nimport { getPluginName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n} from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Tapables {\n constructor(cwd: Tapables['cwd']) {\n this.cwd = cwd;\n }\n cwd: string;\n monitoredTaps: MonitoredTaps = {};\n tapables: Tapable[] = [];\n hooks: Hooks = {};\n timings: TimingsMap = new Map();\n ignoredHooks = [\n // This one triggers a DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK warning.\n 'normalModuleLoader',\n ];\n\n saveResult(\n type: TAP_TYPES,\n pluginName: string,\n hookName: string,\n context: ValueContext[],\n start: number,\n end: number,\n ) {\n const timing: Timing = this.timings.get(pluginName) || {\n name: pluginName,\n duration: 0,\n increment: 0,\n events: {},\n };\n if (!timing.events[hookName]) {\n timing.events[hookName] = {\n name: hookName,\n values: [],\n };\n }\n\n timing.events[hookName].values.push({\n start,\n end,\n duration: end - start,\n context,\n type,\n });\n timing.duration += end - start;\n timing.increment += 1;\n this.timings.set(pluginName, timing);\n }\n\n getResults(): TapablesResult {\n const timings = this.timings;\n\n // Aggregate the durations for each plugin.\n for (const [tapableName, tapable] of this.timings) {\n const timing = tapable;\n timing.duration = Object.values(tapable.events)\n .map((hookArray) =>\n hookArray.values.reduce((previous, current) => {\n return previous + current.end - current.start;\n }, 0),\n )\n .reduce((previous, current) => previous + current, 0);\n timings.set(tapableName, timing);\n }\n\n return {\n monitoredTaps: this.monitoredTaps,\n tapables: this.tapables,\n hooks: this.hooks,\n timings,\n };\n }\n\n getPromiseTapPatch(type: TAP_TYPES, fn: TapPromise, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n const cb = () => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n };\n // Save the result whether it succeeds or not.\n returnValue.then(cb, cb);\n return returnValue;\n };\n }\n\n getAsyncTapPatch(type: TAP_TYPES, fn: TapAsync, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n // Callback is the last argument.\n const originalCB = args.pop();\n const newCB = (...a: [any]) => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return originalCB(...a);\n };\n return fn.apply(this, [...args, newCB]);\n };\n }\n\n getDefaultTapPatch(type: TAP_TYPES, fn: Tap, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return returnValue;\n };\n }\n\n // Patch the tap so we can report its execution duration.\n getTapPatch(type: TAP_TYPES, fn: (args: any) => any, pluginName: string, hookName: string) {\n switch (type) {\n case 'promise':\n return this.getPromiseTapPatch(type, fn, pluginName, hookName);\n case 'async':\n return this.getAsyncTapPatch(type, fn, pluginName, hookName);\n case 'default':\n default:\n return this.getDefaultTapPatch(type, fn, pluginName, hookName);\n }\n }\n\n newTap(\n type: TAP_TYPES,\n hookName: string,\n originalTap: Tap | TapAsync | TapPromise,\n scope: any,\n ) {\n return (options: any, fn: (args: any) => any) => {\n const pluginName = getPluginName(options);\n const key = `${hookName}-${pluginName}`;\n if (this.monitoredTaps[key]) {\n // Since it's monitored, fn is already patched.\n return originalTap.call(scope, options, fn);\n }\n this.monitoredTaps[key] = true;\n const newFn = this.getTapPatch(type, fn, pluginName, hookName);\n return originalTap.call(scope, options, newFn);\n };\n }\n\n replaceTaps(hookName: string, hook: Hook) {\n // Cover three types of tap.\n hook.tap = this.newTap('default', hookName, hook.tap!, hook);\n hook.tapAsync = this.newTap('async', hookName, hook.tapAsync!, hook);\n hook.tapPromise = this.newTap('promise', hookName, hook.tapPromise!, hook);\n }\n\n patchHook(tapableName: string, hookName: string, hook: Hook) {\n // Webpack specific, these _fakeHook are not writable.\n // eslint-disable-next-line no-underscore-dangle\n if (hook._fakeHook) {\n return;\n }\n\n // Skip the current plugin.\n if (tapableName.includes(PLUGIN_NAME)) {\n return;\n }\n\n if (!this.hooks[tapableName]) {\n this.hooks[tapableName] = [];\n }\n\n if (this.hooks[tapableName].includes(hookName)) {\n return;\n }\n\n this.hooks[tapableName].push(hookName);\n this.replaceTaps(hookName, hook);\n }\n\n patchHooks(tapable: Tapable) {\n const name = tapable.constructor.name;\n const hooksToPatch = Object.keys(tapable.hooks).filter((hookName) => {\n // Skip the ignored hooks.\n if (this.ignoredHooks.includes(hookName)) {\n return false;\n }\n\n // Skip the already patched hooks.\n if (this.hooks[name]?.includes(hookName)) {\n return false;\n }\n\n return true;\n });\n\n for (const hookName of hooksToPatch) {\n this.patchHook(name, hookName, tapable.hooks[hookName]);\n }\n }\n\n checkNewHooks() {\n // We reparse hooks in case new ones arrived.\n for (const tapable of this.tapables) {\n this.patchHooks(tapable);\n }\n }\n\n // Let's navigate through all the hooks we can find.\n throughHooks(tapable: Tapable) {\n if (!this.tapables.includes(tapable)) {\n this.tapables.push(tapable);\n }\n\n this.patchHooks(tapable);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type { Compilation } from '@dd/metrics-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.buildRoot);\n const loaders = new Loaders(globalContext.buildRoot);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack and rspack reconciliation.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack and rspack reconciliation.\n compiler.hooks.thisCompilation.tap(HOOK_OPTIONS, (compilation: Compilation) => {\n const compilationTime = log.time('parse compilation hooks');\n tapables.throughHooks(compilation);\n compilationTime.end();\n\n // TODO: Use log.time() to measure modules.\n compilation.hooks.buildModule.tap(HOOK_OPTIONS, (module) => {\n loaders.startModule(module, compilation);\n });\n\n compilation.hooks.succeedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n\n // NOTE: compilation.hooks.failedModule is not available in rspack as of 1.2.8\n // https://rspack.dev/api/plugin-api/compilation-hooks\n if (compilation.hooks.failedModule) {\n compilation.hooks.failedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n }\n });\n\n // We're losing some tracing from plugins by using `afterEmit` instead of `done` but\n // it allows us to centralize the common process better.\n // TODO: Use custom hooks to make this more reliable and not blocked by a race condition.\n compiler.hooks.afterEmit.tapPromise(HOOK_OPTIONS, async () => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n await globalContext.asyncHook('timings', {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\n });\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, GetPlugins, Metric, PluginOptions, TimingsReport } from '@dd/core/types';\n\nimport { getUniversalMetrics, getPluginMetrics, getLoaderMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getMetricsToSend, getTimestamp, validateOptions } from './common/helpers';\nimport { outputTexts } from './common/output/text';\nimport { sendMetrics } from './common/sender';\nimport { PLUGIN_NAME, CONFIG_KEY } from './constants';\nimport { getEsbuildPlugin } from './esbuild-plugin';\nimport type { Filter, MetricsOptions } from './types';\nimport { getWebpackPlugin } from './webpack-plugin';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n filters: defaultFilters,\n};\n\nexport type types = {\n Filter: Filter;\n Metric: Metric;\n MetricsOptions: MetricsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n\n const validatedOptions = validateOptions(options, context.bundler.name);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return plugins;\n }\n\n // Webpack and Esbuild specific plugins.\n // LEGACY\n const legacyPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: getEsbuildPlugin(context, log),\n webpack: getWebpackPlugin(context),\n rspack: getWebpackPlugin(context),\n };\n\n const timeBuild = log.time('build', { start: false });\n // Identify if we need the legacy plugin.\n const needLegacyPlugin =\n validatedOptions.enableTracing &&\n ['esbuild', 'webpack', 'rspack'].includes(context.bundler.name);\n let timingsReport: TimingsReport | undefined;\n let buildReport: BuildReport;\n\n const computeMetrics = async () => {\n context.build.end = Date.now();\n context.build.duration = context.build.end - context.build.start!;\n context.build.writeDuration = context.build.end - realBuildEnd;\n\n const timeMetrics = log.time(`aggregating metrics`);\n const timestamp = validatedOptions.timestamp;\n\n const universalMetrics = getUniversalMetrics(buildReport, timestamp);\n const pluginMetrics = getPluginMetrics(timingsReport?.tapables, timestamp);\n const loaderMetrics = getLoaderMetrics(timingsReport?.loaders, timestamp);\n\n const allMetrics = new Set([...universalMetrics, ...pluginMetrics, ...loaderMetrics]);\n\n const metricsToSend = getMetricsToSend(\n allMetrics,\n timestamp,\n validatedOptions.filters,\n validatedOptions.tags,\n validatedOptions.prefix,\n );\n\n await context.asyncHook('metrics', metricsToSend);\n\n timeMetrics.end();\n\n const timeReport = log.time('outputing report');\n outputTexts(context, log, timingsReport);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-metrics-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n // Set the timestamp to the build start if not provided.\n if (!options[CONFIG_KEY]?.timestamp) {\n validatedOptions.timestamp = getTimestamp(context.build.start);\n }\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n async timings(timings) {\n timingsReport = timings;\n // Once we have both reports, we can compute the metrics.\n if (buildReport) {\n await computeMetrics();\n }\n },\n\n async buildReport(report) {\n buildReport = report;\n // Once we have both reports (or we don't need the legacy plugin),\n // we can compute the metrics.\n if (timingsReport || !needLegacyPlugin) {\n await computeMetrics();\n }\n },\n };\n\n if (validatedOptions.enableTracing) {\n plugins.push(legacyPlugin);\n }\n\n plugins.push(universalPlugin);\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, Metric, TimingsMap } from '@dd/core/types';\n\nexport const getUniversalMetrics = (buildReport: BuildReport, timestamp: number): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n const inputs = buildReport.inputs || [];\n const outputs = buildReport.outputs || [];\n const entries = buildReport.entries || [];\n const nbWarnings = buildReport.warnings.length;\n const nbErrors = buildReport.errors.length;\n const duration = buildReport.duration;\n\n // Create some indexes to speed up the process.\n const entriesPerInput = new Map<string, string[]>();\n const assetsPerInput = new Map<string, string[]>();\n const entriesPerAsset = new Map<string, string[]>();\n\n for (const entry of entries) {\n for (const input of entry.inputs) {\n if (!entriesPerInput.has(input.filepath)) {\n entriesPerInput.set(input.filepath, []);\n }\n entriesPerInput.get(input.filepath)!.push(entry.name);\n }\n for (const output of entry.outputs) {\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (!entriesPerAsset.has(cleanAssetName)) {\n entriesPerAsset.set(cleanAssetName, []);\n }\n entriesPerAsset.get(cleanAssetName)!.push(entry.name);\n }\n }\n\n for (const output of outputs) {\n for (const input of output.inputs) {\n if (!assetsPerInput.has(input.filepath)) {\n assetsPerInput.set(input.filepath, []);\n }\n assetsPerInput.get(input.filepath)!.push(output.name);\n }\n }\n\n // Counts\n metrics\n .add({\n metric: 'assets.count',\n type: 'count',\n points: [[timestamp, outputs.length]],\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n points: [[timestamp, entries.length]],\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n points: [[timestamp, nbErrors]],\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n points: [[timestamp, inputs.length]],\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n points: [[timestamp, nbWarnings]],\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n points: [[timestamp, duration]],\n tags: [],\n });\n }\n\n // Modules\n for (const input of inputs) {\n const tags = [`moduleName:${input.name}`, `moduleType:${input.type}`];\n if (entriesPerInput.has(input.filepath)) {\n tags.push(\n ...entriesPerInput\n .get(input.filepath)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n\n if (assetsPerInput.has(input.filepath)) {\n tags.push(\n ...assetsPerInput.get(input.filepath)!.map((assetName) => `assetName:${assetName}`),\n );\n }\n metrics\n .add({\n metric: 'modules.size',\n type: 'size',\n points: [[timestamp, input.size]],\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n points: [[timestamp, input.dependencies.size]],\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n points: [[timestamp, input.dependents.size]],\n tags,\n });\n }\n\n // Assets\n for (const output of outputs) {\n const tags = [`assetName:${output.name}`, `assetType:${output.type}`];\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (entriesPerAsset.has(cleanAssetName)) {\n tags.push(\n ...entriesPerAsset\n .get(cleanAssetName)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n metrics\n .add({\n metric: 'assets.size',\n type: 'size',\n points: [[timestamp, output.size]],\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n points: [[timestamp, output.inputs.length]],\n tags,\n });\n }\n\n // Entries\n for (const entry of entries) {\n const tags = [`entryName:${entry.name}`];\n metrics\n .add({\n metric: 'entries.size',\n type: 'size',\n points: [[timestamp, entry.size]],\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n points: [[timestamp, entry.inputs.length]],\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n points: [[timestamp, entry.outputs.length]],\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const getPluginMetrics = (\n plugins: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!plugins) {\n return metrics;\n }\n\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n points: [[timestamp, plugins.size]],\n tags: [],\n });\n\n for (const plugin of plugins.values()) {\n let pluginDuration = 0;\n let pluginCount = 0;\n\n for (const hook of Object.values(plugin.events)) {\n let hookDuration = 0;\n pluginCount += hook.values.length;\n for (const v of hook.values) {\n const duration = v.end - v.start;\n hookDuration += duration;\n pluginDuration += duration;\n }\n metrics\n .add({\n metric: 'plugins.hooks.duration',\n type: 'duration',\n points: [[timestamp, hookDuration]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n points: [[timestamp, hook.values.length]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n });\n }\n\n metrics\n .add({\n metric: 'plugins.duration',\n type: 'duration',\n points: [[timestamp, pluginDuration]],\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n points: [[timestamp, pluginCount]],\n tags: [`pluginName:${plugin.name}`],\n });\n }\n\n return metrics;\n};\n\nexport const getLoaderMetrics = (\n loaders: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!loaders) {\n return metrics;\n }\n\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n points: [[timestamp, loaders.size]],\n tags: [],\n });\n\n for (const loader of loaders.values()) {\n metrics\n .add({\n metric: 'loaders.duration',\n type: 'duration',\n points: [[timestamp, loader.duration]],\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n points: [[timestamp, loader.increment]],\n tags: [`loaderName:${loader.name}`],\n });\n }\n\n return metrics;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { Logger, Metric, MetricToSend } from '@dd/core/types';\n\nexport const METRICS_API_PATH = 'api/v1/series';\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; site: string },\n log: Logger,\n) => {\n if (!auth.apiKey) {\n log.info(`Won't send metrics to Datadog: missing API Key.`);\n return;\n }\n if (!metrics.size) {\n log.info(`No metrics to send.`);\n return;\n }\n\n // Only send metrics that are to be sent.\n const metricsToSend: Metric[] = Array.from(metrics)\n .filter((metric) => metric.toSend)\n .map((metric) => {\n return {\n ...metric,\n toSend: undefined,\n };\n });\n\n const metricIterations: Map<string, number> = new Map();\n for (const metric of metricsToSend) {\n if (!metricIterations.has(metric.metric)) {\n metricIterations.set(metric.metric, 0);\n }\n metricIterations.set(metric.metric, metricIterations.get(metric.metric)! + 1);\n }\n\n const metricsNames = Array.from(metricIterations.entries())\n // Sort by metric name.\n .sort(([nameA], [nameB]) => nameA.localeCompare(nameB))\n .map(([name, count]) => `${name} - ${count}`);\n\n log.debug(`\nSending ${metricsToSend.length} metrics.\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `https://api.${auth.site}/${METRICS_API_PATH}?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: metricsToSend } satisfies {\n series: Metric[];\n }),\n }),\n }).catch((e) => {\n log.error(`Error sending metrics ${e}`);\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'output' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-output-plugin' as const;\nexport const FILE_KEYS = [\n 'build',\n 'bundler',\n 'dependencies',\n 'errors',\n 'logs',\n 'metrics',\n 'timings',\n 'warnings',\n] as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Options } from '@dd/core/types';\n\nimport { CONFIG_KEY } from './constants';\nimport type { FileKey, OutputOptions, OutputOptionsWithDefaults } from './types';\n\n// Sanitize the output path.\nconst sanitizeOutputPath = (key: FileKey, value: boolean | string) => {\n if (typeof value === 'string') {\n // Ensure we end with the correct extension.\n return value.replace(/(\\.json)?$/, '.json');\n }\n\n // Transform the value into a path.\n return value === true ? `${key}.json` : value;\n};\n\nconst validateFilesOptions = (\n files: OutputOptions['files'],\n): OutputOptionsWithDefaults['files'] => {\n // If no files object is provided, we'll output all files.\n const defaultValue = typeof files === 'undefined';\n\n const validatedFiles: OutputOptionsWithDefaults['files'] = {\n // Listing everything to keep TS happy.\n build: sanitizeOutputPath('build', files?.build ?? defaultValue),\n bundler: sanitizeOutputPath('bundler', files?.bundler ?? defaultValue),\n dependencies: sanitizeOutputPath('dependencies', files?.dependencies ?? defaultValue),\n errors: sanitizeOutputPath('errors', files?.errors ?? defaultValue),\n logs: sanitizeOutputPath('logs', files?.logs ?? defaultValue),\n metrics: sanitizeOutputPath('metrics', files?.metrics ?? defaultValue),\n timings: sanitizeOutputPath('timings', files?.timings ?? defaultValue),\n warnings: sanitizeOutputPath('warnings', files?.warnings ?? defaultValue),\n };\n\n return validatedFiles;\n};\n\n// Deal with validation and defaults here.\nexport const validateOptions = (options: Options): OutputOptionsWithDefaults => {\n const validatedOptions: OutputOptionsWithDefaults = {\n // By using an empty object, we consider the plugin as enabled.\n enable: !!options[CONFIG_KEY],\n path: './',\n ...options[CONFIG_KEY],\n files: validateFilesOptions(options[CONFIG_KEY]?.files),\n };\n\n return validatedOptions;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { outputJson } from '@dd/core/helpers/fs';\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport type { GetPlugins, Logger, PluginOptions } from '@dd/core/types';\nimport path from 'path';\nimport type { OutputBundle } from 'rollup';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { FileKey, FileValue, OutputOptions } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n OutputOptions: OutputOptions;\n};\n\nconst getXpackPlugin =\n (\n log: Logger,\n write: (getStats: () => any) => void,\n ): PluginOptions['webpack'] & PluginOptions['rspack'] =>\n (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\n write(() => {\n const statsTimer = log.time('stats serialization');\n const statsJson = stats.toJson({\n all: false,\n assets: true,\n children: true,\n chunks: true,\n chunkGroupAuxiliary: true,\n chunkGroupChildren: true,\n chunkGroups: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n relatedAssets: true,\n warnings: true,\n // These two add a massive amount of time to the serialization on big builds.\n reasons: false,\n chunkModules: false,\n });\n statsTimer.end();\n return statsJson;\n });\n });\n };\n\nconst getRollupPlugin = (\n write: (getOutputs: () => OutputBundle[]) => void,\n): PluginOptions['rollup'] & PluginOptions['vite'] => {\n const outputs: Set<OutputBundle> = new Set();\n return {\n buildStart() {\n // Clear set on build start.\n outputs.clear();\n },\n writeBundle(opts, bundle) {\n outputs.add(bundle);\n },\n closeBundle() {\n write(() => Array.from(outputs));\n },\n };\n};\n\nexport const getFilePath = (outDir: string, pathOption: string, filename: string): string => {\n // If we have an absolute path, we use it as is.\n const outputPath = path.isAbsolute(pathOption)\n ? pathOption\n : // Otherwise, we resolve it relative to the bundler output directory.\n path.resolve(outDir, pathOption);\n return path.resolve(outputPath, filename);\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n // Verify configuration.\n const validatedOptions = validateOptions(options);\n const log = context.getLogger(PLUGIN_NAME);\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return [];\n }\n\n const writeFile = (name: FileKey, data: any) => {\n const fileValue: FileValue = validatedOptions.files[name];\n if (!data || fileValue === false) {\n return;\n }\n\n const queuedWrite = async () => {\n const timeWrite = log.time(`output ${fileValue}`);\n const filePath = getFilePath(context.bundler.outDir, validatedOptions.path, fileValue);\n let error: unknown;\n\n try {\n const dataToWrite = typeof data === 'function' ? await data() : data;\n await outputJson(filePath, dataToWrite);\n } catch (e) {\n error = e;\n }\n\n if (error) {\n log.error(`Failed writing ${fileValue}: ${error}`);\n } else {\n log.info(`Wrote \"${filePath}\"`);\n }\n\n timeWrite.end();\n };\n // Do not make the file creations blocking.\n context.queue(queuedWrite());\n };\n\n return [\n {\n name: PLUGIN_NAME,\n buildReport(report) {\n const timeSerialization = log.time(`serialize report`);\n const serializedReport = serializeBuildReport(report);\n timeSerialization.end();\n writeFile('build', {\n bundler: serializedReport.bundler,\n metadata: serializedReport.metadata,\n start: serializedReport.start,\n end: serializedReport.end,\n duration: serializedReport.duration,\n writeDuration: serializedReport.writeDuration,\n entries: serializedReport.entries,\n outputs: serializedReport.outputs,\n });\n writeFile('logs', serializedReport.logs);\n writeFile('timings', serializedReport.timings);\n writeFile('dependencies', serializedReport.inputs);\n writeFile('errors', serializedReport.errors);\n writeFile('warnings', serializedReport.warnings);\n },\n metrics(metrics) {\n writeFile('metrics', () => Array.from(metrics));\n },\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n writeFile('bundler', result.metafile);\n });\n },\n },\n rspack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n rollup: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n vite: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n webpack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// This file is partially generated.\n// Anything between #imports-injection-marker and #types-injection-marker\n// will be updated using the 'yarn cli integrity' command.\nimport type { TrackedFilesMatcher } from '@dd/internal-git-plugin/trackedFilesMatcher';\n/* eslint-disable arca/import-ordering */\n// #imports-injection-marker\nimport type { ErrorTrackingOptions } from '@dd/error-tracking-plugin/types';\nimport type * as errorTracking from '@dd/error-tracking-plugin';\nimport type { MetricsOptions } from '@dd/metrics-plugin/types';\nimport type * as metrics from '@dd/metrics-plugin';\nimport type { OutputOptions } from '@dd/output-plugin/types';\nimport type * as output from '@dd/output-plugin';\nimport type { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\n// #imports-injection-marker\n/* eslint-enable arca/import-ordering */\nimport type { BodyInit } from 'undici-types';\nimport type { UnpluginOptions } from 'unplugin';\n\nimport type { ALL_ENVS, SUPPORTED_BUNDLERS } from './constants';\n\nexport type Assign<A, B> = Omit<A, keyof B> & B;\nexport type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };\nexport type IterableElement<IterableType extends Iterable<unknown>> =\n IterableType extends Iterable<infer ElementType> ? ElementType : never;\n\nexport interface RepositoryData {\n commit: {\n hash: string;\n message: string;\n author: {\n name: string;\n email: string;\n date: string;\n };\n committer: {\n name: string;\n email: string;\n date: string;\n };\n };\n hash: string;\n branch: string;\n remote: string;\n trackedFilesMatcher: TrackedFilesMatcher;\n}\n\nexport type FileReport = { filepath: string; name: string; size: number; type: string };\nexport type Input = FileReport & { dependencies: Set<Input>; dependents: Set<Input> };\nexport type Output = FileReport & { inputs: (Input | Output)[] };\nexport type Entry = Output & { outputs: Output[] };\n\nexport type SerializedEntry = Assign<Entry, { inputs: string[]; outputs: string[] }>;\nexport type SerializedInput = Assign<Input, { dependencies: string[]; dependents: string[] }>;\nexport type SerializedOutput = Assign<Output, { inputs: string[] }>;\n\nexport interface Metric {\n metric: string;\n type: 'count' | 'size' | 'duration';\n points: [number, number][];\n tags: string[];\n}\n\nexport interface MetricToSend extends Metric {\n toSend: boolean;\n}\n\nexport type Log = {\n bundler?: BundlerName;\n pluginName: string;\n type: LogLevel;\n message: string;\n time: number;\n};\nexport type LogTags = string[];\nexport type Timer = {\n label: string;\n pluginName: string;\n spans: { start: number; end?: number; tags: LogTags }[];\n tags: LogTags;\n total: number;\n logLevel: LogLevel;\n};\n\nexport type BuildMetadata = {\n name?: string;\n};\n\nexport type BuildReport = {\n bundler: GlobalData['bundler'];\n errors: GlobalStores['errors'];\n warnings: GlobalStores['warnings'];\n logs: GlobalStores['logs'];\n timings: GlobalStores['timings'];\n metadata: GlobalData['metadata'];\n entries?: Entry[];\n inputs?: Input[];\n outputs?: Output[];\n start?: number;\n end?: number;\n duration?: number;\n writeDuration?: number;\n};\n\n// A JSON safe version of the report.\nexport type SerializedBuildReport = Assign<\n BuildReport,\n {\n entries: SerializedEntry[];\n inputs: SerializedInput[];\n outputs: SerializedOutput[];\n }\n>;\n\nexport type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];\nexport type BundlerReport = GlobalData['bundler'] & {\n outDir: string;\n rawConfig?: any;\n};\n\nexport type InjectedValue = string | (() => Promise<string>);\nexport enum InjectPosition {\n BEFORE,\n MIDDLE,\n AFTER,\n}\nexport type ToInjectItem = {\n type: 'file' | 'code';\n value: InjectedValue;\n position?: InjectPosition;\n fallback?: ToInjectItem;\n};\n\nexport type TimeLogger = {\n timer: Timer;\n resume: (startTime?: number) => void;\n end: (endTime?: number) => void;\n pause: (pauseTime?: number, warn?: boolean) => void;\n tag: (tags: LogTags, opts?: { span?: boolean }) => void;\n};\n\n// The rest parameter is a LogLevel or a boolean to auto start the timer.\nexport type TimeLog = (\n label: string,\n opts?: { level?: LogLevel; start?: boolean | number; log?: boolean; tags?: LogTags },\n) => TimeLogger;\nexport type GetLogger = (name: string) => Logger;\nexport type LogOptions = { forward?: boolean };\nexport type LoggerFn = (text: any, opts?: LogOptions) => void;\nexport type Logger = {\n getLogger: GetLogger;\n time: TimeLog;\n error: LoggerFn;\n warn: LoggerFn;\n info: LoggerFn;\n debug: LoggerFn;\n};\ntype RestContext = string | string[] | number | boolean;\nexport type LogData = Record<string, RestContext | Record<string, RestContext>>;\nexport type DdLogOptions = {\n message: string;\n context?: LogData;\n};\nexport type Env = (typeof ALL_ENVS)[number];\nexport type TriggerHook<R> = <K extends keyof CustomHooks>(\n name: K,\n ...args: Parameters<NonNullable<CustomHooks[K]>>\n) => R;\nexport type GlobalContext = {\n asyncHook: TriggerHook<Promise<void[]>>;\n auth: AuthOptionsWithDefaults;\n build: BuildReport;\n bundler: BundlerReport;\n buildRoot: string;\n env: GlobalData['env'];\n getLogger: GetLogger;\n git?: RepositoryData;\n hook: TriggerHook<void>;\n inject: (item: ToInjectItem) => void;\n pluginNames: string[];\n plugins: (PluginOptions | CustomPluginOptions)[];\n queue: (promise: Promise<any>) => void;\n sendLog: (args: DdLogOptions) => Promise<void>;\n start: number;\n version: GlobalData['version'];\n};\n\nexport type FactoryMeta = {\n bundler: any;\n version: string;\n};\n\nexport type HookFn<T extends Array<any>> = (...args: T) => void;\nexport type AsyncHookFn<T extends Array<any>> = (...args: T) => Promise<void> | void;\nexport type CustomHooks = {\n asyncTrueEnd?: () => Promise<void> | void;\n buildRoot?: HookFn<[string]>;\n init?: HookFn<[GlobalContext]>;\n buildReport?: AsyncHookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n metrics?: AsyncHookFn<[Set<Metric>]>;\n syncTrueEnd?: () => void;\n timings?: AsyncHookFn<[TimingsReport]>;\n};\n\nexport type PluginOptions = Assign<\n UnpluginOptions & CustomHooks,\n {\n name: PluginName;\n }\n>;\n\nexport type CustomPluginOptions = Assign<\n PluginOptions,\n {\n name: string;\n }\n>;\n\nexport type GetPluginsArg = {\n bundler: any;\n context: GlobalContext;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n};\nexport type GetPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetCustomPlugins = (arg: GetPluginsArg) => CustomPluginOptions[];\nexport type GetInternalPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetWrappedPlugins = (arg: GetPluginsArg) => (PluginOptions | CustomPluginOptions)[];\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\nexport type AuthOptions = {\n apiKey?: string;\n appKey?: string;\n site?: string;\n};\n\nexport type AuthOptionsWithDefaults = WithRequired<AuthOptions, 'site'>;\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n enableGit?: boolean;\n logLevel?: LogLevel;\n}\n\nexport interface Options extends BaseOptions {\n // Each product should have a unique entry.\n // #types-injection-marker\n [errorTracking.CONFIG_KEY]?: ErrorTrackingOptions;\n [metrics.CONFIG_KEY]?: MetricsOptions;\n [output.CONFIG_KEY]?: OutputOptions;\n [rum.CONFIG_KEY]?: RumOptions;\n // #types-injection-marker\n customPlugins?: GetCustomPlugins;\n}\n\nexport type OptionsWithDefaults = Assign<\n Assign<Options, Required<BaseOptions>>,\n { auth: AuthOptionsWithDefaults }\n>;\n\nexport type PluginName = `datadog-${Lowercase<string>}-plugin`;\n\ntype Data = { data?: BodyInit; headers?: Record<string, string> };\nexport type RequestOpts = {\n url: string;\n auth?: Pick<AuthOptions, 'apiKey' | 'appKey'>;\n method?: string;\n getData?: () => Promise<Data> | Data;\n type?: 'json' | 'text';\n onRetry?: (error: Error, attempt: number) => void;\n retries?: number;\n minTimeout?: number;\n maxTimeout?: number;\n};\n\nexport type ResolvedEntry = { name?: string; resolved: string; original: string };\n\nexport interface LocalAppendOptions {\n contentType: string;\n filename: string;\n}\n\nexport type FileValidity = {\n empty: boolean;\n exists: boolean;\n};\n\nexport type GlobalData = {\n bundler: {\n name: BundlerName;\n version: string;\n };\n env: Env;\n metadata: BuildMetadata;\n packageName: string;\n version: string;\n};\n\nexport type GlobalStores = {\n errors: string[];\n logs: Log[];\n queue: Promise<any>[];\n timings: Timer[];\n warnings: string[];\n};\n\n/* Legacy Telemetry types */\nexport type TAP_TYPES = 'default' | 'async' | 'promise';\n\nexport interface ValueContext {\n type: string;\n name: string;\n value?: string;\n}\n\nexport interface Value {\n start: number;\n end: number;\n duration: number;\n context?: ValueContext[];\n type?: TAP_TYPES; // Only for webpack.\n}\n\nexport interface Timing {\n name: string;\n duration: number;\n increment: number;\n events: {\n [key: string]: {\n name: string;\n values: Value[];\n };\n };\n}\nexport type TimingsMap = Map<string, Timing>;\n\nexport interface TimingsReport {\n tapables?: TimingsMap;\n loaders?: TimingsMap;\n modules?: TimingsMap;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'rum' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-rum-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-rum-privacy-plugin' as const;\nexport const PRIVACY_HELPERS_FILE_NAME = 'privacy-helpers';\nexport const PRIVACY_HELPERS_MODULE_ID = `\\0datadog:${PRIVACY_HELPERS_FILE_NAME}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { buildTransformOptions } from './transform';\nimport type { PrivacyOptionsWithDefaults } from './types';\n\nexport const getPrivacyPlugin = (\n pluginOptions: PrivacyOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n\n const transformOptions = buildTransformOptions(\n pluginOptions.helperCodeExpression,\n context.bundler.name,\n );\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: pluginOptions.include,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n try {\n return instrument({ id, code }, transformOptions);\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { GlobalContext, InjectedValue } from '@dd/core/types';\n\nimport type { RumOptionsWithDefaults, RumOptionsWithSdk } from './types';\n\ntype RumAppResponse = {\n data: {\n attributes: {\n client_token: string;\n };\n };\n};\n\nconst getContent = (opts: RumOptionsWithDefaults) => {\n return `DD_RUM.init({${JSON.stringify(opts.sdk).replace(/(^{|}$)/g, '')}});\n`;\n};\n\nexport const getInjectionValue = (\n options: RumOptionsWithSdk,\n context: GlobalContext,\n): InjectedValue => {\n const sdkOpts = options.sdk;\n // We already have the clientToken, we can inject it directly.\n if (sdkOpts.clientToken) {\n return getContent(options);\n }\n\n // Let's try and fetch the clientToken from the API.\n if (!context.auth.apiKey || !context.auth.appKey) {\n throw new Error(\n 'Missing \"auth.apiKey\" and/or \"auth.appKey\" to fetch \"rum.sdk.clientToken\".',\n );\n }\n\n // Return the value as an async function so it gets resolved during buildStart.\n return async () => {\n let clientToken: string;\n try {\n // Fetch the client token from the API.\n const appResponse = await doRequest<RumAppResponse>({\n url: `https://api.${context.auth.site}/api/v2/rum/applications/${sdkOpts.applicationId}`,\n type: 'json',\n auth: context.auth,\n });\n\n clientToken = appResponse.data?.attributes?.client_token;\n } catch (e: any) {\n // Could not fetch the clientToken.\n // Let's crash the build.\n throw new Error(`Could not fetch the clientToken: ${e.message}`);\n }\n\n // Still no clientToken.\n if (!clientToken) {\n throw new Error('Missing clientToken in the API response.');\n }\n\n return getContent({\n ...options,\n sdk: {\n clientToken,\n ...sdkOpts,\n },\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options, OptionsWithDefaults } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';\n\nexport const validateOptions = (\n options: OptionsWithDefaults,\n log: Logger,\n): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options);\n\n errors.push(...sdkResults.errors);\n errors.push(...privacyResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n // Build the final configuration.\n const toReturn: RumOptionsWithDefaults = {\n enable: !!options[CONFIG_KEY],\n ...options[CONFIG_KEY],\n sdk: undefined,\n privacy: undefined,\n };\n\n // Fill in the defaults.\n if (sdkResults.config) {\n toReturn.sdk = sdkResults.config;\n }\n\n if (privacyResults.config) {\n toReturn.privacy = privacyResults.config;\n\n log.debug(\n `datadog-rum-privacy plugin options: ${JSON.stringify(toReturn.privacy, (_, value) => {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n })}`,\n { forward: true },\n );\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SDKOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SDKOptionsWithDefaults> = {\n errors: [],\n };\n if (!validatedOptions.sdk) {\n return toReturn;\n }\n\n // Validate the configuration.\n if (!validatedOptions.sdk.applicationId) {\n toReturn.errors.push(`Missing ${red('applicationId')} in the SDK configuration.`);\n }\n\n // Check if we have all we need to fetch the client token if necessary.\n if ((!options.auth.apiKey || !options.auth.appKey) && !validatedOptions.sdk.clientToken) {\n toReturn.errors.push(\n `Missing ${red('\"auth.apiKey\"')} and/or ${red('\"auth.appKey\"')} to fetch missing client token.`,\n );\n }\n\n const sdkWithDefault: SDKOptionsWithDefaults = {\n applicationId: 'unknown_application_id',\n allowUntrustedEvents: false,\n compressIntakeRequests: false,\n defaultPrivacyLevel: 'mask',\n enablePrivacyForActionName: false,\n sessionReplaySampleRate: 0,\n sessionSampleRate: 100,\n silentMultipleInit: false,\n site: 'datadoghq.com',\n startSessionReplayRecordingManually: false,\n storeContextsAcrossPages: false,\n telemetrySampleRate: 20,\n traceSampleRate: 100,\n trackingConsent: 'granted',\n trackLongTasks: false,\n trackResources: false,\n trackUserInteractions: false,\n trackViewsManually: false,\n };\n\n // Save the config.\n toReturn.config = {\n ...sdkWithDefault,\n ...validatedOptions.sdk,\n };\n\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOptionsWithDefaults> => {\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<PrivacyOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.privacy) {\n const privacyWithDefault: PrivacyOptionsWithDefaults = {\n // Exclude dependencies and preval files from being transformed. Files starting with\n // special characters are likely to be virtual libraries and are excluded to avoid loading them.\n exclude: [/\\/node_modules\\//, /\\.preval\\./, /^[!@#$%^&*()=+~`-]/],\n include: [/\\.(?:c|m)?(?:j|t)sx?$/],\n addToDictionaryFunctionName: '$',\n helperCodeExpression: `/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()`,\n };\n\n toReturn.config = {\n ...privacyWithDefault,\n ...validatedOptions.privacy,\n };\n }\n\n return toReturn;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginOptions, GetPlugins } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { getPrivacyPlugin } from './privacy';\nimport { getInjectionValue } from './sdk';\nimport type { RumOptions, RumOptionsWithSdk, RumPublicApi, RumInitConfiguration } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n RumOptions: RumOptions;\n RumPublicApi: RumPublicApi;\n RumInitConfiguration: RumInitConfiguration;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n // Verify configuration.\n const validatedOptions = validateOptions(options, log);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is not enabled, return an empty array.\n if (!validatedOptions.enable) {\n return plugins;\n }\n\n // NOTE: These files are built from \"@dd/tools/rollupConfig.mjs\" and available in the distributed package.\n if (validatedOptions.sdk) {\n // Inject the SDK from the CDN.\n context.inject({\n type: 'file',\n // Using MIDDLE otherwise it's not executed in context.\n position: InjectPosition.MIDDLE,\n // This file is being built alongside the bundler plugin.\n value: path.join(__dirname, './rum-browser-sdk.js'),\n });\n\n // Inject the SDK Initialization.\n context.inject({\n type: 'code',\n position: InjectPosition.MIDDLE,\n value: getInjectionValue(validatedOptions as RumOptionsWithSdk, context),\n });\n }\n\n if (validatedOptions.privacy) {\n // Add the privacy plugin.\n context.inject({\n type: 'file',\n position: InjectPosition.BEFORE,\n value: path.join(__dirname, './privacy-helpers.js'),\n });\n const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n plugins.push(privacyPlugin);\n }\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { InstrumentationOptions } from '@datadog/js-instrumentation-wasm';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(\n helperCodeExpression: string,\n bundlerName: string,\n): InstrumentationOptions {\n const transformOptions: InstrumentationOptions = {\n privacy: {\n addToDictionaryHelper: {\n expression: {\n code: helperCodeExpression,\n },\n },\n },\n };\n if (['esbuild', 'webpack', 'rspack'].includes(bundlerName)) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n return transformOptions;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-analytics-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getAnalyticsPlugins: GetInternalPlugins = ({ context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const buildStartFn = async () => {\n try {\n await context.sendLog({\n message: 'Build started',\n context: {\n plugins: context.pluginNames,\n },\n });\n } catch (e: unknown) {\n // We don't want to break anything in case of error.\n log.debug(`Could not submit data to Datadog: ${e}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n async buildStart() {\n // Only send logs in production.\n if (context.env !== 'production') {\n return;\n }\n\n // Use the queue so it doesn't block the build process.\n context.queue(buildStartFn());\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-async-queue-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME };\n\nexport const getAsyncQueuePlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context, stores } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const errors: string[] = [];\n\n // Initialize the queue function\n context.queue = (promise: Promise<any>) => {\n // Wrap the promise to catch errors immediately\n const wrappedPromise = promise.catch((error: any) => {\n errors.push(error.message || error.toString());\n });\n stores.queue.push(wrappedPromise);\n };\n\n return [\n {\n name: PLUGIN_NAME,\n asyncTrueEnd: async () => {\n // Await for all promises to finish processing.\n await Promise.all(stores.queue);\n if (errors.length > 0) {\n log.error(\n `Error occurred while processing async queue:\\n ${errors.join('\\n ')}`,\n );\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BundlerName, GlobalContext, Logger, ResolvedEntry } from '@dd/core/types';\nimport type { PluginBuild } from 'esbuild';\nimport { glob } from 'glob';\n\n// https://esbuild.github.io/api/#glob-style-entry-points\n// Exported only for testing purposes.\nexport const getAllEntryFiles = (filepath: string): string[] => {\n if (!filepath.includes('*')) {\n return [filepath];\n }\n\n const files = glob.sync(filepath);\n return files;\n};\n\n// Parse, resolve and return all the entries of esbuild.\nexport const getEsbuildEntries = async (\n build: PluginBuild,\n context: GlobalContext,\n log: Logger,\n): Promise<ResolvedEntry[]> => {\n const entries: { name?: string; resolved: string; original: string }[] = [];\n const entryPoints = build.initialOptions.entryPoints;\n const entryPaths: { name?: string; path: string }[] = [];\n const resolutionErrors: string[] = [];\n\n if (Array.isArray(entryPoints)) {\n for (const entry of entryPoints) {\n const fullPath = entry && typeof entry === 'object' ? entry.in : entry;\n entryPaths.push({ path: fullPath });\n }\n } else if (entryPoints && typeof entryPoints === 'object') {\n entryPaths.push(\n ...Object.entries(entryPoints).map(([name, filepath]) => ({ name, path: filepath })),\n );\n }\n\n // Resolve all the paths.\n const proms = entryPaths\n .flatMap((entry) =>\n getAllEntryFiles(entry.path).map<[{ name?: string; path: string }, string]>((p) => [\n entry,\n p,\n ]),\n )\n .map(async ([entry, p]) => {\n const result = await build.resolve(p, {\n kind: 'entry-point',\n resolveDir: context.buildRoot,\n });\n\n if (result.errors.length) {\n resolutionErrors.push(...result.errors.map((e) => e.text));\n }\n\n if (result.path) {\n // Store them for later use.\n entries.push({\n name: entry.name,\n resolved: result.path,\n original: entry.path,\n });\n }\n });\n\n for (const resolutionError of resolutionErrors) {\n log.error(resolutionError);\n }\n\n await Promise.all(proms);\n return entries;\n};\n\n// From a bundler's name, is it part of the \"xpack\" family?\nexport const isXpack = (bundlerName: BundlerName) => ['rspack', 'webpack'].includes(bundlerName);\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\nimport { existsSync } from './fs';\n\n// Will only prepend the cwd if not already there.\nexport const getAbsolutePath = (cwd: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath.startsWith(cwd) || path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.resolve(cwd, filepath);\n};\n\n// Find the highest package.json from the current directory.\nexport const getHighestPackageJsonDir = (currentDir: string): string | undefined => {\n let highestPackage;\n let current = getAbsolutePath(process.cwd(), currentDir);\n let currentDepth = current.split(path.sep).length;\n while (currentDepth > 0) {\n const packagePath = path.resolve(current, `package.json`);\n // Check if package.json exists in the current directory.\n if (existsSync(packagePath)) {\n highestPackage = current;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n currentDepth--;\n }\n return highestPackage;\n};\n\nexport const getClosest = (currentDir: string, filename: string) => {\n let closest;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closest) {\n const filepath = path.resolve(current, filename);\n // Check if it exists in the current directory.\n if (existsSync(filepath)) {\n closest = filepath;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n\n // Exit if we reach the root directory.\n if ([path.sep, ''].includes(current)) {\n break;\n }\n }\n return closest;\n};\n\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n return getClosest(currentDir, 'package.json');\n};\n\n// From a list of path, return the nearest common directory.\nexport const getNearestCommonDirectory = (dirs: string[], cwd?: string) => {\n const dirsToCompare = [...dirs];\n\n const splitPaths = dirsToCompare.map((dir) => {\n const absolutePath = getAbsolutePath(cwd || process.cwd(), dir);\n return absolutePath.split(path.sep);\n });\n\n // Use the shortest length for faster results.\n const minLength = splitPaths.length ? Math.min(...splitPaths.map((parts) => parts.length)) : 0;\n const commonParts = [];\n\n for (let i = 0; i < minLength; i++) {\n // We use the first path as our basis.\n const component = splitPaths[0][i];\n if (splitPaths.every((parts) => parts[i] === component)) {\n commonParts.push(component);\n } else {\n break;\n }\n }\n\n return commonParts.length > 0\n ? // Use \"|| path.sep\" to cover for the [''] case.\n commonParts.join(path.sep) || path.sep\n : path.sep;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\n// Will match any last part of a path after a dot or slash and is a word character.\nconst EXTENSION_RX = /\\.(?!.*(?:\\.|\\/|\\\\))(\\w{1,})/g;\n\n// Will match any type of query characters.\n// \"?\" or \"%3F\" (url encoded \"?\") or \"|\"\nconst QUERY_RX = /(\\?|%3F|\\|)+/gi;\n\nconst getExtension = (filepath: string) => {\n // Reset RX first.\n EXTENSION_RX.lastIndex = 0;\n return EXTENSION_RX.exec(filepath)?.[1];\n};\n\nexport const getType = (name: string): string => {\n if (name === 'unknown') {\n return name;\n }\n\n if (name.includes('webpack/runtime')) {\n return 'runtime';\n }\n\n return getExtension(cleanPath(name)) || 'unknown';\n};\n\nconst BUNDLER_SPECIFICS = ['unknown', 'commonjsHelpers.js', `vite${path.sep}preload-helper.js`];\n// Make list of paths unique, remove the current file and particularities.\nexport const cleanReport = <T = string>(\n report: Set<string>,\n filepath: string,\n filter?: (p: string) => T,\n) => {\n const cleanedReport: Set<T> = new Set();\n for (const reportFilepath of report) {\n const cleanedPath = cleanPath(reportFilepath);\n if (\n // Don't add injections.\n isInjectionFile(reportFilepath) ||\n // Don't add itself into it.\n cleanedPath === filepath ||\n // Remove common specific files injected by bundlers.\n BUNDLER_SPECIFICS.includes(cleanedPath)\n ) {\n continue;\n }\n\n if (filter) {\n const filteredValue = filter(cleanedPath);\n if (filteredValue) {\n cleanedReport.add(filteredValue);\n }\n } else {\n cleanedReport.add(cleanedPath as unknown as T);\n }\n }\n return cleanedReport;\n};\n\n// Clean a path from its query parameters and leading invisible characters.\n// Careful with this and webpack/rspack as loaders may add \"|\" before and after the filepath.\nexport const cleanPath = (filepath: string) => {\n return (\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading, invisible characters,\n // sometimes added in rollup by the commonjs plugin.\n .replace(/^[^\\w\\s.,!@#$%^&*()=+~`\\-/\\\\]+/, '')\n );\n};\n\n// From two file paths, remove the common path prefix.\nexport const removeCommonPrefix = (filepath1: string, filepath2: string) => {\n const filepath2Split = filepath2.split(path.sep);\n const commonPath = filepath1\n .split(path.sep)\n .filter((part, index) => part === filepath2Split[index])\n .join(path.sep);\n return filepath1.replace(commonPath, '');\n};\n\n// Extract a name from a path based on the context (outDir and cwd).\nexport const cleanName = (absoluteOutDir: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath === 'unknown') {\n return filepath;\n }\n\n if (filepath.includes('webpack/runtime')) {\n return filepath.replace('webpack/runtime/', '').replace(/ +/g, '-');\n }\n\n return (\n removeCommonPrefix(\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!,\n absoluteOutDir,\n )\n // Remove node_modules path.\n .split('node_modules')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading dots and slashes.\n .replace(/^((\\.\\.?)?[/\\\\])+/g, '')\n );\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n Output,\n PluginOptions,\n ResolvedEntry,\n} from '@dd/core/types';\nimport path from 'path';\n\nimport { cleanName, getType } from './helpers';\n\n// Re-index metafile data for easier access.\nconst reIndexMeta = <T>(obj: Record<string, T>, buildRoot: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(buildRoot, key);\n return [newKey, value];\n }),\n );\n\nexport const getEsbuildPlugin = (context: GlobalContext, log: Logger): PluginOptions['esbuild'] => {\n return {\n setup(build) {\n const entryNames = new Map();\n let resolvedEntries: ResolvedEntry[] = [];\n const timeBuildReport = log.time('build report', { start: false });\n\n build.onStart(async () => {\n // Start from a clean slate.\n entryNames.clear();\n resolvedEntries = [];\n\n timeBuildReport.resume();\n const timeEntries = log.time('process entries');\n // Store entry names based on the configuration.\n resolvedEntries.push(...(await getEsbuildEntries(build, context, log)));\n for (const entry of resolvedEntries) {\n const cleanedName = cleanName(context.bundler.outDir, entry.resolved);\n if (entry.name) {\n entryNames.set(cleanedName, entry.name);\n } else {\n entryNames.set(cleanedName, cleanedName);\n }\n }\n timeEntries.end();\n timeBuildReport.pause();\n });\n\n build.onEnd(async (result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const outDir = context.bundler.outDir;\n const buildRoot = context.buildRoot;\n for (const error of result.errors) {\n context.build.errors.push(error.text);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.text);\n }\n timeCollect.end();\n\n if (!result.metafile) {\n const warning = 'Missing metafile from build report.';\n context.build.warnings.push(warning);\n log.warn(warning);\n return;\n }\n\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n const timeIndex = log.time('indexing metafile data');\n const metaInputsIndexed = reIndexMeta(result.metafile.inputs, buildRoot);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, buildRoot);\n timeIndex.end();\n\n // From a proxy entry point, created by our injection plugin, get the real path.\n const getRealPathFromInjectionProxy = (entryPoint: string): string => {\n if (!isInjectionFile(entryPoint)) {\n return entryPoint;\n }\n\n const metaInput = metaInputsIndexed[getAbsolutePath(buildRoot, entryPoint)];\n if (!metaInput) {\n return entryPoint;\n }\n\n // Get the first non-injection import.\n const actualImport = metaInput.imports.find(\n (imp) => !isInjectionFile(imp.path),\n );\n if (!actualImport) {\n return entryPoint;\n }\n\n return actualImport.path;\n };\n\n // Loop through inputs.\n const timeInputs = log.time('looping through inputs');\n for (const [filename, input] of Object.entries(result.metafile.inputs)) {\n if (isInjectionFile(filename)) {\n continue;\n }\n\n const filepath = getAbsolutePath(buildRoot, filename);\n const name = cleanName(outDir, filename);\n\n const file: Input = {\n name,\n filepath,\n dependents: new Set(),\n dependencies: new Set(),\n size: input.bytes,\n type: getType(filename),\n };\n reportInputsIndexed[filepath] = file;\n inputs.push(file);\n }\n timeInputs.end();\n\n // Loop through outputs.\n const timeOutputs = log.time('looping through outputs');\n for (const [filename, output] of Object.entries(result.metafile.outputs)) {\n const fullPath = getAbsolutePath(buildRoot, filename);\n const cleanedName = cleanName(outDir, fullPath);\n // Get inputs of this output.\n const inputFiles: Input[] = [];\n for (const inputName of Object.keys(output.inputs)) {\n if (isInjectionFile(inputName)) {\n continue;\n }\n\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, inputName)];\n if (!inputFound) {\n log.debug(`Input ${inputName} not found for output ${cleanedName}`);\n continue;\n }\n\n inputFiles.push(inputFound);\n }\n\n // When splitting, esbuild creates an empty entryPoint wrapper for the chunk.\n // It has no inputs, but still relates to its entryPoint.\n if (output.entryPoint && !inputFiles.length) {\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, output.entryPoint)];\n if (!inputFound) {\n log.debug(\n `Input ${output.entryPoint} not found for output ${cleanedName}`,\n );\n continue;\n }\n inputFiles.push(inputFound);\n }\n\n const file: Output = {\n name: cleanedName,\n filepath: fullPath,\n inputs: inputFiles,\n size: output.bytes,\n type: getType(fullPath),\n };\n\n reportOutputsIndexed[fullPath] = file;\n\n // Store sourcemaps for later filling.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n }\n\n outputs.push(file);\n\n if (!output.entryPoint) {\n continue;\n }\n\n // The entryPoint may have been altered by our injection plugin.\n const inputFile =\n reportInputsIndexed[\n getAbsolutePath(\n buildRoot,\n getRealPathFromInjectionProxy(output.entryPoint),\n )\n ];\n\n if (inputFile) {\n // In the case of \"splitting: true\", all the files are considered entries to esbuild.\n // Not to us.\n // Verify we have listed it as an entry earlier.\n if (!entryNames.get(inputFile.name)) {\n continue;\n }\n\n const entry = {\n ...file,\n name: entryNames.get(inputFile.name) || inputFile.name,\n outputs: [file],\n size: file.size,\n };\n\n tempEntryFiles.push(entry);\n }\n }\n timeOutputs.end();\n\n // Loop through sourcemaps.\n const timeSourcemaps = log.time('looping through sourcemaps');\n for (const sourcemap of tempSourcemaps) {\n const outputFilepath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[outputFilepath];\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n\n // Build our references for the entries.\n const references = {\n inputs: {\n report: reportInputsIndexed,\n meta: metaInputsIndexed,\n },\n outputs: {\n report: reportOutputsIndexed,\n meta: metaOutputsIndexed,\n },\n };\n\n // There are some exceptions we want to ignore.\n const FILE_EXCEPTIONS_RX = /(<runtime>|https:|file:|data:|#)/g;\n const isFileSupported = (filePath: string) => {\n if (isInjectionFile(filePath) || filePath.match(FILE_EXCEPTIONS_RX)) {\n return false;\n }\n return true;\n };\n\n // Go through all imports.\n const getAllImports = <T extends Input | Output>(\n filePath: string,\n ref: typeof references.inputs | typeof references.outputs,\n allImports: Record<string, T> = {},\n ): Record<string, T> => {\n if (!isFileSupported(filePath)) {\n return allImports;\n }\n\n const file = ref.report[filePath];\n if (!file) {\n log.debug(`Could not find report's ${filePath}`);\n return allImports;\n }\n\n // Check if we already have processed it.\n if (allImports[file.filepath]) {\n return allImports;\n }\n\n allImports[file.filepath] = file as T;\n\n const metaFile = ref.meta[filePath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${filePath}`);\n return allImports;\n }\n\n // If there are no imports, we can return what we have.\n if (!metaFile.imports || !metaFile.imports.length) {\n return allImports;\n }\n\n for (const imported of metaFile.imports) {\n const isRelative = imported.path.match(/^\\.\\.?\\//);\n const root = isRelative ? path.dirname(filePath) : buildRoot;\n const absoluteImportPath = getAbsolutePath(root, imported.path);\n\n // We need to register external imports, as this is the first time we see them.\n if (imported.external) {\n if (isFileSupported(imported.path)) {\n // If it's an absolute external import,\n // we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteImportPath : imported.path;\n\n // But we can still add it to the report.\n const inputFile: Input = references.inputs.report[filepath] || {\n filepath,\n name: cleanName(outDir, imported.path),\n size: 0,\n type: 'external',\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if ('dependencies' in file) {\n // file is an Input, so we add the external to its dependencies,\n // and we add file to the external's dependents.\n inputFile.dependents.add(file);\n file.dependencies.add(inputFile);\n }\n\n if ('inputs' in file && !file.inputs.includes(inputFile)) {\n // file is an Output, so we add the external to its inputs.\n file.inputs.push(inputFile);\n }\n\n if (!inputs.includes(inputFile)) {\n inputs.push(inputFile);\n }\n\n references.inputs.report[filepath] = inputFile;\n allImports[inputFile.filepath] = inputFile as T;\n }\n // We can't follow external imports.\n continue;\n }\n\n // Look for the other inputs.\n getAllImports<T>(absoluteImportPath, ref, allImports);\n }\n\n return allImports;\n };\n\n // Loop through entries.\n const timeEntries = log.time('looping through entries');\n // TODO This is slightly underperformant due to getAllImports' recursivity.\n for (const entryFile of tempEntryFiles) {\n const entryInputs: Record<string, Input> = {};\n const entryOutputs: Record<string, Output> = {};\n\n // Do inputs for this entry.\n for (const input of entryFile.inputs) {\n getAllImports<Input>(input.filepath, references.inputs, entryInputs);\n }\n\n // Do outputs for this entry.\n for (const outputFile of entryFile.outputs) {\n getAllImports<Output>(\n outputFile.filepath,\n references.outputs,\n entryOutputs,\n );\n }\n\n entryFile.inputs = Object.values(entryInputs);\n entryFile.outputs = Object.values(entryOutputs);\n entryFile.size = entryFile.outputs.reduce(\n (acc, output) => acc + output.size,\n 0,\n );\n\n entries.push(entryFile);\n }\n timeEntries.end();\n\n // Loop through all inputs to aggregate dependencies and dependents.\n const timeDeps = log.time('aggregate dependencies and dependents');\n for (const input of inputs) {\n // The metafile does not contain external dependencies.\n // So we can only fill in their dependents.\n if (input.type === 'external') {\n continue;\n }\n\n const metaFile = references.inputs.meta[input.filepath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${input.name}`);\n continue;\n }\n\n for (const dependency of metaFile.imports) {\n if (!isFileSupported(dependency.path)) {\n continue;\n }\n\n const isRelative = dependency.path.match(/^\\.?\\.\\//);\n const root = isRelative ? path.dirname(input.filepath) : buildRoot;\n const absoluteDependencyPath = getAbsolutePath(root, dependency.path);\n\n let dependencyFile: Input | undefined;\n if (dependency.external) {\n // If it's an absolute external import, we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteDependencyPath : dependency.path;\n // In case of externals, we use their path directly.\n dependencyFile = references.inputs.report[filepath];\n } else {\n dependencyFile = references.inputs.report[absoluteDependencyPath];\n }\n\n if (!dependencyFile) {\n log.debug(\n `Could not find input file of ${dependency.path} imported from ${input.name}`,\n );\n continue;\n }\n\n input.dependencies.add(dependencyFile);\n // Add itself to the dependency's dependents.\n dependencyFile.dependents.add(input);\n }\n }\n timeDeps.end();\n\n context.build.outputs = outputs;\n context.build.inputs = inputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, Entry, GlobalContext, Input, Output, PluginOptions } from '@dd/core/types';\n\nimport { cleanName, cleanPath, cleanReport, getType } from './helpers';\n\nexport const getRollupPlugin = (context: GlobalContext, log: Logger): PluginOptions['rollup'] => {\n const timeModuleParsing = log.time('module parsing', { start: false });\n const timeBuildReport = log.time('build report', { start: false });\n const timeEntries = log.time('filling entries', { start: false });\n const timeInputsOutputs = log.time('filling inputs and outputs', { start: false });\n const timeCompleteDeps = log.time('completing dependencies and dependents', { start: false });\n const timeDeps = log.time('filling dependencies and dependents', { start: false });\n const timeSourcemaps = log.time('filling sourcemaps inputs', { start: false });\n\n const inputs: Map<string, Input> = new Map();\n const outputs: Map<string, Output> = new Map();\n const entries: Map<string, Entry> = new Map();\n const importsReport: Map<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = new Map();\n\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds.\n // It's useful with a dev server or a build with multiple outputs.\n importsReport.clear();\n inputs.clear();\n outputs.clear();\n entries.clear();\n },\n onLog(level, logItem) {\n if (level === 'warn') {\n context.build.warnings.push(logItem.message || logItem.toString());\n }\n },\n renderError(error) {\n if (error) {\n context.build.errors.push(error.message);\n }\n },\n moduleParsed(info) {\n timeModuleParsing.resume();\n // Store import infos.\n const cleanId = cleanPath(info.id);\n const report = importsReport.get(cleanId) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n // Clean new dependencies and dependents.\n const newDependencies = cleanReport(\n new Set([...info.dynamicallyImportedIds, ...info.importedIds]),\n cleanId,\n );\n\n const newDependents = cleanReport(\n new Set([...info.dynamicImporters, ...info.importers]),\n cleanId,\n );\n\n for (const dependent of newDependents) {\n report.dependents.add(dependent);\n }\n\n for (const dependency of newDependencies) {\n report.dependencies.add(dependency);\n }\n\n importsReport.set(cleanId, report);\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n // This can be called multiple times depending on the number of output configured.\n writeBundle(options, bundle) {\n timeBuildReport.resume();\n const outDir = options.dir\n ? getAbsolutePath(context.buildRoot, options.dir)\n : context.bundler.outDir;\n\n const tempEntryFiles: Set<Entry> = new Set();\n const tempSourcemaps: Set<Output> = new Set();\n const tempOutputsImports: Map<string, Output> = new Map();\n\n // Complete the importsReport with missing dependents and dependencies.\n timeCompleteDeps.resume();\n for (const [filepath, { dependencies, dependents }] of importsReport) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n const report = importsReport.get(cleanedDependency) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependents.has(filepath)) {\n continue;\n }\n\n report.dependents.add(filepath);\n importsReport.set(cleanedDependency, report);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n const report = importsReport.get(cleanedDependent) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependencies.has(filepath)) {\n continue;\n }\n\n report.dependencies.add(filepath);\n importsReport.set(cleanedDependent, report);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n timeInputsOutputs.resume();\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(outDir, filename);\n const size =\n 'code' in asset\n ? Buffer.byteLength(asset.code, 'utf8')\n : Buffer.byteLength(asset.source, 'utf8');\n\n const file: Output = outputs.get(filepath) || {\n name: filename,\n filepath,\n inputs: [],\n size,\n type: getType(filename),\n };\n\n // Store sourcemaps for later filling.\n // Because we may not have reported its input yet.\n if (file.type === 'map') {\n tempSourcemaps.add(file);\n }\n\n if ('modules' in asset) {\n for (const [modulepath, module] of Object.entries(asset.modules)) {\n // We don't want to include commonjs wrappers and proxies that are like:\n // \\u0000{{path}}?commonjs-proxy\n if (cleanPath(modulepath) !== modulepath) {\n continue;\n }\n const moduleFile: Input = inputs.get(modulepath) || {\n name: cleanName(outDir, modulepath),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: modulepath,\n // Since we store as input, we use the originalLength.\n size: module.originalLength,\n type: getType(modulepath),\n };\n file.inputs.push(moduleFile);\n inputs.set(moduleFile.filepath, moduleFile);\n }\n }\n\n // Add imports as inputs.\n // These are external imports since they are declared in the output file.\n if ('imports' in asset) {\n for (const importName of asset.imports) {\n const cleanedImport = cleanPath(importName);\n if (!importsReport.has(cleanedImport)) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports.set(getAbsolutePath(outDir, cleanedImport), file);\n continue;\n }\n\n if (inputs.has(cleanedImport)) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = inputs.get(cleanedImport) || {\n name: cleanName(outDir, importName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: cleanedImport,\n // Since it's external, we don't have the size.\n size: 0,\n type: 'external',\n };\n file.inputs.push(importFile);\n inputs.set(importFile.filepath, importFile);\n }\n }\n\n // Store entries for later filling.\n // As we may not have reported its outputs and inputs yet.\n if ('isEntry' in asset && asset.isEntry) {\n tempEntryFiles.add({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n outputs.set(file.filepath, file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of tempOutputsImports) {\n const outputReport = outputs.get(filepath);\n if (!outputReport) {\n log.debug(`Could not find the output report for ${filepath}.`);\n continue;\n }\n\n if (!output.inputs.includes(outputReport)) {\n output.inputs.push(outputReport);\n }\n }\n\n // Fill in inputs' dependencies and dependents.\n timeDeps.resume();\n for (const [filepath, input] of inputs) {\n const importReport = importsReport.get(filepath);\n if (!importReport) {\n log.debug(`Could not find the import report for ${input.name}.`);\n continue;\n }\n\n for (const dependency of importReport.dependencies) {\n const foundInput = inputs.get(dependency);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(outDir, dependency)} of ${input.name}`,\n );\n continue;\n }\n input.dependencies.add(foundInput);\n }\n\n for (const dependent of importReport.dependents) {\n const foundInput = inputs.get(dependent);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(outDir, dependent)} of ${input.name}`,\n );\n continue;\n }\n input.dependents.add(foundInput);\n }\n }\n timeDeps.end();\n\n // Fill in sourcemaps' inputs if necessary\n if (tempSourcemaps.size) {\n timeSourcemaps.resume();\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = outputs.get(outputPath);\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n }\n\n // Gather all outputs from a filepath, following imports.\n const getAllOutputs = (\n filepath: string,\n allOutputs: Map<string, Output> = new Map(),\n ) => {\n // We already processed it.\n if (allOutputs.has(filepath)) {\n return allOutputs;\n }\n const filename = cleanName(outDir, filepath);\n\n // Get its output.\n const foundOutput = outputs.get(filepath);\n if (!foundOutput) {\n // If it's been reported in the inputs, it means it's an external here.\n // Do not log about externals, we don't expect to find them.\n if (!inputs.has(filename)) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs.set(filepath, foundOutput);\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(outDir, filepath)];\n if (!asset) {\n log.debug(`Could not find asset for ${filename}`);\n return allOutputs;\n }\n\n // Imports are stored in two different places.\n const imports = [];\n if ('imports' in asset) {\n imports.push(...asset.imports);\n }\n if ('dynamicImports' in asset) {\n imports.push(...asset.dynamicImports);\n }\n\n for (const importName of imports) {\n getAllOutputs(getAbsolutePath(outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n timeEntries.resume();\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Array.from(entryOutputs.values());\n\n // NOTE: This might not be as accurate as expected, some inputs could be side-effects.\n // Rollup doesn't provide a way to get the imports of an input.\n entryFile.inputs = Array.from(\n new Set(entryFile.outputs.flatMap((output) => output.inputs)),\n );\n entryFile.size = entryFile.outputs.reduce((acc, output) => acc + output.size, 0);\n\n if (entries.has(entryFile.filepath)) {\n log.debug(\n `Entry \"${entryFile.name}\":\"${cleanName(outDir, entryFile.filepath)}\" already reported.`,\n );\n }\n\n entries.set(entryFile.filepath, entryFile);\n }\n timeEntries.pause();\n timeBuildReport.pause();\n },\n async closeBundle() {\n context.build.inputs = Array.from(inputs.values());\n context.build.outputs = Array.from(outputs.values());\n context.build.entries = Array.from(entries.values());\n\n timeEntries.end();\n timeBuildReport.end();\n\n await context.asyncHook('buildReport', context.build);\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n IterableElement,\n Output,\n PluginOptions,\n} from '@dd/core/types';\n\nimport { cleanName, cleanPath, getType } from './helpers';\n\nexport const getXpackPlugin =\n (\n context: GlobalContext,\n PLUGIN_NAME: string,\n log: Logger,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n let inputs: Input[] = [];\n let outputs: Output[] = [];\n let entries: Entry[] = [];\n\n // Types for the xpack hooks.\n type Compilation = Parameters<Parameters<typeof compiler.hooks.thisCompilation.tap>[1]>[0];\n type Module = IterableElement<Compilation['modules']>;\n type Dependency = IterableElement<IterableElement<Module['blocks']>['dependencies']>;\n type Chunk = IterableElement<Compilation['chunks']>;\n type IndexedModule = {\n identifier: Module['identifier'];\n dependencies: Dependency[];\n blocks: any[];\n externalType: unknown;\n external: unknown;\n };\n\n // Some indexes to help with the report generation.\n const reportInputsIndexed: Map<string, Input> = new Map();\n const reportOutputsIndexed: Map<string, Output> = new Map();\n const modulesPerFile: Map<string, Set<string>> = new Map();\n const moduleIndex: Map<string, IndexedModule> = new Map();\n\n // Some temporary holders to later fill in more data.\n const tempSourcemaps: Output[] = [];\n const tempDeps: Map<string, { dependencies: Set<string>; dependents: Set<string> }> =\n new Map();\n\n const timeBuildReport = log.time('build report', { start: false });\n\n const isModuleSupported = (moduleIdentifier?: string): boolean => {\n return (\n // Ignore unidentified modules and runtimes.\n !!moduleIdentifier &&\n !moduleIdentifier.startsWith('webpack/runtime') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack.\n * 1. Build a dependency graph from all the initial modules once they're finished\n * In afterEmit, modules are concatenated and obfuscated.\n * 2. Once the build is finished and emitted, we can compute the outputs and the entries.\n */\n\n // Clear the data in case we have multiple compilations (dev server, etc...).\n const clear = () => {\n inputs = [];\n outputs = [];\n entries = [];\n reportInputsIndexed.clear();\n reportOutputsIndexed.clear();\n moduleIndex.clear();\n tempDeps.clear();\n };\n\n const cleanExternalName = (name: string) => {\n // Removes \"external \" prefix and surrounding quotes from external dependency names\n // Example: 'external var \"lodash\"' -> 'lodash'\n return name.replace(/(^external[^\"]+\"|\"$)/g, '');\n };\n\n // Index the module by its identifier, resource, request, rawRequest, and userRequest.\n const getKeysToIndex = (mod: Module): Set<string> => {\n const indexes = new Set<string>();\n\n const keysOfModuleToIndexOn: string[] = [\n 'rawRequest',\n 'resource',\n 'request',\n 'userRequest',\n ];\n\n const indexValue = (value: string) => {\n const valueToIndex = cleanPath(value);\n indexes.add(valueToIndex);\n // RSpack only use \"external ...\" for external dependencies.\n // So we need to clean and add the actual name to the index too.\n if (valueToIndex.startsWith('external ')) {\n indexes.add(cleanExternalName(valueToIndex));\n }\n };\n\n // Start by indexing the identifier.\n indexValue(mod.identifier());\n\n // Then index all the other keys.\n for (const key of keysOfModuleToIndexOn) {\n const value = mod[key as keyof Module];\n if (key && key in mod && typeof value === 'string') {\n indexValue(value);\n }\n }\n\n return indexes;\n };\n\n const createIndexedModule = (mod: Module): IndexedModule => {\n const id = mod.identifier();\n return {\n identifier: () => id,\n dependencies: 'dependencies' in mod ? [...mod.dependencies] : [],\n blocks: 'blocks' in mod ? [...mod.blocks] : [],\n externalType: 'externalType' in mod ? mod.externalType : undefined,\n external: 'external' in mod ? mod.external : undefined,\n };\n };\n\n const indexModule = (mod: Module) => {\n const moduleToIndex = createIndexedModule(mod);\n const keysToIndex = getKeysToIndex(mod);\n for (const key of keysToIndex) {\n if (moduleIndex.has(key)) {\n // Update the existing module.\n const previousModule = moduleIndex.get(key)!;\n previousModule.dependencies.push(...(moduleToIndex.dependencies || []));\n previousModule.blocks.push(...(moduleToIndex.blocks || []));\n } else {\n moduleIndex.set(key, moduleToIndex);\n }\n }\n };\n\n // Aggregate all dependencies from a module.\n const getAllDependencies = (\n module: Module | Dependency | Module['blocks'][number],\n dependencies: Dependency[] = [],\n ) => {\n if ('dependencies' in module) {\n for (const dependency of module.dependencies) {\n dependencies.push(dependency);\n getAllDependencies(dependency, dependencies);\n }\n }\n\n if ('blocks' in module) {\n for (const block of module.blocks) {\n getAllDependencies(block, dependencies);\n }\n }\n\n return dependencies;\n };\n\n const getModuleFromDep = (mod: Module, dep: Dependency): IndexedModule | undefined => {\n if ('request' in dep && dep.request) {\n const cleanRequest = cleanPath(dep.request);\n if (moduleIndex.has(cleanRequest)) {\n return moduleIndex.get(cleanRequest);\n }\n if (mod.context) {\n const cleanedPath = getAbsolutePath(cleanPath(mod.context), cleanRequest);\n if (moduleIndex.has(cleanedPath)) {\n return moduleIndex.get(cleanedPath);\n }\n }\n }\n };\n\n const isExternal = (mod: Module | IndexedModule) => {\n if ('externalType' in mod && mod.externalType) {\n return true;\n }\n if ('external' in mod && mod.external) {\n return true;\n }\n if (mod.identifier?.().startsWith('external ')) {\n return true;\n }\n return false;\n };\n\n // Intercept the compilation to then get the modules.\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n clear();\n // Intercept the modules to build the dependency graph.\n compilation.hooks.finishModules.tap(\n PLUGIN_NAME,\n (finishedModules: Iterable<Module>) => {\n timeBuildReport.resume();\n const timeGraph = log.time('dependency graph');\n // First loop to create indexes.\n const timeIndex = log.time('indexing modules');\n for (const module of finishedModules) {\n indexModule(module);\n }\n timeIndex.end();\n\n // Second loop to create the dependency graph.\n const timeInputs = log.time('building inputs');\n for (const module of finishedModules) {\n const moduleIdentifier = module.identifier();\n const moduleName = cleanName(context.bundler.outDir, moduleIdentifier);\n const dependencies: Set<string> = new Set(\n getAllDependencies(module)\n .map((dep) => {\n const mod = getModuleFromDep(module, dep);\n\n // Ignore those we can't identify.\n if (!mod?.identifier()) {\n return false;\n }\n\n const identifier = mod.identifier();\n\n // Only what we support.\n if (!isModuleSupported(identifier)) {\n return false;\n }\n\n // Don't add itself as a dependency.\n if (identifier === moduleIdentifier) {\n return false;\n }\n\n return isExternal(mod)\n ? cleanExternalName(identifier)\n : identifier;\n })\n .filter(Boolean) as string[],\n );\n\n if (!isModuleSupported(moduleIdentifier)) {\n continue;\n }\n\n // Create dependents relationships.\n const moduleDeps = tempDeps.get(moduleIdentifier) || {\n dependents: new Set(),\n dependencies: new Set(),\n };\n for (const depIdentifier of dependencies) {\n const depDeps = tempDeps.get(depIdentifier) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n depDeps.dependents.add(moduleIdentifier);\n moduleDeps.dependencies.add(depIdentifier);\n tempDeps.set(depIdentifier, depDeps);\n }\n\n // Store the dependencies.\n tempDeps.set(moduleIdentifier, moduleDeps);\n\n // Store the inputs.\n const file: Input = isExternal(module)\n ? {\n size: 0,\n name: cleanExternalName(moduleName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: 'external',\n }\n : {\n size: module.size() || 0,\n name: moduleName,\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: getType(moduleIdentifier),\n };\n\n inputs.push(file);\n reportInputsIndexed.set(moduleIdentifier, file);\n\n // If it's an external dependency, we also need to index it by its cleaned name.\n if (isExternal(module)) {\n reportInputsIndexed.set(cleanExternalName(moduleIdentifier), file);\n }\n }\n timeInputs.end();\n\n // Assign dependencies and dependents.\n const timeAssign = log.time('assigning dependencies and dependents');\n for (const input of inputs) {\n const depsReport = tempDeps.get(input.filepath);\n\n if (!depsReport) {\n log.debug(`Could not find dependency report for ${input.name}`);\n continue;\n }\n\n for (const dependency of depsReport.dependencies) {\n const depInput = reportInputsIndexed.get(dependency);\n if (!depInput) {\n log.debug(`Could not find input of dependency ${dependency}`);\n continue;\n }\n input.dependencies.add(depInput);\n }\n\n for (const dependent of depsReport.dependents) {\n const depInput = reportInputsIndexed.get(dependent);\n if (!depInput) {\n log.debug(`Could not find input of dependent ${dependent}`);\n continue;\n }\n input.dependents.add(depInput);\n }\n }\n timeAssign.end();\n timeGraph.end();\n timeBuildReport.pause();\n },\n );\n });\n\n compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (result: Compilation) => {\n timeBuildReport.resume();\n const chunks = result.chunks;\n const assets = result.getAssets();\n\n const getChunkFiles = (chunk: Chunk) => {\n return [...(chunk.files || []), ...(chunk.auxiliaryFiles || [])].map((f: string) =>\n getAbsolutePath(context.bundler.outDir, f),\n );\n };\n\n const timeChunks = log.time('indexing chunks');\n const chunkGraph = result.chunkGraph;\n for (const chunk of chunks) {\n const files = getChunkFiles(chunk);\n\n const chunkModules =\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n (chunkGraph?.getChunkModules(chunk) || [])\n .flatMap((m) => {\n // modules exists but isn't in the types.\n return 'modules' in m && Array.isArray(m.modules)\n ? m.modules.map((m2) => m2.identifier())\n : m.identifier();\n })\n .filter(isModuleSupported);\n\n for (const file of files) {\n if (getType(file) === 'map') {\n continue;\n }\n const fileModules = modulesPerFile.get(file) || new Set();\n for (const module of chunkModules) {\n fileModules.add(module);\n }\n modulesPerFile.set(file, fileModules);\n }\n }\n timeChunks.end();\n\n // Build outputs\n const timeOutputs = log.time('building outputs');\n for (const asset of assets) {\n const file: Output = {\n size: asset.source.size() || 0,\n name: asset.name,\n inputs: [],\n filepath: getAbsolutePath(context.bundler.outDir, asset.name),\n type: getType(asset.name),\n };\n\n reportOutputsIndexed.set(file.filepath, file);\n outputs.push(file);\n\n // If it's a sourcemap, store it, we'll fill its input when we'll have\n // referenced all the outputs.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n continue;\n }\n\n // Add the inputs.\n const fileModules = modulesPerFile.get(file.filepath);\n if (!fileModules) {\n log.debug(`Could not find modules for ${file.name}`);\n continue;\n }\n\n for (const moduleIdentifier of fileModules) {\n const inputFound = reportInputsIndexed.get(moduleIdentifier);\n if (!inputFound) {\n log.debug(`Could not find input of ${moduleIdentifier}`);\n continue;\n }\n file.inputs.push(inputFound);\n }\n }\n timeOutputs.end();\n\n // Fill in inputs for sourcemaps.\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputFound = reportOutputsIndexed.get(\n sourcemap.filepath.replace(/\\.map$/, ''),\n );\n\n if (!outputFound) {\n log.debug(`Output not found for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(outputFound);\n }\n timeSourcemaps.end();\n\n // Build entries\n const timeEntries = log.time('building entries');\n for (const [name, entrypoint] of result.entrypoints) {\n const entryOutputs: Map<string, Output> = new Map();\n const entryInputs: Map<string, Input> = new Map();\n let size = 0;\n const entryFiles = entrypoint.chunks.flatMap(getChunkFiles);\n\n // FIXME This is not a 100% reliable way to get the entry filename.\n const entryFilename = entrypoint.chunks\n // Get the chunks that have entry modules.\n .filter(\n (chunk: Chunk) =>\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk) || false,\n )\n // Get the files of those chunks.\n .flatMap((c) => Array.from(c.files))\n // Filter the ones that includes the entry name.\n .filter(\n (f) => f.includes(name) || (entrypoint.name && f.includes(entrypoint.name)),\n )\n // Only keep JS files.\n .find((f) => getType(f) === 'js');\n\n for (const file of entryFiles) {\n const outputFound = reportOutputsIndexed.get(file);\n if (!file || !outputFound) {\n log.debug(`Could not find output of ${JSON.stringify(file)}`);\n continue;\n }\n if (outputFound.type !== 'map' && !entryOutputs.has(outputFound.name)) {\n entryOutputs.set(outputFound.name, outputFound);\n // We know it's not a map, so we cast it.\n for (const input of outputFound.inputs as Input[]) {\n if (!entryInputs.has(input.filepath)) {\n entryInputs.set(input.filepath, input);\n }\n }\n // We don't want to include sourcemaps in the sizing.\n size += outputFound.size;\n }\n }\n\n const file: Entry = {\n name,\n filepath: entryFilename\n ? getAbsolutePath(context.bundler.outDir, entryFilename)\n : 'unknown',\n size,\n inputs: Array.from(entryInputs.values()),\n outputs: Array.from(entryOutputs.values()),\n type: entryFilename ? getType(entryFilename) : 'unknown',\n };\n\n entries.push(file);\n }\n timeEntries.end();\n\n // Save everything in the context.\n for (const error of result.errors) {\n context.build.errors.push(error.message);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.message);\n }\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions } from '@dd/core/types';\n\nimport { getEsbuildPlugin } from './esbuild';\nimport { getRollupPlugin } from './rollup';\nimport { getXpackPlugin } from './xpack';\n\nexport const PLUGIN_NAME = 'datadog-build-report-plugin';\n\nexport const getBuildReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n esbuild: getEsbuildPlugin(context, log),\n rspack: getXpackPlugin(context, PLUGIN_NAME, log),\n webpack: getXpackPlugin(context, PLUGIN_NAME, log),\n // Vite and Rollup have the same API.\n vite: getRollupPlugin(context, log) as PluginOptions['vite'],\n rollup: getRollupPlugin(context, log),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath, getNearestCommonDirectory } from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\nimport type { InputOptions, OutputOptions } from 'rollup';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\nexport const getAbsoluteOutDir = (buildRoot: string, outDir?: string) => {\n if (!outDir) {\n return '';\n }\n\n return path.isAbsolute(outDir) ? outDir : path.resolve(buildRoot, outDir);\n};\n\nexport const getOutDirsFromOutputs = (\n outputOptions?: OutputOptions | OutputOptions[],\n): string[] => {\n if (!outputOptions) {\n return [];\n }\n\n const normalizedOutput = Array.isArray(outputOptions) ? outputOptions : [outputOptions];\n return normalizedOutput\n .map((o) => {\n if (o.dir) {\n return o.dir;\n }\n if (o.file) {\n return path.dirname(o.file);\n }\n })\n .filter(Boolean) as string[];\n};\n\nexport const getIndirsFromInputs = (options: InputOptions) => {\n const inDirs: Set<string> = new Set();\n\n if (options.input) {\n const normalizedInput = Array.isArray(options.input)\n ? options.input\n : typeof options.input === 'object'\n ? Object.values(options.input)\n : [options.input];\n\n for (const input of normalizedInput) {\n if (typeof input !== 'string') {\n throw new Error('Invalid input type');\n }\n inDirs.add(path.dirname(input));\n }\n }\n\n return Array.from(inDirs);\n};\n\nconst xpackPlugin: (context: GlobalContext) => PluginOptions['webpack'] & PluginOptions['rspack'] =\n (context) => (compiler) => {\n context.bundler.rawConfig = compiler.options;\n\n if (compiler.options.output?.path) {\n // While webpack doesn't allow for non-absolute paths,\n // rspack does, and will fallback to use process.cwd().\n context.bundler.outDir = getAbsoluteOutDir(process.cwd(), compiler.options.output.path);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.buildRoot = compiler.options.context;\n }\n context.hook('buildRoot', context.buildRoot);\n };\n\nconst vitePlugin = (context: GlobalContext): PluginOptions['vite'] => {\n return {\n configResolved(config) {\n context.bundler.rawConfig = config;\n // If we have the outDir configuration from Vite.\n let outDir = config.build?.outDir ?? 'dist';\n // We need to know if we have a rollup output configuration.\n // As it will override Vite's outDir and root.\n const output = config.build?.rollupOptions?.output as\n | OutputOptions\n | OutputOptions[]\n | undefined;\n\n const outDirs = getOutDirsFromOutputs(output);\n\n // Vite will fallback to process.cwd() if no root is provided.\n context.buildRoot = config.root ?? process.cwd();\n // Vite will fallback to process.cwd() if we have an output configuration with dirs.\n if (output && outDirs.length) {\n // Now compute the nearest common directory from the output directories.\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Make sure the outDir is absolute.\n context.bundler.outDir = getAbsoluteOutDir(context.buildRoot, outDir);\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n },\n };\n};\n\n// TODO: Add universal config report with list of plugins (names), loaders.\nexport const getBundlerReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const bundlerReportPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: {\n setup(build) {\n context.bundler.rawConfig = build.initialOptions;\n\n if (build.initialOptions.absWorkingDir) {\n context.buildRoot = build.initialOptions.absWorkingDir;\n }\n\n if (build.initialOptions.outdir) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n build.initialOptions.outdir,\n );\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n path.dirname(build.initialOptions.outfile),\n );\n }\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n },\n },\n webpack: xpackPlugin(context),\n rspack: xpackPlugin(context),\n vite: vitePlugin(context),\n rollup: {\n options(options) {\n // By default, with relative paths, rollup will use process.cwd() as the CWD.\n let outDir;\n if ('output' in options) {\n const outDirs = getOutDirsFromOutputs(\n options.output as OutputOptions | OutputOptions[],\n );\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Compute input directories if possible.\n const inDirs = getIndirsFromInputs(options);\n\n if (outDir) {\n context.bundler.outDir = getAbsolutePath(process.cwd(), outDir);\n const computedCwd = getNearestCommonDirectory(\n [outDir, ...inDirs],\n process.cwd(),\n );\n // If the computed CWD is the root directory, it means we could not compute it,\n // so we fallback to process.cwd().\n context.buildRoot = computedCwd === path.sep ? process.cwd() : computedCwd;\n } else {\n // Fallback to process.cwd()/dist as it is rollup's default.\n context.buildRoot = getNearestCommonDirectory(inDirs, process.cwd());\n context.bundler.outDir = path.resolve(process.cwd(), 'dist');\n }\n\n context.hook('buildRoot', context.buildRoot);\n },\n buildStart(options) {\n // Save the resolved options.\n context.bundler.rawConfig = options;\n },\n renderStart(outputOptions) {\n // Save the resolved options.\n context.bundler.rawConfig.outputs = context.bundler.rawConfig.outputs || [];\n context.bundler.rawConfig.outputs.push(outputOptions);\n context.hook('bundlerReport', context.bundler);\n\n // Verify that the output directory is the same as the one computed in the options hook.\n const outDirs = getOutDirsFromOutputs(outputOptions);\n // Rollup always uses process.cwd() as the CWD.\n const outDir = getNearestCommonDirectory(outDirs, process.cwd());\n if (!outDir.startsWith(context.bundler.outDir)) {\n log.info(\n 'The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.',\n );\n }\n },\n },\n };\n\n return [bundlerReportPlugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-custom-hooks-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, TriggerHook } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getCustomHooksPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const executeHooks =\n (async: boolean): TriggerHook<Promise<void[]> | void> =>\n (hookName, ...hookArgs) => {\n const timeHook = log.time(`execution | ${hookName}`, {\n tags: ['type:custom-hook', `hook:${hookName}`],\n });\n const errors: string[] = [];\n const proms: Promise<void>[] = [];\n\n for (const plugin of context.plugins) {\n if (!(hookName in plugin)) {\n continue;\n }\n\n const hookFn = plugin[hookName];\n if (typeof hookFn !== 'function') {\n errors.push(\n `Plugin \"${plugin.name}\" has an invalid hook type for \"${hookName}\". [${typeof hookFn}]`,\n );\n continue;\n }\n\n try {\n // Re-typing to take over typechecking.\n const result: any = hookFn(...(hookArgs as any[]));\n\n if (result instanceof Promise) {\n // Confirm that the result is not an unsupported Promise.\n if (!async) {\n errors.push(\n `Plugin \"${plugin.name}\" returned a promise on the non async hook \"${hookName}\".`,\n );\n }\n proms.push(result);\n }\n } catch (e) {\n errors.push(`Plugin \"${plugin.name}\" errored on hook \"${hookName}\". [${e}]`);\n }\n }\n\n if (errors.length > 0) {\n for (const error of errors) {\n log.error(error);\n }\n throw new Error(`Some plugins errored during the hook execution.`);\n }\n\n return Promise.all(proms).finally(() => timeHook.end());\n };\n\n // Define the hook functions.\n context.hook = executeHooks(false);\n // Define the asyncHook functions.\n context.asyncHook = executeHooks(true) as TriggerHook<Promise<void[]>>;\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFileSync } from '@dd/core/helpers/fs';\n\n// TrackedFilesMatcher can compute the list of tracked files related to a particular sourcemap.\n// The current implementation simply returns all tracked files whose filename is found inside\n// the sourcemap 'sources' field.\n// It is used so that we don't send every tracked files to the backend since most won't be of any use\n// for a particular sourcemap.\nexport class TrackedFilesMatcher {\n // A map with tracked filenames as key and the related tracked file paths as value.\n private trackedFilenames: Map<string, string[]>;\n\n constructor(trackedFiles: string[]) {\n this.trackedFilenames = new Map<string, string[]>();\n for (const f of trackedFiles) {\n const filename = this.getFilename(f);\n const list = this.trackedFilenames.get(filename);\n if (list) {\n list.push(f);\n } else {\n this.trackedFilenames.set(filename, new Array<string>(f));\n }\n }\n }\n\n private displaySource(src: string) {\n if (src.length <= 40) {\n return src;\n }\n return `[...]${src.slice(-35)}`;\n }\n\n // Looks up the sources declared in the sourcemap and return a list of related tracked files.\n public matchSourcemap(\n srcmapPath: string,\n onSourcesNotFound: (reason: string) => void,\n ): string[] | undefined {\n const buff = readFileSync(srcmapPath);\n const srcmapObj = JSON.parse(buff);\n if (!srcmapObj.sources) {\n onSourcesNotFound(`Missing 'sources' field in sourcemap.`);\n return undefined;\n }\n const sources = srcmapObj.sources as string[];\n if (sources.length === 0) {\n onSourcesNotFound(`Empty 'sources' field in sourcemap.`);\n return undefined;\n }\n const filtered = this.matchSources(sources);\n if (filtered.length === 0) {\n onSourcesNotFound(\n `${sources.map(this.displaySource).join(', ')} not in the tracked files.`,\n );\n return undefined;\n }\n\n return filtered;\n }\n\n public matchSources(sources: string[]): string[] {\n let filtered: string[] = [];\n const filenameAlreadyMatched = new Set<string>();\n for (const source of sources) {\n const filename = this.getFilename(source);\n if (filenameAlreadyMatched.has(filename)) {\n continue;\n }\n filenameAlreadyMatched.add(filename);\n const trackedFiles = this.trackedFilenames.get(filename);\n if (trackedFiles) {\n filtered = filtered.concat(trackedFiles);\n }\n }\n\n return filtered;\n }\n\n // Return a list of all tracked files\n public rawTrackedFilesList() {\n let rawList: string[] = [];\n this.trackedFilenames.forEach((value) => {\n rawList = rawList.concat(value);\n });\n\n return rawList;\n }\n\n // Extract the filename from a path.\n //\n // We are removing any suffix that is after the character '?'. The only reason this is done\n // is because we noticed that a non-negligible (~5%) amount of source paths from our customers\n // source maps contained query parameters.\n // We are assuming that the files may not actually be named with the interrogation mark but that\n // it is only an artifact of the build process. The query parameters look random. It looks\n // like it may be used as a trick to force a web browser to reload the file content.\n // The only side effect of doing that operation is that more tracked files paths may be sent\n // alongside the sourcemap which is not a problem.\n // Example: webpack:///./src/folder/ui/select.vue?821e\n private getFilename(s: string): string {\n let start = s.lastIndexOf('/');\n if (start === -1) {\n start = 0;\n } else {\n start++;\n }\n let end = s.lastIndexOf('?');\n if (end === -1 || end <= start) {\n end = s.length;\n }\n\n return s.substring(start, end);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { filterSensitiveInfoFromRepositoryUrl } from '@dd/core/helpers/strings';\nimport type { RepositoryData } from '@dd/core/types';\nimport type { SimpleGit, BranchSummary } from 'simple-git';\nimport { simpleGit } from 'simple-git';\n\nimport { TrackedFilesMatcher } from './trackedFilesMatcher';\n\n// Returns a configured SimpleGit.\nexport const newSimpleGit = async (cwd?: string): Promise<SimpleGit> => {\n const options = {\n baseDir: cwd || process.cwd(),\n binary: 'git',\n // We are invoking at most 3 git commands at the same time.\n maxConcurrentProcesses: 3,\n };\n try {\n // Attempt to set the baseDir to the root of the repository so the 'git ls-files' command\n // returns the tracked files paths relative to the root of the repository.\n const git = simpleGit(options);\n const root = await git.revparse('--show-toplevel');\n options.baseDir = root;\n } catch {\n // Ignore exception as it will fail if we are not inside a git repository.\n }\n\n return simpleGit(options);\n};\n\n// Returns the remote of the current repository.\nexport const gitRemote = async (git: SimpleGit): Promise<string> => {\n const remotes = await git.getRemotes(true);\n if (remotes.length === 0) {\n throw new Error('No git remotes available');\n }\n const defaultRemote = await getDefaultRemoteName(git);\n\n for (const remote of remotes) {\n if (remote.name === defaultRemote) {\n return filterSensitiveInfoFromRepositoryUrl(remote.refs.push);\n }\n }\n\n // Falling back to picking the first remote in the list if the default remote is not found.\n return filterSensitiveInfoFromRepositoryUrl(remotes[0].refs.push);\n};\n\nexport const getDefaultRemoteName = async (git: SimpleGit): Promise<string> => {\n try {\n return (await git.getConfig('clone.defaultRemoteName'))?.value ?? 'origin';\n } catch (e) {\n return 'origin';\n }\n};\n\n// Returns the hash of the current repository.\nexport const gitHash = async (git: SimpleGit): Promise<string> => git.revparse('HEAD');\n\n// Returns the tracked files of the current repository.\nexport const gitTrackedFiles = async (git: SimpleGit): Promise<string[]> => {\n const files = await git.raw('ls-files');\n\n return files.split(/\\r\\n|\\r|\\n/);\n};\n\nexport const gitBranch = async (git: SimpleGit): Promise<BranchSummary> => git.branch();\n\nexport const gitMessage = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%s']);\n\nexport const gitAuthorAndCommitter = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%an,%ae,%aI,%cn,%ce,%cI']);\n\nexport const gitRepositoryURL = async (git: SimpleGit): Promise<string> =>\n git.listRemote(['--get-url']);\n\n// Returns the current hash and remote as well as a TrackedFilesMatcher.\n//\n// To obtain the list of tracked files paths tied to a specific sourcemap, invoke the 'matchSourcemap' method.\nexport const getRepositoryData = async (git: SimpleGit): Promise<RepositoryData> => {\n // Invoke git commands to retrieve some informations and tracked files.\n // We're using Promise.all instead of Promise.allSettled since we want to fail early if\n // any of the promises fails.\n\n const proms: [\n ReturnType<typeof gitHash>,\n ReturnType<typeof gitBranch>,\n ReturnType<typeof gitMessage>,\n ReturnType<typeof gitAuthorAndCommitter>,\n ReturnType<typeof gitTrackedFiles>,\n ReturnType<typeof gitRemote>,\n ] = [\n gitHash(git),\n gitBranch(git),\n gitMessage(git),\n gitAuthorAndCommitter(git),\n gitTrackedFiles(git),\n gitRemote(git),\n ];\n\n const [hash, branch, message, authorAndCommitter, trackedFiles, remote] =\n await Promise.all(proms);\n\n const [authorName, authorEmail, authorDate, committerName, committerEmail, committerDate] =\n authorAndCommitter.split(',').map((item) => item.trim());\n\n const data: RepositoryData = {\n commit: {\n author: {\n name: authorName,\n email: authorEmail,\n date: authorDate,\n },\n committer: {\n name: committerName,\n email: committerEmail,\n date: committerDate,\n },\n message: message.trim(),\n hash,\n },\n hash,\n branch: branch.current,\n remote: remote.trim(),\n trackedFilesMatcher: new TrackedFilesMatcher(trackedFiles),\n };\n\n return data;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getClosest } from '@dd/core/helpers/paths';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\nimport path from 'path';\n\nimport { getRepositoryData, newSimpleGit } from './helpers';\n\nexport const PLUGIN_NAME = 'datadog-git-plugin';\n\nexport const getGitPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { options, context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const timeGit = log.time('get git information', { start: false });\n const processGit = async (gitDir: string) => {\n try {\n const repositoryData = await getRepositoryData(\n await newSimpleGit(path.dirname(gitDir!)),\n );\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\n } catch (e: any) {\n log.error(`Could not get git information: ${e.message}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n buildRoot(buildRoot) {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n timeGit.resume();\n // Add git information to the context.\n const gitDir = getClosest(buildRoot, '.git');\n if (!gitDir) {\n log.warn('No .git directory found, skipping git plugin.');\n return;\n }\n\n // buildRoot hook is sync because xpack can't make it async.\n // So we queue the async part of the plugin.\n context.queue(processGit(gitDir));\n } catch (e: any) {\n // We don't want to have the build fail for this.\n log.error(`Could not get git information: ${e.message}`);\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const PLUGIN_NAME = 'datadog-injection-plugin';\nexport const DISTANT_FILE_RX = /^https?:\\/\\//;\nexport const BEFORE_INJECTION = `// begin injection by Datadog build plugins`;\nexport const AFTER_INJECTION = `// end injection by Datadog build plugins`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { doRequest } from '@dd/core/helpers/request';\nimport { truncateString } from '@dd/core/helpers/strings';\nimport type { Logger, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\n\nimport { AFTER_INJECTION, BEFORE_INJECTION, DISTANT_FILE_RX } from './constants';\nimport type { ContentsToInject } from './types';\n\nconst MAX_TIMEOUT_IN_MS = 5000;\n\nexport const getInjectedValue = async (item: ToInjectItem): Promise<string> => {\n if (typeof item.value === 'function') {\n return item.value();\n }\n\n return item.value;\n};\n\nexport const processDistantFile = async (\n url: string,\n timeout: number = MAX_TIMEOUT_IN_MS,\n): Promise<string> => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n doRequest<string>({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url,\n }).finally(() => {\n if (timeout) {\n clearTimeout(timeoutId);\n }\n }),\n new Promise<string>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error('Timeout'));\n }, timeout);\n }),\n ]);\n};\n\nexport const processLocalFile = async (\n filepath: string,\n cwd: string = process.cwd(),\n): Promise<string> => {\n const absolutePath = getAbsolutePath(cwd, filepath);\n return readFile(absolutePath);\n};\n\nexport const processItem = async (\n item: ToInjectItem,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<string | undefined> => {\n let result: string | undefined;\n const value = await getInjectedValue(item);\n try {\n if (item.type === 'file') {\n if (value.match(DISTANT_FILE_RX)) {\n result = await processDistantFile(value);\n } else {\n result = await processLocalFile(value, cwd);\n }\n } else if (item.type === 'code') {\n // TODO: Confirm the code actually executes without errors.\n result = value;\n } else {\n throw new Error(`Invalid item type \"${item.type}\", only accepts \"code\" or \"file\".`);\n }\n } catch (error: any) {\n const itemId = `${item.type} - ${truncateString(value)}`;\n if (item.fallback) {\n // In case of any error, we'll fallback to next item in queue.\n log.info(`Fallback for \"${itemId}\": ${error.toString()}`);\n result = await processItem(item.fallback, log, cwd);\n } else {\n // Or return an empty string.\n log.warn(`Failed \"${itemId}\": ${error.toString()}`);\n }\n }\n\n return result;\n};\n\nexport const processInjections = async (\n toInject: Map<string, ToInjectItem>,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<Map<string, { position: InjectPosition; value: string }>> => {\n const toReturn: Map<string, { position: InjectPosition; value: string }> = new Map();\n\n // Processing sequentially all the items.\n for (const [id, item] of toInject.entries()) {\n // eslint-disable-next-line no-await-in-loop\n const value = await processItem(item, log, cwd);\n if (value) {\n toReturn.set(id, { value, position: item.position || InjectPosition.BEFORE });\n }\n }\n\n return toReturn;\n};\n\nexport const getContentToInject = (contentToInject: Map<string, string>) => {\n if (contentToInject.size === 0) {\n return '';\n }\n\n const stringToInject = Array.from(contentToInject.values())\n // Wrapping it in order to avoid variable name collisions.\n .map((content) => `(() => {${content}})();`)\n .join('\\n\\n');\n return `${BEFORE_INJECTION}\\n${stringToInject}\\n${AFTER_INJECTION}`;\n};\n\n// Prepare and fetch the content to inject.\nexport const addInjections = async (\n log: Logger,\n toInject: Map<string, ToInjectItem>,\n contentsToInject: ContentsToInject,\n cwd: string = process.cwd(),\n) => {\n const results = await processInjections(toInject, log, cwd);\n // Redistribute the content to inject in the right place.\n for (const [id, value] of results.entries()) {\n contentsToInject[value.position].set(id, value.value);\n }\n};\n\nexport interface NodeSystemError extends Error {\n code: string;\n}\n\nexport const isNodeSystemError = (e: unknown): e is NodeSystemError => {\n return e instanceof Error && 'code' in e;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { outputFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, PluginOptions, GlobalContext, ResolvedEntry } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, isNodeSystemError } from './helpers';\nimport type { ContentsToInject } from './types';\n\nconst fsp = fs.promises;\n\nexport const getEsbuildPlugin = (\n log: Logger,\n context: GlobalContext,\n contentsToInject: ContentsToInject,\n): PluginOptions['esbuild'] => ({\n setup(build) {\n const { onStart, onResolve, onLoad, onEnd, esbuild, initialOptions } = build;\n const entries: ResolvedEntry[] = [];\n // Use a narrower identifier to avoid cross build collisions.\n const id = context.bundler.name;\n const filePath = `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`;\n const tmpDir = fs.realpathSync(os.tmpdir());\n const absoluteFilePath = path.resolve(tmpDir, filePath);\n const injectionRx = new RegExp(`${filePath}$`);\n\n // InjectPosition.MIDDLE\n // Inject the file in the build using the \"inject\" option.\n // NOTE: This is made \"safer\" for sub-builds by actually creating the file.\n const initialInject = initialOptions.inject;\n initialOptions.inject = initialInject ? [...initialInject] : [];\n initialOptions.inject.push(absoluteFilePath);\n\n onStart(async () => {\n // Get all the entry points for later reference.\n entries.push(...(await getEsbuildEntries(build, context, log)));\n\n // Remove our injected file from the config, so we reduce our chances to leak our changes.\n build.initialOptions.inject = initialInject;\n\n try {\n // Create the MIDDLE file because esbuild will crash if it doesn't exist.\n // It seems to load entries outside of the onLoad hook once.\n await outputFile(absoluteFilePath, '');\n } catch (e: any) {\n log.error(`Could not create the files: ${e.message}`);\n }\n });\n\n onResolve(\n {\n filter: injectionRx,\n },\n async (args) => {\n // Mark the file as being injected by us.\n return { path: args.path, namespace: PLUGIN_NAME };\n },\n );\n\n onLoad(\n {\n filter: injectionRx,\n namespace: PLUGIN_NAME,\n },\n async () => {\n const content = getContentToInject(contentsToInject[InjectPosition.MIDDLE]);\n\n return {\n // We can't use an empty string otherwise esbuild will crash.\n contents: content || ' ',\n // Resolve the imports from the project's root.\n resolveDir: context.buildRoot,\n loader: 'js',\n };\n },\n );\n\n // InjectPosition.START and InjectPosition.END\n onEnd(async (result) => {\n if (!result.metafile) {\n log.warn('Missing metafile from build result.');\n return;\n }\n\n const banner = getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n const footer = getContentToInject(contentsToInject[InjectPosition.AFTER]);\n\n if (!banner && !footer) {\n // Nothing to inject.\n return;\n }\n\n // Rewrite outputs with the injected content.\n // Only keep the entry files.\n const outputs: string[] = Object.entries(result.metafile.outputs)\n .map(([p, o]) => {\n const entryPoint = o.entryPoint;\n if (!entryPoint) {\n return;\n }\n\n const entry = entries.find((e) => e.resolved.endsWith(entryPoint));\n if (!entry) {\n return;\n }\n\n return getAbsolutePath(context.buildRoot, p);\n })\n .filter(Boolean) as string[];\n\n // Write the content.\n const proms = outputs.map(async (output) => {\n try {\n const source = await fsp.readFile(output, 'utf-8');\n const data = await esbuild.transform(source, {\n loader: 'default',\n banner,\n footer,\n });\n\n // FIXME: Handle sourcemaps.\n await fsp.writeFile(output, data.code);\n } catch (e) {\n if (isNodeSystemError(e) && e.code === 'ENOENT') {\n // When we are using sub-builds, the entry file of sub-builds may not exist\n // Hence we should skip the file injection in this case.\n log.warn(`Could not inject content in ${output}: ${e}`);\n } else {\n throw e;\n }\n }\n });\n\n await Promise.all(proms);\n });\n },\n});\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\n\nimport { getContentToInject } from './helpers';\nimport type { ContentsToInject } from './types';\n\n// Use \"INJECTED_FILE\" so it get flagged by isInjectionFile().\nconst TO_INJECT_ID = INJECTED_FILE;\nconst TO_INJECT_SUFFIX = '?inject-proxy';\n\nexport const getRollupPlugin = (contentsToInject: ContentsToInject): PluginOptions['rollup'] => {\n return {\n banner(chunk) {\n if (chunk.isEntry) {\n // Can be empty.\n return getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n }\n return '';\n },\n async resolveId(source, importer, options) {\n if (isInjectionFile(source)) {\n // It is important that side effects are always respected for injections, otherwise using\n // \"treeshake.moduleSideEffects: false\" may prevent the injection from being included.\n return { id: source, moduleSideEffects: true };\n }\n if (options.isEntry && getContentToInject(contentsToInject[InjectPosition.MIDDLE])) {\n // Determine what the actual entry would have been.\n const resolution = await this.resolve(source, importer, options);\n // If it cannot be resolved or is external, just return it so that Rollup can display an error\n if (!resolution || resolution.external) {\n return resolution;\n }\n // In the load hook of the proxy, we need to know if the\n // entry has a default export. There, however, we no longer\n // have the full \"resolution\" object that may contain\n // meta-data from other plugins that is only added on first\n // load. Therefore we trigger loading here.\n const moduleInfo = await this.load(resolution);\n // We need to make sure side effects in the original entry\n // point are respected even for\n // treeshake.moduleSideEffects: false. \"moduleSideEffects\"\n // is a writable property on ModuleInfo.\n moduleInfo.moduleSideEffects = true;\n // It is important that the new entry does not start with\n // \\0 and has the same directory as the original one to not\n // mess up relative external import generation. Also\n // keeping the name and just adding a \"?query\" to the end\n // ensures that preserveModules will generate the original\n // entry name for this entry.\n return `${resolution.id}${TO_INJECT_SUFFIX}`;\n }\n return null;\n },\n load(id) {\n if (isInjectionFile(id)) {\n // Replace with injection content.\n return getContentToInject(contentsToInject[InjectPosition.MIDDLE]);\n }\n if (id.endsWith(TO_INJECT_SUFFIX)) {\n const entryId = id.slice(0, -TO_INJECT_SUFFIX.length);\n // We know ModuleInfo.hasDefaultExport is reliable because we awaited this.load in resolveId\n const info = this.getModuleInfo(entryId);\n let code = `import ${JSON.stringify(TO_INJECT_ID)};\\nexport * from ${JSON.stringify(entryId)};`;\n // Namespace reexports do not reexport default, so we need special handling here\n if (info?.hasDefaultExport) {\n code += `export { default } from ${JSON.stringify(entryId)};`;\n }\n return code;\n }\n return null;\n },\n footer(chunk) {\n if (chunk.isEntry) {\n // Can be empty.\n return getContentToInject(contentsToInject[InjectPosition.AFTER]);\n }\n return '';\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { outputFileSync, rmSync } from '@dd/core/helpers/fs';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, addInjections } from './helpers';\nimport type { ContentsToInject } from './types';\n\nexport const getXpackPlugin =\n (\n bundler: any,\n log: Logger,\n context: GlobalContext,\n toInject: Map<string, ToInjectItem>,\n contentsToInject: ContentsToInject,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n const cache = new WeakMap();\n // Use a narrower identifier to avoid cross build collisions.\n const ConcatSource = bundler.sources.ConcatSource;\n const id = context.bundler.name;\n const filePath = path.resolve(\n context.bundler.outDir,\n `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`,\n );\n\n // NOTE: RSpack MAY try to resolve the entry points before the loader is ready.\n // There must be some race condition around this, because it's not always failing.\n outputFileSync(filePath, '');\n // WARNING: Can't use shutdown.tapPromise as rspack would randomly crash the process.\n // Seems to be fixed in rspack@1.2.*\n // We also do it for webpack, as it fixes some resolution edge cases.\n const hookFn = () => {\n // Delete the file we created.\n rmSync(filePath);\n };\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n\n // Handle the InjectPosition.MIDDLE.\n type Entry = typeof compiler.options.entry;\n // TODO: Move this into @dd/core, add rspack/webpack types and tests.\n const injectEntry = (initialEntry: Entry): Entry => {\n const injectedEntry = {\n import: [filePath],\n };\n\n const objectInjection = (entry: Entry) => {\n for (const [entryKey, entryValue] of Object.entries(entry)) {\n if (typeof entryValue === 'object') {\n entryValue.import = entryValue.import || [];\n entryValue.import.unshift(filePath);\n } else if (typeof entryValue === 'string') {\n // @ts-expect-error - Badly typed for strings.\n entry[entryKey] = [filePath, entryValue];\n } else if (Array.isArray(entryValue)) {\n entryValue.unshift(filePath);\n } else {\n log.error(`Invalid entry type: ${typeof entryValue}`);\n }\n }\n };\n\n if (!initialEntry) {\n return {\n ddHelper: injectedEntry,\n };\n } else if (typeof initialEntry === 'function') {\n // @ts-expect-error - This is webpack / rspack typing conflict.\n return async () => {\n const originEntry = await initialEntry();\n objectInjection(originEntry);\n return originEntry;\n };\n } else if (typeof initialEntry === 'object') {\n objectInjection(initialEntry);\n } else if (typeof initialEntry === 'string') {\n // @ts-expect-error - Badly typed for strings.\n return [injectedEntry, initialEntry];\n } else {\n log.error(`Invalid entry type: ${typeof initialEntry}`);\n return initialEntry;\n }\n return initialEntry;\n };\n\n // We need to prepare the injections before the build starts.\n // Otherwise they'll be empty once resolved.\n compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {\n // Prepare the injections.\n await addInjections(log, toInject, contentsToInject, context.buildRoot);\n });\n\n // Handle the InjectPosition.START and InjectPosition.END.\n // This is a re-implementation of the BannerPlugin,\n // that is compatible with all versions of webpack and rspack,\n // with both banner and footer.\n compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {\n const hookCb = () => {\n const banner = getContentToInject(contentsToInject[InjectPosition.BEFORE]);\n const footer = getContentToInject(contentsToInject[InjectPosition.AFTER]);\n\n for (const chunk of compilation.chunks) {\n if (!chunk.canBeInitial()) {\n continue;\n }\n\n for (const file of chunk.files) {\n compilation.updateAsset(file, (old) => {\n const cached = cache.get(old);\n\n // If anything changed, we need to re-create the source.\n if (!cached || cached.banner !== banner || cached.footer !== footer) {\n const source = new ConcatSource(banner, '\\n', old, '\\n', footer);\n\n // Cache the result.\n cache.set(old, { source, banner, footer });\n return source;\n }\n\n return cached.source;\n });\n }\n }\n };\n\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n });\n\n // We inject the new entry.\n const newEntry = injectEntry(compiler.options.entry);\n compiler.options.entry = newEntry;\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE_RX } from '@dd/core/constants';\nimport { isXpack } from '@dd/core/helpers/bundlers';\nimport { getUniqueId } from '@dd/core/helpers/strings';\nimport {\n InjectPosition,\n type GetInternalPlugins,\n type GetPluginsArg,\n type PluginOptions,\n type ToInjectItem,\n} from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getEsbuildPlugin } from './esbuild';\nimport { addInjections, getContentToInject } from './helpers';\nimport { getRollupPlugin } from './rollup';\nimport type { ContentsToInject } from './types';\nimport { getXpackPlugin } from './xpack';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getInjectionPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { bundler, context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n // Storage for all the injections.\n const injections: Map<string, ToInjectItem> = new Map();\n\n // Storage for all the positional contents we want to inject.\n const contentsToInject: ContentsToInject = {\n [InjectPosition.BEFORE]: new Map(),\n [InjectPosition.MIDDLE]: new Map(),\n [InjectPosition.AFTER]: new Map(),\n };\n\n context.inject = (item: ToInjectItem) => {\n injections.set(getUniqueId(), item);\n };\n\n const plugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'post',\n // Bundler specific part of the plugin.\n // We use it to:\n // - Inject the content in the right places, each bundler offers this differently.\n esbuild: getEsbuildPlugin(log, context, contentsToInject),\n webpack: getXpackPlugin(bundler, log, context, injections, contentsToInject),\n rspack: getXpackPlugin(bundler, log, context, injections, contentsToInject),\n rollup: getRollupPlugin(contentsToInject),\n vite: { ...(getRollupPlugin(contentsToInject) as PluginOptions['vite']), enforce: 'pre' },\n };\n\n // We need to handle the resolution in xpack,\n // and it's easier to use unplugin's hooks for it.\n if (isXpack(context.bundler.name)) {\n plugin.load = {\n filter: {\n id: INJECTED_FILE_RX,\n },\n handler() {\n return {\n code: getContentToInject(contentsToInject[InjectPosition.MIDDLE]),\n };\n },\n };\n } else {\n // In xpack, we need to prepare the injections BEFORE the build starts.\n // Otherwise, the bundler doesn't have the content when it needs it.\n // So we do it in their specific plugin.\n // Here for all the other non-xpack bundlers.\n plugin.buildStart = async () => {\n // Prepare the injections.\n await addInjections(log, injections, contentsToInject, context.buildRoot);\n };\n }\n\n return [plugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions, PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-true-end-plugin' as const;\n\nexport const getTrueEndPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const asyncHookFn = async () => {\n await context.asyncHook('asyncTrueEnd');\n };\n const syncHookFn = () => {\n context.hook('syncTrueEnd');\n };\n const bothHookFns = async () => {\n syncHookFn();\n await asyncHookFn();\n };\n\n const xpackPlugin: PluginOptions['rspack'] & PluginOptions['webpack'] = (compiler) => {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n };\n\n const rollupPlugin: PluginOptions['rollup'] & PluginOptions['vite'] = {\n async writeBundle() {\n // TODO: Need to fallback here in case the closeBundle isn't called.\n },\n async closeBundle() {\n await bothHookFns();\n },\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n webpack: xpackPlugin,\n esbuild: {\n setup(build) {\n // NOTE: \"onEnd\" is the best we can do for esbuild, but it's very far from being the \"true end\" of the build.\n build.onEnd(async () => {\n await asyncHookFn();\n });\n // NOTE: \"onDispose\" is strictly synchronous.\n build.onDispose(() => {\n syncHookFn();\n });\n },\n },\n vite: rollupPlugin,\n rollup: rollupPlugin,\n rspack: xpackPlugin,\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n/* eslint-disable arca/import-ordering, arca/newline-after-import-section */\n// This file is mostly generated.\n// Anything between\n// - #imports-injection-marker\n// - #types-export-injection-marker\n// - #internal-plugins-injection-marker\n// - #helpers-injection-marker\n// - #configs-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type {\n BundlerName,\n Env,\n FactoryMeta,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPlugins,\n GlobalContext,\n GlobalData,\n GlobalStores,\n Options,\n OptionsWithDefaults,\n} from '@dd/core/types';\nimport type { UnpluginContextMeta, UnpluginInstance } from 'unplugin';\nimport { createUnplugin } from 'unplugin';\nimport chalk from 'chalk';\n\nimport { validateOptions } from './validate';\nimport { getContext } from './helpers/context';\nimport { wrapGetPlugins } from './helpers/wrapPlugins';\nimport { ALL_ENVS, HOST_NAME } from '@dd/core/constants';\n// #imports-injection-marker\nimport * as errorTracking from '@dd/error-tracking-plugin';\nimport * as metrics from '@dd/metrics-plugin';\nimport * as output from '@dd/output-plugin';\nimport * as rum from '@dd/rum-plugin';\nimport { getAnalyticsPlugins } from '@dd/internal-analytics-plugin';\nimport { getAsyncQueuePlugins } from '@dd/internal-async-queue-plugin';\nimport { getBuildReportPlugins } from '@dd/internal-build-report-plugin';\nimport { getBundlerReportPlugins } from '@dd/internal-bundler-report-plugin';\nimport { getCustomHooksPlugins } from '@dd/internal-custom-hooks-plugin';\nimport { getGitPlugins } from '@dd/internal-git-plugin';\nimport { getInjectionPlugins } from '@dd/internal-injection-plugin';\nimport { getTrueEndPlugins } from '@dd/internal-true-end-plugin';\n// #imports-injection-marker\n// #types-export-injection-marker\nexport type { types as ErrorTrackingTypes } from '@dd/error-tracking-plugin';\nexport type { types as MetricsTypes } from '@dd/metrics-plugin';\nexport type { types as OutputTypes } from '@dd/output-plugin';\nexport type { types as RumTypes } from '@dd/rum-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [metrics.CONFIG_KEY]: metrics.helpers,\n // #helpers-injection-marker\n};\n\nexport const buildPluginFactory = ({\n bundler,\n version,\n}: FactoryMeta): UnpluginInstance<Options, true> => {\n const start = Date.now();\n return createUnplugin((opts: Options, unpluginMetaContext: UnpluginContextMeta) => {\n // TODO: Implement config overrides with environment variables.\n // TODO: Validate API Key and endpoint.\n // TODO: Inject a metric logger into the global context.\n\n const options: OptionsWithDefaults = validateOptions(opts);\n\n // Set the host name for the esbuild plugin.\n if (unpluginMetaContext.framework === 'esbuild') {\n unpluginMetaContext.esbuildHostName = HOST_NAME;\n }\n\n // Use \"production\" if there is no env passed.\n const passedEnv: Env = (process.env.BUILD_PLUGINS_ENV as Env) || 'production';\n // Fallback to \"development\" if the passed env is wrong.\n const env = ALL_ENVS.includes(passedEnv) ? passedEnv : 'development';\n // We need to account for how each bundler exposes its version.\n // - (webpack|esbuild|vite).version\n // - rollup.VERSION\n // - rspack.rspackVersion\n const bundlerVersion = bundler.rspackVersion || bundler.version || bundler.VERSION;\n const bundlerName = unpluginMetaContext.framework as BundlerName;\n\n const data: GlobalData = {\n bundler: {\n name: bundlerName,\n version: bundlerVersion,\n },\n env,\n metadata: options.metadata || {},\n packageName: `@datadog/${bundlerName}-plugin`,\n version,\n };\n\n const stores: GlobalStores = {\n errors: [],\n logs: [],\n queue: [],\n timings: [],\n warnings: [],\n };\n\n // Create the global context.\n const context: GlobalContext = getContext({\n start,\n options,\n data,\n stores,\n });\n\n const log = context.getLogger('factory');\n const timeInit = log.time('Plugins initialization', { start });\n\n context.pluginNames.push(HOST_NAME);\n\n const pluginsToAdd: [name: string, GetPlugins | GetCustomPlugins | GetInternalPlugins][] =\n [];\n\n // List of plugins to be returned.\n // We keep the UnpluginOptions type for the custom plugins.\n pluginsToAdd.push(\n // Prefill with our internal plugins.\n // #internal-plugins-injection-marker\n ['analytics', getAnalyticsPlugins],\n ['async-queue', getAsyncQueuePlugins],\n ['build-report', getBuildReportPlugins],\n ['bundler-report', getBundlerReportPlugins],\n ['custom-hooks', getCustomHooksPlugins],\n ['git', getGitPlugins],\n ['injection', getInjectionPlugins],\n ['true-end', getTrueEndPlugins],\n // #internal-plugins-injection-marker\n );\n\n // Add custom, on the fly plugins, if any.\n if (options.customPlugins) {\n pluginsToAdd.push(['custom', options.customPlugins]);\n }\n\n // Add the customer facing plugins.\n pluginsToAdd.push(\n // #configs-injection-marker\n ['error-tracking', errorTracking.getPlugins],\n ['metrics', metrics.getPlugins],\n ['output', output.getPlugins],\n ['rum', rum.getPlugins],\n // #configs-injection-marker\n );\n\n // Initialize all our plugins.\n for (const [name, getPlugins] of pluginsToAdd) {\n context.plugins.push(\n ...wrapGetPlugins(\n context,\n getPlugins,\n name,\n )({\n bundler,\n context,\n options,\n data,\n stores,\n }),\n );\n }\n\n // List all our plugins in the context.\n context.pluginNames.push(...context.plugins.map((plugin) => plugin.name));\n\n // Verify we don't have plugins with the same name, as they would override each other.\n const duplicates = new Set(\n context.pluginNames.filter(\n (name) => context.pluginNames.filter((n) => n === name).length > 1,\n ),\n );\n if (duplicates.size > 0) {\n throw new Error(\n `Duplicate plugin names: ${chalk.bold.red(Array.from(duplicates).join(', '))}`,\n );\n }\n\n context.hook('init', context);\n timeInit.end();\n\n return context.plugins;\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n// This file is partially generated.\n// Anything between #types-export-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type { Options } from '@dd/core/types';\nimport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport * as vite from 'vite';\n\nimport pkg from '../package.json';\n\nexport type VitePluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogVitePlugin = factory.buildPluginFactory({\n bundler: vite,\n version: pkg.version,\n}).vite;\n\nexport const version = pkg.version;\nexport const helpers = factory.helpers;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport type {\n BuildReport,\n GlobalContext,\n GlobalData,\n GlobalStores,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nimport { getLoggerFactory } from './logger';\n\nexport const getContext = ({\n start,\n options,\n data,\n stores,\n}: {\n start: number;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n}): GlobalContext => {\n const buildRoot = process.cwd();\n const build: BuildReport = {\n errors: stores.errors,\n warnings: stores.warnings,\n logs: stores.logs,\n metadata: data.metadata,\n timings: stores.timings,\n bundler: data.bundler,\n };\n const context: GlobalContext = {\n auth: options.auth,\n pluginNames: [],\n bundler: {\n ...build.bundler,\n // This will be updated in the bundler-report plugin once we have the configuration.\n outDir: buildRoot,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n buildRoot,\n env: data.env,\n getLogger: getLoggerFactory(data, stores, options.logLevel),\n // This will be updated in the injection plugin on initialization.\n asyncHook: () => {\n throw new Error('AsyncHook function called before it was initialized.');\n },\n hook: () => {\n throw new Error('Hook function called before it was initialized.');\n },\n // This will be updated in the injection plugin on initialization.\n inject: () => {\n throw new Error('Inject function called before it was initialized.');\n },\n plugins: [],\n // This will be updated in the async-queue plugin on initialization.\n queue: () => {\n throw new Error('Queue function called before it was initialized.');\n },\n sendLog: getSendLog(data),\n start,\n version: data.version,\n };\n\n return context;\n};\n"],"names":["getEnvValue","key","process","env","INJECTED_FILE","INJECTED_FILE_RX","RegExp","ALL_ENVS","HOST_NAME","ERROR_CODES_NO_RETRY","doRequest","opts","auth","url","method","getData","type","retryOpts","retries","onRetry","maxTimeout","minTimeout","retry","async","bail","attempt","response","requestInit","duplex","requestHeaders","apiKey","appKey","data","headers","body","fetch","error","ok","errorMessage","status","statusText","includes","Error","result","json","text","getSendLog","message","context","payload","ddsource","packageName","service","team","version","bundler","name","metadata","JSON","stringify","cleanPluginName","replace","isInjectionFile","filename","serializeBuildReport","report","jsonReport","errors","warnings","logs","timings","start","end","duration","writeDuration","entries","inputs","outputs","entry","newEntry","map","file","filepath","push","input","newInput","dependencies","dependents","dependency","dependent","output","newOutput","shouldGetGitInfo","options","gitEnabledFromSourcemaps","errorTracking","sourcemaps","gitEnabledFromRoot","enableGit","formatDuration","days","Math","floor","d","Date","hours","getUTCHours","minutes","getUTCMinutes","seconds","getUTCSeconds","milliseconds","getUTCMilliseconds","timeString","trim","truncateString","str","maxLength","placeholder","length","stringLength","max","leftStop","min","rightStop","slice","filterSensitiveInfoFromRepositoryUrl","repositoryUrl","startsWith","URL","cleanPath","pathname","protocol","host","index","logPriority","debug","info","warn","none","cleanName","split","join","getLogFn","stores","logLevel","cleanedName","forward","color","c","dim","logFn","console","log","red","yellow","cyan","prefix","content","pluginName","time","now","forwardLog","sendLog","plugin","e","subLogger","queue","getTimeLogger","store","label","level","toLog","tags","timer","spans","total","getUncompleteSpans","filter","span","resume","startTime","pause","pauseTime","uncompleteSpans","param","endTime","reduce","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","getLoggerFactory","getLogger","subName","logger","HOOKS_TO_TRACE","wrapHook","hookName","hook","wrapWithTiming","fn","args","apply","this","Promise","finally","handler","wrapGetPlugins","getPlugins","arg","initTimer","wrappedPlugins","wrappedPlugin","wrapPlugin","pluginNames","CONFIG_KEY","PLUGIN_NAME","decomposePath","absoluteOutDir","sourcemapFilePath","path","extname","chalk","green","bold","minifiedFilePath","relativePath","relative","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","mkdir","dir","fsp","recursive","outputFileSync","dirname","fs","mkdirSync","writeFileSync","encoding","existsSync","code","getFile","openAsBlob","blob","contentType","File","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","pathParts","prefixParts","normalizedPath","i","partialPrefix","getPayload","sourcemap","git","resultMinFile","resultSourcemap","all","repeatedPrefix","getSourcemapValidity","Map","value","minified_url","set","files","trackedFilesMatcher","matchSourcemap","reason","basename","hash","repository_url","remote","defaultHeaders","form","FormData","gz","createGzip","Blob","append","req","Request","fromWeb","pipe","Object","fromEntries","upload","payloads","PQueue","default","concurrency","maxConcurrency","intakeUrl","site","DATADOG_SOURCEMAP_INTAKE_URL","bundlerName","configurationString","outDir","toString","summary","addPromises","get","add","warningMessage","bailOnError","onIdle","uploadSourcemaps","sourcemapsTime","endsWith","minifiedPathPrefix","getSourcemapsFiles","sendTime","git_repository_url","git_commit_sha","plugin_version","project_path","releaseVersion","flat","errorMsg","uploadErrors","uploadWarnings","fileMetadata","errorToPrint","cause","stack","sendSourcemaps","validateSourcemapsOptions","config","validatedOptions","toReturn","validateMinifiedPathPrefix","sourcemapsWithDefaults","dryRun","timeOptions","sourcemapsResults","enable","validateOptions","gitInfo","buildReport","handleSourcemaps","totalTime","enforce","repoData","defaultFilters","metric","test","some","thresholds","count","points","accumulator","currentPoint","getTimestamp","timestamp","getMetric","defaultTags","formatCwd","cwd","getDisplayName","pop","formatModuleName","getModuleName","module","compilation","userRequest","issuer","moduleGraph","getIssuer","_identifier","getModulePath","formatLoaderName","loader","getValueContext","constructor","numColor","nameColor","sortDesc","attr","a","b","aVal","bVal","getTimingValues","times","Array","from","values","sort","durationsToPrint","top","increment","outputTexts","globalContext","valuesToPrint","loaders","tapables","modules","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","Set","serializedReport","build","fileDependencies","fileDependents","dependenciesSet","dependentsSet","dep","has","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","prettyBytes","getModulesValues","nbModules","nbAssets","nbWarnings","nbErrors","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","flatMap","v","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","FN_TO_WRAP","loadersMap","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","cb","pluginTiming","events","isLoader","initialFunction","modulePath","moduleTiming","performance","statsObject","loaderTiming","getEsbuildPlugin","setup","initialOptions","metafile","timeWrap","plugins","initialPlugins","oldSetup","esbuild","wrapPlugins","buildRoot","onEnd","timeResult","asyncHook","Loaders","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","current","getPromiseTapPatch","checkNewHooks","returnValue","then","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","scope","call","newFn","replaceTaps","tap","tapAsync","tapPromise","patchHook","_fakeHook","patchHooks","hooksToPatch","keys","throughHooks","getWebpackPlugin","compiler","HOOK_OPTIONS","compilerTime","thisCompilation","compilationTime","buildModule","succeedModule","failedModule","afterEmit","tapableTimings","loadersTimings","modulesTimings","helpers","filters","realBuildEnd","enableDefaultPrefix","enableTracing","toLowerCase","legacyPlugin","webpack","rspack","timeBuild","needLegacyPlugin","timingsReport","computeMetrics","timeMetrics","universalMetrics","metrics","entriesPerInput","assetsPerInput","entriesPerAsset","cleanAssetName","entryName","assetName","getUniversalMetrics","pluginMetrics","pluginDuration","pluginCount","hookDuration","getPluginMetrics","loaderMetrics","getLoaderMetrics","metricsToSend","processedMetrics","toSend","m","getMetricsToSend","timeReport","timeSend","metricIterations","metricsNames","nameA","nameB","localeCompare","series","catch","sendMetrics","universalPlugin","buildStart","buildEnd","sanitizeOutputPath","validateFilesOptions","defaultValue","getXpackPlugin","write","done","stats","statsTimer","statsJson","toJson","assets","children","chunks","chunkGroupAuxiliary","chunkGroupChildren","chunkGroups","chunkRelations","entrypoints","ids","nestedModules","relatedAssets","reasons","chunkModules","getRollupPlugin","clear","writeBundle","bundle","closeBundle","writeFile","fileValue","timeWrite","pathOption","outputPath","isAbsolute","resolve","getFilePath","dataToWrite","writable","createWriteStream","readable","JsonStreamStringify","prom","reject","on","err","outputJson","queuedWrite","timeSerialization","getStats","rollup","getOutputs","vite","InjectPosition","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","attributes","client_token","validateSDKOptions","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacy","privacyWithDefault","exclude","include","addToDictionaryFunctionName","helperCodeExpression","sdkResults","privacyResults","_","inject","position","MIDDLE","__dirname","BEFORE","privacyPlugin","pluginOptions","transformOptions","addToDictionaryHelper","expression","inlineSourceMap","embedCodeInSourceMap","buildTransformOptions","transform","id","instrument","getPrivacyPlugin","getAnalyticsPlugins","buildStartFn","getAsyncQueuePlugins","promise","wrappedPromise","asyncTrueEnd","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","isArray","fullPath","in","proms","getAllEntryFiles","glob","sync","p","kind","resolveDir","resolved","original","resolutionError","getAbsolutePath","getNearestCommonDirectory","dirs","splitPaths","sep","minLength","parts","commonParts","component","every","EXTENSION_RX","QUERY_RX","getType","lastIndex","exec","BUNDLER_SPECIFICS","cleanReport","cleanedReport","reportFilepath","cleanedPath","shift","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","obj","entryNames","resolvedEntries","timeBuildReport","onStart","timeEntries","timeCollect","warning","tempEntryFiles","tempSourcemaps","reportInputsIndexed","reportOutputsIndexed","timeIndex","metaInputsIndexed","metaOutputsIndexed","getRealPathFromInjectionProxy","entryPoint","metaInput","actualImport","imports","find","imp","timeInputs","bytes","timeOutputs","inputFiles","inputName","inputFound","inputFile","timeSourcemaps","foundOutput","references","meta","FILE_EXCEPTIONS_RX","isFileSupported","match","getAllImports","ref","allImports","metaFile","imported","isRelative","root","absoluteImportPath","external","entryFile","entryInputs","entryOutputs","outputFile","timeDeps","absoluteDependencyPath","dependencyFile","timeModuleParsing","timeInputsOutputs","timeCompleteDeps","importsReport","onLog","logItem","renderError","moduleParsed","cleanId","newDependencies","dynamicallyImportedIds","importedIds","newDependents","dynamicImporters","importers","tempOutputsImports","cleanedDependency","cleanedDependent","asset","Buffer","byteLength","source","modulepath","moduleFile","originalLength","importName","cleanedImport","importFile","isEntry","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","modulesPerFile","moduleIndex","tempDeps","isModuleSupported","moduleIdentifier","cleanExternalName","indexModule","mod","moduleToIndex","identifier","blocks","externalType","createIndexedModule","keysToIndex","indexes","keysOfModuleToIndexOn","indexValue","valueToIndex","getKeysToIndex","previousModule","getAllDependencies","block","getModuleFromDep","request","cleanRequest","isExternal","finishModules","finishedModules","timeGraph","Boolean","moduleDeps","depIdentifier","depDeps","timeAssign","depsReport","depInput","getAssets","getChunkFiles","chunk","auxiliaryFiles","f","timeChunks","chunkGraph","getChunkModules","m2","fileModules","outputFound","entrypoint","entryFiles","entryFilename","getChunkEntryModulesIterable","getBuildReportPlugins","getAbsoluteOutDir","getOutDirsFromOutputs","outputOptions","o","xpackPlugin","rawConfig","vitePlugin","configResolved","rollupOptions","outDirs","getBundlerReportPlugins","absWorkingDir","outdir","outfile","inDirs","normalizedInput","getIndirsFromInputs","computedCwd","renderStart","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","TrackedFilesMatcher","trackedFiles","trackedFilenames","getFilename","list","displaySource","src","srcmapPath","onSourcesNotFound","buff","readFileSync","srcmapObj","parse","sources","filtered","matchSources","filenameAlreadyMatched","concat","rawTrackedFilesList","rawList","forEach","s","lastIndexOf","substring","gitRemote","remotes","getRemotes","defaultRemote","getDefaultRemoteName","refs","getConfig","gitHash","revparse","gitTrackedFiles","raw","gitBranch","branch","gitMessage","show","gitAuthorAndCommitter","getGitPlugins","timeGit","processGit","gitDir","repositoryData","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","item","commit","author","email","date","committer","getRepositoryData","baseDir","binary","maxConcurrentProcesses","simpleGit","newSimpleGit","currentDir","closest","getClosest","DISTANT_FILE_RX","processLocalFile","readFile","processItem","getInjectedValue","timeout","timeoutId","race","clearTimeout","setTimeout","processDistantFile","itemId","fallback","getContentToInject","contentToInject","addInjections","toInject","contentsToInject","results","processInjections","promises","onResolve","onLoad","tmpDir","realpathSync","os","tmpdir","absoluteFilePath","injectionRx","initialInject","namespace","contents","banner","footer","AFTER","isNodeSystemError","TO_INJECT_ID","TO_INJECT_SUFFIX","resolveId","importer","moduleSideEffects","resolution","load","entryId","getModuleInfo","hasDefaultExport","cache","WeakMap","ConcatSource","shutdown","rmSync","force","maxRetries","beforeRun","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","processAssets","canBeInitial","updateAsset","old","cached","initialEntry","injectedEntry","import","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","getTrueEndPlugins","asyncHookFn","syncHookFn","bothHookFns","rollupPlugin","onDispose","CONFIG_KEY$2","metrics.CONFIG_KEY","metrics.helpers","datadogVitePlugin","createUnplugin","unpluginMetaContext","defineProperty","enumerable","framework","esbuildHostName","passedEnv","BUILD_PLUGINS_ENV","bundlerVersion","rspackVersion","VERSION","getContext","timeInit","pluginsToAdd","customPlugins","errorTracking.getPlugins","metrics.getPlugins","output.getPlugins","rum.getPlugins","duplicates","n","factory.buildPluginFactory","pkg","factory.helpers"],"mappings":"srBAMA,MAAMA,EAAeC,GACVC,QAAQC,IAAI,WAAWF,MAAUC,QAAQC,IAAI,MAAMF,KCHjDG,EAAgB,wBAChBC,EAAmB,IAAIC,OAAOF,GAE9BG,EAAW,CAAC,cAAe,aAAc,QAKzCC,EAAY,wBCHZC,EAAuB,CAAC,IAAK,IAAK,KAGlCC,EAAgBC,IACzB,MAAMC,KAAEA,MAAMC,EAAAC,OAAKA,EAAS,cAAOC,EAAAC,KAASA,EAAO,QAAWL,EACxDM,EAA2B,CAC7BC,QAA0B,IAAjBP,EAAKO,QAAgB,EAAIP,EAAKO,SALrB,EAMlBC,QAASR,EAAKQ,QACdC,WAAYT,EAAKS,WACjBC,WAAYV,EAAKU,YAGrB,OAAOC,GAAMC,MAAOC,EAA0BC,KAC1C,IAAIC,EACJ,IACI,MAAMC,EAA2B,CAC7Bb,SAGAc,OAAQ,QAEZ,IAAIC,EAAyC,CACzC,mBAAoB,iBAYxB,GARIjB,GAAMkB,SACND,EAAe,cAAgBjB,EAAKkB,QAGpClB,GAAMmB,SACNF,EAAe,sBAAwBjB,EAAKmB,QAGzB,mBAAZhB,EAAwB,CAC/B,MAAMiB,KAAEA,EAAAC,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