@datadog/rollup-plugin 2.6.3-dev-3 → 2.6.3-dev-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../factory/src/validate.ts","../../../../core/src/constants.ts","../../../../core/src/helpers/fs.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/request.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","../../../../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/telemetry/src/constants.ts","../../../../plugins/telemetry/src/common/filters.ts","../../../../plugins/telemetry/src/common/helpers.ts","../../../../plugins/telemetry/src/common/aggregator.ts","../../../../plugins/telemetry/src/common/metrics/common.ts","../../../../plugins/telemetry/src/common/output/files.ts","../../../../plugins/telemetry/src/common/output/text.ts","../../../../plugins/telemetry/src/esbuild-plugin/plugins.ts","../../../../plugins/telemetry/src/esbuild-plugin/index.ts","../../../../plugins/telemetry/src/webpack-plugin/loaders.ts","../../../../plugins/telemetry/src/webpack-plugin/tapables.ts","../../../../plugins/telemetry/src/webpack-plugin/index.ts","../../../../plugins/telemetry/src/index.ts","../../../../plugins/telemetry/src/common/sender.ts","../../../../plugins/analytics/src/constants.ts","../../../../plugins/analytics/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 { Options, OptionsWithDefaults } from '@dd/core/types';\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n return {\n auth: {},\n disableGit: false,\n logLevel: 'warn',\n metadata: {},\n ...options,\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';\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 FULL_NAME_BUNDLERS = [\n 'esbuild',\n 'rollup',\n 'rspack',\n 'vite',\n 'webpack4',\n 'webpack5',\n] 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 { File } from 'buffer';\nimport fsp from 'fs/promises';\nimport fs from 'fs';\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 // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n return outputFile(filepath, dataString);\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 // @ts-expect-error openAsBlob is not in the NodeJS types until 19+\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n // @ts-expect-error openAsBlob is not in the NodeJS types until 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 { INJECTED_FILE } from '@dd/core/constants';\nimport { outputJsonSync } from '@dd/core/helpers/fs';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n GetCustomPlugins,\n GlobalContext,\n Input,\n IterableElement,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\nimport path from 'path';\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// Returns a customPlugin to output some debug files.\ntype CustomPlugins = ReturnType<GetCustomPlugins>;\nexport const debugFilesPlugins = (context: GlobalContext): CustomPlugins => {\n const outputFilePath = () =>\n path.resolve(context.bundler.outDir, `output.${context.bundler.fullName}.json`);\n const reportFilePath = () =>\n path.resolve(context.bundler.outDir, `report.${context.bundler.fullName}.json`);\n const xpackPlugin: IterableElement<CustomPlugins>['webpack'] &\n IterableElement<CustomPlugins>['rspack'] = (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\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 chunkModules: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n reasons: true,\n relatedAssets: true,\n warnings: true,\n });\n outputJsonSync(outputFilePath(), statsJson);\n });\n };\n\n return [\n {\n name: 'build-report',\n enforce: 'post',\n writeBundle() {\n outputJsonSync(reportFilePath(), serializeBuildReport(context.build));\n },\n },\n {\n name: 'bundler-outputs',\n enforce: 'post',\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n outputJsonSync(outputFilePath(), result.metafile);\n });\n },\n },\n rspack: xpackPlugin,\n rollup: {\n writeBundle(options, bundle) {\n outputJsonSync(outputFilePath(), bundle);\n },\n },\n vite: {\n writeBundle(options, bundle) {\n outputJsonSync(outputFilePath(), bundle);\n },\n },\n webpack: xpackPlugin,\n },\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 not disabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n return (\n !!options.errorTracking?.sourcemaps &&\n options.errorTracking?.sourcemaps.disableGit !== true &&\n options.disableGit !== true\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// 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 { cleanPluginName } from '@dd/core/helpers/plugins';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type { BuildReport, GetLogger, LogLevel, TimeLog, TimeLogger, Timer } 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\nexport const getLoggerFactory =\n (build: BuildReport, logLevel: LogLevel = 'warn'): GetLogger =>\n (name) => {\n // Will remove any \"datadog-\" prefix and \"-plugin\" suffix in the name string.\n const cleanedName = cleanName(name);\n const log = (text: any, type: LogLevel = 'debug') => {\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 = build.metadata?.name ? `${build.metadata.name}|` : '';\n const prefix = `[${buildName}${type}|${build.bundler.fullName}|${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 build.logs.push({\n bundler: build.bundler.fullName,\n pluginName: name,\n type,\n message: content,\n time: Date.now(),\n });\n\n if (type === 'error') {\n build.errors.push(content);\n }\n if (type === 'warn') {\n build.warnings.push(content);\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 const time: TimeLog = (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 build.timings.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) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\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 pause(endTime);\n const duration = timer.spans.reduce(\n (acc, span) => acc + (span.end! - span.start),\n 0,\n );\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 return {\n getLogger: (subName: string) => {\n const logger = getLoggerFactory(build, logLevel);\n return logger(`${cleanedName}${NAME_SEP}${subName}`);\n },\n time,\n error: (text: any) => log(text, 'error'),\n warn: (text: any) => log(text, 'warn'),\n info: (text: any) => log(text, 'info'),\n debug: (text: any) => log(text, 'debug'),\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 'loadInclude',\n 'resolveId',\n 'transform',\n 'transformInclude',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['cwd', '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 function called by a hook that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = (pluginName: string, hookName: HookName, hook: HookFn, log: Logger) => {\n return (...args: Parameters<HookFn>) => {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n // @ts-expect-error, can't type \"args\" correctly: \"A spread argument must either have a tuple type or be passed to a rest parameter.\"\n const result = hook(...args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n };\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 as PluginHookName];\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 { GlobalContext } 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 options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\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(context.bundler.outDir, minifiedFilePath);\n const minifiedUrl = joinUrlOrPath(options.minifiedPathPrefix, relativePath);\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\n): Sourcemap[] => {\n if (!context.build.outputs || context.build.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.build.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, context, 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 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 { 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, GlobalContext } 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\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 const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.auth?.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.bundler.fullName}-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.bundler.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.bundler.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.auth!.apiKey },\n url: options.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 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 const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\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.bundler.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 context,\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, GlobalContext } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { outdent } from 'outdent';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport { getSourcemapsFiles } from './files';\nimport { sendSourcemaps } from './sender';\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: GlobalContext,\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, context);\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(sourcemaps, options.sourcemaps, context, log);\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\nexport const defaultIntakeUrl = `https://sourcemap-intake.${process.env.DATADOG_SITE || 'datadoghq.com'}/api/v2/srcmap`;\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 disabled: !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 disableGit: false,\n dryRun: false,\n maxConcurrency: 20,\n intakeUrl:\n process.env.DATADOG_SOURCEMAP_INTAKE_URL ||\n validatedOptions.sourcemaps.intakeUrl ||\n defaultIntakeUrl,\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 type { GetPlugins } 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 disabled, return an empty array.\n if (validatedOptions.disabled) {\n return [];\n }\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async writeBundle() {\n if (validatedOptions.disabled) {\n return;\n }\n\n if (validatedOptions.sourcemaps) {\n const totalTime = log.time('sourcemaps process');\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n await uploadSourcemaps(\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n context,\n log,\n );\n totalTime.end();\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\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 { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\nimport type { TelemetryOptions } from '@dd/telemetry-plugin/types';\nimport type * as telemetry from '@dd/telemetry-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, FULL_NAME_BUNDLERS, 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 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: Omit<BundlerReport, 'outDir' | 'rawConfig'>;\n errors: string[];\n warnings: string[];\n logs: {\n bundler: BundlerFullName;\n pluginName: string;\n type: LogLevel;\n message: string;\n time: number;\n }[];\n metadata: BuildMetadata;\n timings: Timer[];\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 BundlerFullName = (typeof FULL_NAME_BUNDLERS)[number];\nexport type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];\nexport type BundlerReport = {\n name: BundlerName;\n fullName: BundlerFullName;\n outDir: string;\n rawConfig?: any;\n variant?: string; // e.g. Major version of the bundler (webpack 4, webpack 5)\n version: string;\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) => 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 Logger = {\n getLogger: GetLogger;\n time: TimeLog;\n error: (text: any) => void;\n warn: (text: any) => void;\n info: (text: any) => void;\n debug: (text: any) => void;\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?: AuthOptions;\n build: BuildReport;\n bundler: BundlerReport;\n cwd: string;\n env: Env;\n getLogger: GetLogger;\n git?: RepositoryData;\n hook: TriggerHook<void>;\n inject: (item: ToInjectItem) => void;\n pluginNames: string[];\n plugins: (PluginOptions | CustomPluginOptions)[];\n sendLog: (message: string, ctx?: any) => Promise<void>;\n start: number;\n version: string;\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 cwd?: HookFn<[string]>;\n init?: HookFn<[GlobalContext]>;\n buildReport?: HookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n syncTrueEnd?: () => void;\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: Options;\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};\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n disableGit?: 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 [rum.CONFIG_KEY]?: RumOptions;\n [telemetry.CONFIG_KEY]?: TelemetryOptions;\n // #types-injection-marker\n customPlugins?: GetCustomPlugins;\n}\n\nexport type GetPluginsOptions = Required<BaseOptions>;\nexport type OptionsWithDefaults = Assign<Options, GetPluginsOptions>;\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?: AuthOptions;\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","// 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_MODULE_ID = '\\0datadog:privacy-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 { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { createFilter } from '@rollup/pluginutils';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { PRIVACY_HELPERS_MODULE_ID, PLUGIN_NAME } from './constants';\nimport { buildTransformOptions } from './transform';\nimport type { PrivacyOptions } from './types';\n\nexport const getPrivacyPlugin = (\n pluginOptions: PrivacyOptions,\n context: GlobalContext,\n): PluginOptions | undefined => {\n const log = context.getLogger(PLUGIN_NAME);\n\n if (pluginOptions.disabled) {\n return;\n }\n\n const transformOptions = buildTransformOptions(pluginOptions);\n const transformFilter = createFilter(pluginOptions.include, pluginOptions.exclude);\n const privacyHelpersModuleId = pluginOptions.helpersModule ?? PRIVACY_HELPERS_MODULE_ID;\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 // webpack's id filter is outside of loader logic,\n // an additional hook is needed for better perf on webpack\n async resolveId(source) {\n if (source.includes(privacyHelpersModuleId)) {\n return { id: source };\n }\n return null;\n },\n\n loadInclude(id) {\n if (id.includes(privacyHelpersModuleId)) {\n return true;\n }\n return false;\n },\n\n async load(id) {\n let privacyHelpersPath: string;\n if (id.includes(privacyHelpersModuleId)) {\n if (id.endsWith('.cjs')) {\n privacyHelpersPath = path.join(__dirname, 'privacy-helpers.js');\n } else {\n privacyHelpersPath = path.join(__dirname, 'privacy-helpers.mjs');\n }\n return { code: fs.readFileSync(privacyHelpersPath, 'utf8'), map: null };\n }\n return null;\n },\n // webpack's id filter is outside of loader logic,\n // an additional hook is needed for better perf on webpack\n transformInclude(id) {\n return transformFilter(id);\n },\n async transform(code, id) {\n try {\n if (\n context.bundler.name === 'esbuild' ||\n context.bundler.name === 'webpack' ||\n context.bundler.name === 'rspack'\n ) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n const result = instrument({ id, code }, transformOptions);\n return result;\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`);\n return {\n code,\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 if (sdkOpts.disabled) {\n return '';\n }\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.datadoghq.com/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 } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { PRIVACY_HELPERS_MODULE_ID } from './privacy/constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';\n\nexport const validateOptions = (options: Options, log: Logger): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options, log);\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 disabled: !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\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (options: Options): 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?.disabled) {\n return toReturn;\n }\n\n if (validatedOptions.sdk) {\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\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (\n options: Options,\n log: Logger,\n): ToReturn<PrivacyOptionsWithDefaults> => {\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<PrivacyOptionsWithDefaults> = {\n errors: [],\n };\n\n log.debug(`datadog-rum-privacy plugin options: ${JSON.stringify(validatedOptions.privacy)}`);\n\n if (validatedOptions.privacy) {\n const privacyWithDefault: PrivacyOptionsWithDefaults = {\n exclude: [/\\/node_modules\\//, /\\.preval\\./, /^[!@#$%^&*()=+~`\\\\\\-/]/],\n include: [/\\.(?:c|m)?(?:j|t)sx?$/],\n addToDictionaryFunctionName: '$',\n helpersModule: PRIVACY_HELPERS_MODULE_ID,\n };\n\n // Save the config.\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 disabled, return an empty array.\n if (validatedOptions.disabled) {\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 const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n if (privacyPlugin) {\n plugins.push(privacyPlugin);\n }\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\nimport type { PrivacyOptions } from './types';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(pluginOptions: PrivacyOptions): InstrumentationOptions {\n return {\n input: {\n module: pluginOptions.module,\n jsx: pluginOptions.jsx,\n typescript: pluginOptions.typescript,\n },\n privacy: {\n addToDictionaryHelper: {\n import: {\n cjsModule: `${pluginOptions.helpersModule}.cjs`,\n esmModule: `${pluginOptions.helpersModule}.mjs`,\n func: pluginOptions.addToDictionaryFunctionName ?? '$',\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 { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'telemetry' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-telemetry-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 { Metric } from '@dd/telemetry-plugin/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\n return metric.value > 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 { Options } from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/telemetry-plugin/constants';\nimport type {\n OptionsDD,\n Metric,\n MetricToSend,\n Module,\n Compilation,\n ValueContext,\n TelemetryOptionsWithDefaults,\n} from '@dd/telemetry-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const validateOptions = (opts: Options): TelemetryOptionsWithDefaults => {\n const endPoint = opts[CONFIG_KEY]?.endPoint || 'https://app.datadoghq.com';\n return {\n disabled: !opts[CONFIG_KEY],\n enableTracing: false,\n filters: defaultFilters,\n output: false,\n prefix: '',\n tags: [],\n ...opts[CONFIG_KEY],\n endPoint: endPoint.startsWith('http') ? endPoint : `https://${endPoint}`,\n };\n};\n\nexport const getMetric = (metric: Metric, opts: OptionsDD): MetricToSend => ({\n type: 'gauge',\n tags: [...metric.tags, ...opts.tags],\n metric: `${opts.prefix ? `${opts.prefix}.` : ''}${metric.metric}`,\n points: [[opts.timestamp, metric.value]],\n});\n\nexport const getOptionsDD = (options: TelemetryOptionsWithDefaults): OptionsDD => {\n return {\n timestamp: Math.floor((options.timestamp || Date.now()) / 1000),\n tags: options.tags,\n prefix: options.prefix,\n filters: options.filters,\n };\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 type { GlobalContext } from '@dd/core/types';\nimport type { Metric, MetricToSend, OptionsDD, Report } from '@dd/telemetry-plugin/types';\n\nimport { getMetric } from './helpers';\nimport { addPluginMetrics, addLoaderMetrics } from './metrics/common';\n\nconst addUniversalMetrics = (globalContext: GlobalContext, metrics: Set<Metric>) => {\n const inputs = globalContext.build.inputs || [];\n const outputs = globalContext.build.outputs || [];\n const entries = globalContext.build.entries || [];\n const nbWarnings = globalContext.build.warnings.length;\n const nbErrors = globalContext.build.errors.length;\n const duration = globalContext.build.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 value: outputs.length,\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n value: entries.length,\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n value: nbErrors,\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n value: inputs.length,\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n value: nbWarnings,\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n value: 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 value: input.size,\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n value: input.dependencies.size,\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n value: 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 value: output.size,\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n value: 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 value: entry.size,\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n value: entry.inputs.length,\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n value: entry.outputs.length,\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const addMetrics = (\n globalContext: GlobalContext,\n optionsDD: OptionsDD,\n metricsToSend: Set<MetricToSend>,\n report?: Report,\n): void => {\n const metrics: Set<Metric> = new Set();\n\n if (report) {\n const { timings } = report;\n\n if (timings) {\n if (timings.tapables) {\n addPluginMetrics(timings.tapables, metrics);\n }\n if (timings.loaders) {\n addLoaderMetrics(timings.loaders, metrics);\n }\n }\n }\n\n addUniversalMetrics(globalContext, metrics);\n\n // Format metrics to be DD ready and apply filters\n for (const metric of metrics) {\n if (optionsDD.filters?.length) {\n let filteredMetric: Metric | null = metric;\n for (const filter of optionsDD.filters) {\n // If it's already been filtered out, no need to keep going.\n if (!filteredMetric) {\n break;\n }\n filteredMetric = filter(metric);\n }\n if (filteredMetric) {\n metricsToSend.add(getMetric(filteredMetric, optionsDD));\n }\n } else {\n metricsToSend.add(getMetric(metric, optionsDD));\n }\n }\n\n // Add the number of metrics sent.\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n value: metricsToSend.size + 1,\n tags: [],\n },\n optionsDD,\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, Metric } from '@dd/telemetry-plugin/types';\n\nexport const addPluginMetrics = (plugins: TimingsMap, metrics: Set<Metric>): void => {\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n value: 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 value: hookDuration,\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n value: 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 value: pluginDuration,\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n value: pluginCount,\n tags: [`pluginName:${plugin.name}`],\n });\n }\n};\n\nexport const addLoaderMetrics = (loaders: TimingsMap, metrics: Set<Metric>): void => {\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n value: 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 value: loader.duration,\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n value: loader.increment,\n tags: [`loaderName:${loader.name}`],\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 { outputJson } from '@dd/core/helpers/fs';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type { Logger } from '@dd/core/types';\nimport type { MetricToSend, OutputOptions, Report } from '@dd/telemetry-plugin/types';\nimport path from 'path';\n\ntype Files = 'timings' | 'metrics';\n\ntype FilesToWrite = {\n [key in Files]?: { content: any };\n};\n\nexport const outputFiles: (\n data: {\n report?: Report;\n metrics: Set<MetricToSend>;\n },\n outputOptions: OutputOptions,\n log: Logger,\n cwd: string,\n) => Promise<void> = async (data, outputOptions, log, cwd) => {\n // Don't write any file if it's not enabled.\n if (typeof outputOptions !== 'string' && typeof outputOptions !== 'object' && !outputOptions) {\n return;\n }\n\n const { report, metrics } = data;\n\n const startWriting = Date.now();\n let destination = '';\n const files = {\n timings: true,\n metrics: true,\n };\n\n if (typeof outputOptions === 'object') {\n destination = outputOptions.destination;\n files.timings = outputOptions.timings || false;\n files.metrics = outputOptions.metrics || false;\n } else if (typeof outputOptions === 'string') {\n destination = outputOptions;\n }\n\n const outputPath = path.resolve(cwd, destination);\n\n try {\n const errors: { [key: string]: Error } = {};\n const filesToWrite: FilesToWrite = {};\n\n if (files.timings && report?.timings) {\n filesToWrite.timings = {\n content: {\n tapables: report.timings.tapables\n ? Array.from(report.timings.tapables.values())\n : null,\n loaders: report.timings.loaders\n ? Array.from(report.timings.loaders.values())\n : null,\n modules: report.timings.modules\n ? Array.from(report.timings.modules.values())\n : null,\n },\n };\n }\n\n if (files.metrics) {\n filesToWrite.metrics = { content: Array.from(metrics) };\n }\n\n const proms = Object.entries(filesToWrite).map(async ([filename, file]): Promise<void> => {\n const start = Date.now();\n log.debug(`Start writing ${filename}.json.`);\n try {\n await outputJson(path.join(outputPath, `${filename}.json`), file.content);\n log.debug(`Wrote ${filename}.json in ${formatDuration(Date.now() - start)}`);\n } catch (e: any) {\n log.error(\n `Failed to write ${filename}.json in ${formatDuration(Date.now() - start)}`,\n );\n errors[filename] = e;\n }\n });\n\n // We can't use Promise.allSettled because we want to support NodeJS 10+\n await Promise.all(proms);\n log.debug(`Wrote files in ${formatDuration(Date.now() - startWriting)}.`);\n // If we had some errors.\n const fileErrored = Object.keys(errors);\n if (fileErrored.length) {\n log.error(\n `Couldn't write files.\\n${fileErrored.map(\n (file) => ` - ${file}: ${errors[file].toString()}`,\n )}`,\n );\n }\n } catch (e) {\n log.error(`Couldn't write files. ${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 { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type { Logger, Entry, GlobalContext, Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\nimport type { Report, TimingsMap } from '../../types';\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, report?: Report) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (report) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', report.timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', report.timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', report.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 { formatModuleName, getValueContext } from '@dd/telemetry-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/telemetry-plugin/constants';\nimport type { TimingsMap, Timing, Value } from '@dd/telemetry-plugin/types';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\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 // Skip the current plugin.\n if (plugin.name.includes(PLUGIN_NAME)) {\n continue;\n }\n\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 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 });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap });\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 { BundlerContext } from '@dd/telemetry-plugin/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n bundlerContext: BundlerContext,\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n globalContext.build.start = Date.now();\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.cwd);\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, modules } = getPluginsResults();\n timeResult.end();\n\n bundlerContext.report = {\n timings: {\n tapables: plugins,\n modules,\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 { getDisplayName, getModuleName, getLoaderNames } from '@dd/telemetry-plugin/common/helpers';\nimport type { Module, Event, Timing, Compilation, TimingsMap } from '@dd/telemetry-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 { getPluginName, getValueContext } from '@dd/telemetry-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/telemetry-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TimingsMap,\n ValueContext,\n TAP_TYPES,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n Timing,\n} from '@dd/telemetry-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 5 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/telemetry-plugin/constants';\nimport type { Compilation, BundlerContext } from '@dd/telemetry-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n bundlerContext: BundlerContext,\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n globalContext.build.start = Date.now();\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.cwd);\n const loaders = new Loaders(globalContext.cwd);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack 4 and 5 nonsense.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack 4 and 5 nonsense.\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 (compilation) => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n bundlerContext.report = {\n timings: {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\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 { GetPlugins, PluginOptions } from '@dd/core/types';\n\nimport { addMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getOptionsDD, validateOptions } from './common/helpers';\nimport { outputFiles } from './common/output/files';\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 { BundlerContext, Filter, Metric, MetricToSend, TelemetryOptions } 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 TelemetryOptions: TelemetryOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n const bundlerContext: BundlerContext = {\n start: Date.now(),\n };\n\n const validatedOptions = validateOptions(options);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is disabled, return an empty array.\n if (validatedOptions.disabled) {\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(bundlerContext, context, log),\n webpack: getWebpackPlugin(bundlerContext, context),\n rspack: getWebpackPlugin(bundlerContext, context),\n };\n const timeBuild = log.time('build', { start: false });\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-telemetry-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n // Move as much as possible in the universal plugin.\n async writeBundle() {\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 metrics: Set<MetricToSend> = new Set();\n const optionsDD = getOptionsDD(validatedOptions);\n\n const timeMetrics = log.time(`aggregating metrics`);\n addMetrics(context, optionsDD, metrics, bundlerContext.report);\n timeMetrics.end();\n\n // TODO Extract the files output in an internal plugin.\n const timeWrite = log.time(`writing to files`);\n await outputFiles(\n { report: bundlerContext.report, metrics },\n validatedOptions.output,\n log,\n context.bundler.outDir,\n );\n timeWrite.end();\n const timeReport = log.time('outputing report');\n outputTexts(context, log, bundlerContext.report);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metrics,\n { apiKey: context.auth?.apiKey, endPoint: validatedOptions.endPoint },\n log,\n );\n timeSend.end();\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 { doRequest } from '@dd/core/helpers/request';\nimport type { Logger } from '@dd/core/types';\nimport type { MetricToSend } from '@dd/telemetry-plugin/types';\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; endPoint: 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 const metricIterations: Map<string, number> = new Map();\n for (const metric of metrics) {\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 ${metrics.size} metrics.\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `${auth.endPoint}/api/v1/series?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: Array.from(metrics) } satisfies {\n series: MetricToSend[];\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 PLUGIN_NAME: PluginName = 'datadog-analytics-plugin' as const;\nexport const INTAKE_PATH = 'v1/input/pub44d5f4eb86e1392037b7501f7adc540e';\nexport const INTAKE_HOST = 'browser-http-intake.logs.datadoghq.com';\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 { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\n\nimport { INTAKE_HOST, INTAKE_PATH, PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getAnalyticsPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = arg.context.getLogger(PLUGIN_NAME);\n\n context.sendLog = async (message: string, overrides: Record<string, string> = {}) => {\n // Only send logs in production.\n if (context.env !== 'production') {\n return;\n }\n\n try {\n const bundler = {\n name: context.bundler.name,\n version: context.bundler.version,\n };\n\n await 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 data = {\n ddsource: `@datadog/${bundler.name}-plugin`,\n env: context.env,\n message,\n service: 'build-plugins',\n bundler,\n metadata: context.build.metadata,\n plugins: context.pluginNames,\n version: context.version,\n team: 'language-foundations',\n ...overrides,\n };\n return {\n data: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json',\n },\n };\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 // Send a log.\n await context.sendLog('Build started');\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 { BundlerFullName, 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.cwd,\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: BundlerFullName) =>\n ['rspack', 'webpack4', 'webpack5', '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\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n let closestPackage;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closestPackage) {\n const packagePath = path.resolve(current, `package.json`);\n // Check if package.json exists in the current directory.\n if (existsSync(packagePath)) {\n closestPackage = packagePath;\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 closestPackage;\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 // We include the CWD because it's part of the paths we want to compare.\n if (cwd) {\n dirsToCompare.push(cwd);\n }\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 { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { GlobalContext } from '@dd/core/types';\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 (out dir and cwd).\nexport const cleanName = (context: GlobalContext, 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 getAbsolutePath(context.cwd, context.bundler.outDir),\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>, cwd: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(cwd, 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, 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((result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const cwd = context.cwd;\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, cwd);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, cwd);\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(cwd, 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(cwd, filename);\n const name = cleanName(context, 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(cwd, filename);\n const cleanedName = cleanName(context, 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 = reportInputsIndexed[getAbsolutePath(cwd, 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(cwd, 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(cwd, getRealPathFromInjectionProxy(output.entryPoint))\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) : cwd;\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(context, 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) : cwd;\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 context.hook('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 let importsReport: Record<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = {};\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds (eg. dev server).\n importsReport = {};\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[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[cleanId] = report;\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n writeBundle(options, bundle) {\n const timeBuildReport = log.time('build report');\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const tempOutputsImports: Record<string, Output> = {};\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n // Complete the importsReport with missing dependents and dependencies.\n const timeCompleteDeps = log.time('completing dependencies and dependents');\n for (const [filepath, { dependencies, dependents }] of Object.entries(importsReport)) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n if (!importsReport[cleanedDependency]) {\n importsReport[cleanedDependency] = {\n dependencies: new Set(),\n dependents: new Set(),\n };\n }\n\n if (importsReport[cleanedDependency].dependents.has(filepath)) {\n continue;\n }\n\n importsReport[cleanedDependency].dependents.add(filepath);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n if (!importsReport[cleanedDependent]) {\n importsReport[cleanedDependent] = {\n dependencies: new Set(),\n dependents: new Set(),\n };\n }\n\n if (importsReport[cleanedDependent].dependencies.has(filepath)) {\n continue;\n }\n\n importsReport[cleanedDependent].dependencies.add(filepath);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n const timeInputsOutputs = log.time('filling inputs and outputs');\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(context.bundler.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 = {\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.push(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 = {\n name: cleanName(context, 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\n reportInputsIndexed[moduleFile.filepath] = moduleFile;\n inputs.push(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 const importReport = importsReport[cleanedImport];\n if (!importReport) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports[\n getAbsolutePath(context.bundler.outDir, cleanedImport)\n ] = file;\n continue;\n }\n\n if (reportInputsIndexed[cleanedImport]) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = {\n name: cleanName(context, 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\n reportInputsIndexed[importFile.filepath] = importFile;\n inputs.push(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.push({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n reportOutputsIndexed[file.filepath] = file;\n outputs.push(file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of Object.entries(tempOutputsImports)) {\n const outputReport = reportOutputsIndexed[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 const timeDeps = log.time('filling dependencies and dependents');\n for (const input of inputs) {\n const importReport = importsReport[input.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 = reportInputsIndexed[dependency];\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(context, 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 = reportInputsIndexed[dependent];\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(context, 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.length) {\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[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 = (filepath: string, allOutputs: Record<string, Output> = {}) => {\n // We already processed it.\n if (allOutputs[filepath]) {\n return allOutputs;\n }\n const filename = cleanName(context, filepath);\n\n // Get its output.\n const foundOutput = reportOutputsIndexed[filepath];\n if (!foundOutput) {\n // If it's been reported in the indexes, it means it's an external here.\n const isExternal = !!reportInputsIndexed[filename];\n // Do not log about externals, we don't expect to find them.\n if (!isExternal) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs[filepath] = foundOutput;\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(context, 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(context.bundler.outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n const timeEntries = log.time('filling entries');\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Object.values(entryOutputs);\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 entries.push(entryFile);\n }\n timeEntries.end();\n\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n context.hook('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.includes('/webpack4/buildin/') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack 4 and 5.\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, 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.tap(PLUGIN_NAME, (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 chunkGraph\n ? // @ts-expect-error: Reconciliating Webpack 4, Webpack 5 and Rspack is hard.\n chunkGraph?.getChunkModules(chunk)\n : // This one is for webpack 4.\n 'getModules' in chunk && typeof chunk.getModules === 'function'\n ? (chunk.getModules() as Module[])\n : []\n )\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 // 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((chunk: Chunk) =>\n chunkGraph\n ? // @ts-expect-error: Reconciliating Webpack 4, Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk)\n : // This one is for webpack 4.\n 'hasEntryModule' in chunk &&\n typeof chunk.hasEntryModule === 'function'\n ? chunk.hasEntryModule()\n : 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 context.hook('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 {\n getAbsolutePath,\n getNearestCommonDirectory,\n getHighestPackageJsonDir,\n} from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\n// Compute the CWD based on a list of directories and the outDir.\nconst getCwd = (dirs: Set<string>, outDir: string) => {\n const highestPackage = getHighestPackageJsonDir(outDir);\n if (highestPackage) {\n return highestPackage;\n }\n\n // Fall back to the nearest common directory.\n const nearestDir = getNearestCommonDirectory(Array.from(dirs));\n if (nearestDir !== path.sep) {\n return nearestDir;\n }\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 context.bundler.outDir = compiler.options.output.path;\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.cwd = compiler.options.context;\n }\n context.hook('cwd', context.cwd);\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 directories: Set<string> = new Set();\n const handleOutputOptions = (outputOptions: any) => {\n if (!outputOptions) {\n return;\n }\n\n if (outputOptions.dir) {\n context.bundler.outDir = outputOptions.dir;\n directories.add(outputOptions.dir);\n } else if (outputOptions.file) {\n context.bundler.outDir = path.dirname(outputOptions.file);\n directories.add(context.bundler.outDir);\n }\n\n // We need an absolute path for rollup because of the way we have to compute its CWD.\n // It's relative to process.cwd(), because there is no cwd options for rollup.\n context.bundler.outDir = getAbsolutePath(process.cwd(), context.bundler.outDir);\n\n // Vite has the \"root\" option we're using.\n if (context.bundler.name === 'vite') {\n return;\n }\n\n context.cwd = getCwd(directories, context.bundler.outDir) || context.cwd;\n context.hook('cwd', context.cwd);\n };\n\n const rollupPlugin: () => PluginOptions['rollup'] = () => {\n return {\n options(options) {\n context.bundler.rawConfig = options;\n if (options.input) {\n if (Array.isArray(options.input)) {\n for (const input of options.input) {\n directories.add(path.dirname(input));\n }\n } else if (typeof options.input === 'object') {\n for (const input of Object.values(options.input)) {\n directories.add(path.dirname(input));\n }\n } else if (typeof options.input === 'string') {\n directories.add(path.dirname(options.input));\n } else {\n throw new Error('Invalid input type');\n }\n }\n\n if ('output' in options) {\n const outputOptions = Array.isArray(options.output)\n ? options.output\n : [options.output];\n for (const output of outputOptions) {\n handleOutputOptions(output);\n }\n }\n\n context.hook('bundlerReport', context.bundler);\n },\n };\n };\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.outdir) {\n context.bundler.outDir = build.initialOptions.outdir;\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = path.dirname(build.initialOptions.outfile);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (build.initialOptions.absWorkingDir) {\n context.cwd = build.initialOptions.absWorkingDir;\n }\n context.hook('cwd', context.cwd);\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 and Rollup have (almost) the same API.\n // They don't really support the CWD concept,\n // so we have to compute it based on existing configurations.\n // The basic idea is to compare input vs output and keep the common part of the paths.\n vite: {\n ...(rollupPlugin() as PluginOptions['vite']),\n config(config) {\n if (config.build?.outDir) {\n context.bundler.outDir = config.build.outDir;\n }\n\n if (config.root) {\n context.cwd = config.root;\n } else {\n context.cwd = getCwd(directories, context.bundler.outDir) || context.cwd;\n }\n\n context.hook('cwd', context.cwd);\n },\n },\n rollup: rollupPlugin(),\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 { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\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 return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n async buildStart() {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n const timeGit = log.time('get git information');\n // Add git information to the context.\n const repositoryData = await getRepositoryData(await newSimpleGit(context.cwd));\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\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","// 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 { getUniqueId } from '@dd/core/helpers/strings';\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 } 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 const filePath = `${getUniqueId()}.${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.cwd,\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.cwd, p);\n })\n .filter(Boolean) as string[];\n\n // Write the content.\n const proms = outputs.map(async (output) => {\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 });\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 { getUniqueId } from '@dd/core/helpers/strings';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport { createRequire } from 'module';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, addInjections } from './helpers';\nimport type { ContentsToInject } from './types';\n\n// A way to get the correct ConcatSource from either the bundler (rspack and webpack 5)\n// or from 'webpack-sources' for webpack 4.\nconst getConcatSource = (bundler: any): typeof import('webpack-sources').ConcatSource => {\n if (!bundler?.sources?.ConcatSource) {\n // We need to require it as if we were \"webpack\", hence the createRequire from 'webpack'.\n // This way, we don't have to declare them in our (peer)dependencies and always use the one\n // that is compatible with the 'webpack' we're currently using.\n const webpackRequire = createRequire(require.resolve('webpack'));\n return webpackRequire('webpack-sources').ConcatSource;\n }\n return bundler.sources.ConcatSource;\n};\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 const ConcatSource = getConcatSource(bundler);\n const filePath = path.resolve(\n context.bundler.outDir,\n `${getUniqueId()}.${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 // Webpack4 doesn't have the \"shutdown\" hook.\n if (compiler.hooks.shutdown) {\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n } else {\n compiler.hooks.done.tap(PLUGIN_NAME, hookFn);\n compiler.hooks.failed.tap(PLUGIN_NAME, hookFn);\n }\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 isWebpack4 = context.bundler.fullName === 'webpack4';\n\n // Webpack 4 doesn't support the \"import\" property.\n const injectedEntry = isWebpack4\n ? filePath\n : {\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 // @ts-expect-error - Badly typed for strings.\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.cwd);\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(\n banner,\n '\\n',\n // @ts-expect-error - This is webpack / rspack typing conflict.\n old,\n '\\n',\n footer,\n );\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 if (compilation.hooks.processAssets) {\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n } else {\n // @ts-expect-error - \"optimizeChunkAssets\" is for webpack 4.\n compilation.hooks.optimizeChunkAssets.tap({ name: PLUGIN_NAME }, hookCb);\n }\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 { isXpack } from '@dd/core/helpers/bundlers';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\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.fullName)) {\n plugin.loadInclude = (id) => {\n if (isInjectionFile(id)) {\n return true;\n }\n\n return null;\n };\n\n plugin.load = (id) => {\n if (isInjectionFile(id)) {\n return {\n code: getContentToInject(contentsToInject[InjectPosition.MIDDLE]),\n };\n }\n return null;\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.cwd);\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 if (compiler.hooks.shutdown) {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n } else {\n // Webpack 4 only.\n compiler.hooks.done.tapPromise(PLUGIN_NAME, bothHookFns);\n compiler.hooks.failed.tap(PLUGIN_NAME, syncHookFn);\n }\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 FactoryMeta,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPlugins,\n GlobalContext,\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 { HOST_NAME } from '@dd/core/constants';\n// #imports-injection-marker\nimport * as errorTracking from '@dd/error-tracking-plugin';\nimport * as rum from '@dd/rum-plugin';\nimport * as telemetry from '@dd/telemetry-plugin';\nimport { getAnalyticsPlugins } from '@dd/internal-analytics-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 RumTypes } from '@dd/rum-plugin';\nexport type { types as TelemetryTypes } from '@dd/telemetry-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [telemetry.CONFIG_KEY]: telemetry.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 // Create the global context.\n const context: GlobalContext = getContext({\n start,\n options,\n // We need to account for how each bundler exposes its version.\n // - (webpack|esbuild|vite).version\n // - rollup.VERSION\n // - rspack.rspackVersion\n bundlerVersion: bundler.rspackVersion || bundler.version || bundler.VERSION,\n bundlerName: unpluginMetaContext.framework as BundlerName,\n version,\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 ['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 ['rum', rum.getPlugins],\n ['telemetry', telemetry.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 }),\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 RumTypes,\n TelemetryTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport rollup from 'rollup';\n\nimport pkg from '../package.json';\n\nexport type RollupPluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n RumTypes,\n TelemetryTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogRollupPlugin = factory.buildPluginFactory({\n bundler: rollup,\n version: pkg.version,\n}).rollup;\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 { ALL_ENVS } from '@dd/core/constants';\nimport type {\n BuildReport,\n BundlerFullName,\n BundlerName,\n Env,\n FactoryMeta,\n GlobalContext,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nimport { getLoggerFactory } from './logger';\n\nexport const getContext = ({\n start,\n options,\n bundlerName,\n bundlerVersion,\n version,\n}: {\n start: number;\n options: OptionsWithDefaults;\n bundlerName: BundlerName;\n bundlerVersion: string;\n version: FactoryMeta['version'];\n}): GlobalContext => {\n const cwd = process.cwd();\n const variant = bundlerName === 'webpack' ? bundlerVersion.split('.')[0] : '';\n const build: BuildReport = {\n errors: [],\n warnings: [],\n logs: [],\n metadata: options.metadata || {},\n timings: [],\n bundler: {\n name: bundlerName,\n fullName: `${bundlerName}${variant}` as BundlerFullName,\n variant,\n version: bundlerVersion,\n },\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: Env = ALL_ENVS.includes(passedEnv) ? passedEnv : 'development';\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: cwd,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n cwd,\n env,\n getLogger: getLoggerFactory(build, 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 sendLog: () => {\n throw new Error('SendLog function called before it was initialized.');\n },\n plugins: [],\n start,\n version,\n };\n\n return context;\n};\n"],"names":["INJECTED_FILE","ALL_ENVS","HOST_NAME","outputFile","async","filepath","data","dir","fsp","mkdir","recursive","path","dirname","writeFile","encoding","outputFileSync","fs","mkdirSync","writeFileSync","existsSync","error","code","getFile","options","openAsBlob","blob","type","contentType","File","filename","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","cleanPluginName","name","replace","isInjectionFile","includes","formatDuration","duration","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","URL","cleanPath","pathname","protocol","host","index","getUniqueId","now","performance","logPriority","debug","info","warn","none","getLoggerFactory","build","logLevel","cleanedName","split","map","join","cleanName","log","text","color","c","dim","logFn","console","red","yellow","cyan","prefix","metadata","bundler","fullName","content","JSON","stringify","logs","push","pluginName","message","time","errors","warnings","getLogger","subName","logger","label","opts","level","start","toLog","tags","timer","spans","total","timings","getUncompleteSpans","filter","span","end","resume","startTime","pause","pauseTime","uncompleteSpans","param","endTime","reduce","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","HOOKS_TO_TRACE","wrapHook","hookName","hook","args","result","Promise","finally","wrapGetPlugins","context","getPlugins","arg","initTimer","wrappedPlugins","plugin","wrappedPlugin","wrapPlugin","pluginNames","CONFIG_KEY","PLUGIN_NAME","decomposePath","sourcemapFilePath","extname","Error","chalk","green","bold","minifiedFilePath","relativePath","relative","outDir","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","minifiedPathPrefix","ERROR_CODES_NO_RETRY","doRequest","auth","method","getData","retryOpts","retries","onRetry","maxTimeout","minTimeout","retry","bail","attempt","response","requestInit","duplex","requestHeaders","apiKey","appKey","headers","body","fetch","ok","errorMessage","status","statusText","json","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","pathParts","prefixParts","normalizedPath","i","partialPrefix","getPayload","sourcemap","git","resultMinFile","resultSourcemap","all","file","repeatedPrefix","getSourcemapValidity","Map","value","minified_url","set","files","trackedFilesMatcher","matchSourcemap","reason","basename","hash","repository_url","remote","version","payload","defaultHeaders","form","FormData","gz","createGzip","key","Blob","append","req","Request","fromWeb","pipe","Object","fromEntries","entries","sendSourcemaps","sourcemaps","git_repository_url","git_commit_sha","plugin_version","project_path","service","releaseVersion","payloads","flat","errorMsg","bailOnError","uploadErrors","uploadWarnings","queue","PQueue","default","concurrency","maxConcurrency","addPromises","get","add","intakeUrl","warningMessage","e","onIdle","upload","toString","fileMetadata","uploadSourcemaps","configurationString","sourcemapsTime","outputs","endsWith","getSourcemapsFiles","summary","outdent","sendTime","defaultIntakeUrl","process","env","DATADOG_SITE","validateSourcemapsOptions","config","validatedOptions","toReturn","validateMinifiedPathPrefix","sourcemapsWithDefaults","disableGit","dryRun","DATADOG_SOURCEMAP_INTAKE_URL","timeOptions","sourcemapsResults","disabled","validateOptions","enforce","writeBundle","totalTime","InjectPosition","InjectPosition2","PRIVACY_HELPERS_MODULE_ID","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","attributes","client_token","validateSDKOptions","sdkWithDefault","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","site","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacy","privacyWithDefault","exclude","include","addToDictionaryFunctionName","helpersModule","sdkResults","privacyResults","plugins","inject","position","MIDDLE","__dirname","privacyPlugin","pluginOptions","transformOptions","input","module","jsx","typescript","addToDictionaryHelper","import","cjsModule","esmModule","func","buildTransformOptions","transformFilter","createFilter","privacyHelpersModuleId","source","id","loadInclude","load","privacyHelpersPath","readFileSync","transformInclude","transform","output","inlineSourceMap","embedCodeInSourceMap","instrument","getPrivacyPlugin","defaultFilters","metric","test","some","thresholds","count","getMetric","points","timestamp","formatCwd","cwd","getDisplayName","pop","formatModuleName","getModuleName","compilation","userRequest","issuer","moduleGraph","getIssuer","_identifier","getModulePath","formatLoaderName","loader","getValueContext","constructor","addMetrics","globalContext","optionsDD","metricsToSend","report","metrics","Set","tapables","values","pluginDuration","pluginCount","events","hookDuration","v","addPluginMetrics","loaders","increment","addLoaderMetrics","inputs","nbWarnings","nbErrors","entriesPerInput","assetsPerInput","entriesPerAsset","entry","has","cleanAssetName","entryName","assetName","dependencies","dependents","addUniversalMetrics","filters","filteredMetric","outputFiles","outputOptions","startWriting","destination","outputPath","resolve","filesToWrite","Array","from","modules","proms","dataString","outputJson","fileErrored","keys","numColor","nameColor","sortDesc","attr","a","b","aVal","bVal","getTimingValues","times","sort","durationsToPrint","top","outputTexts","valuesToPrint","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","serializedReport","jsonReport","writeDuration","newEntry","newInput","dependency","dependent","newOutput","serializeBuildReport","fileDependencies","fileDependents","dependenciesSet","dependentsSet","dep","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","prettyBytes","getModulesValues","nbModules","nbAssets","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","flatMap","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","FN_TO_WRAP","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","fn","cb","pluginTiming","initialFunction","modulePath","moduleTiming","statsObject","getEsbuildPlugin","bundlerContext","setup","initialOptions","metafile","timeWrap","initialPlugins","oldSetup","esbuild","wrapPlugins","onEnd","timeResult","Loaders","this","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","loaderTiming","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","current","getPromiseTapPatch","checkNewHooks","returnValue","apply","then","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","scope","call","newFn","replaceTaps","tap","tapAsync","tapPromise","patchHook","_fakeHook","patchHooks","hooksToPatch","throughHooks","getWebpackPlugin","compiler","HOOK_OPTIONS","compilerTime","thisCompilation","compilationTime","buildModule","succeedModule","failedModule","afterEmit","tapableTimings","loadersTimings","modulesTimings","helpers","realBuildEnd","endPoint","enableTracing","legacyPlugin","webpack","rspack","timeBuild","universalPlugin","buildStart","buildEnd","getOptionsDD","timeMetrics","timeWrite","timeReport","timeSend","metricIterations","metricsNames","nameA","nameB","localeCompare","series","catch","sendMetrics","getAnalyticsPlugins","sendLog","overrides","ddsource","team","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","isArray","fullPath","in","getAllEntryFiles","glob","sync","p","kind","resolveDir","resolved","original","resolutionError","getAbsolutePath","isAbsolute","EXTENSION_RX","QUERY_RX","getType","lastIndex","exec","BUNDLER_SPECIFICS","sep","cleanReport","cleanedReport","reportFilepath","cleanedPath","shift","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","obj","entryNames","resolvedEntries","timeBuildReport","onStart","clear","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","timeDeps","absoluteDependencyPath","dependencyFile","getRollupPlugin","timeModuleParsing","importsReport","onLog","logItem","renderError","moduleParsed","cleanId","newDependencies","dynamicallyImportedIds","importedIds","newDependents","dynamicImporters","importers","bundle","tempOutputsImports","timeCompleteDeps","cleanedDependency","cleanedDependent","timeInputsOutputs","asset","Buffer","byteLength","modulepath","moduleFile","originalLength","importName","cleanedImport","importFile","isEntry","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","getXpackPlugin","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","chunks","assets","getAssets","getChunkFiles","chunk","auxiliaryFiles","f","timeChunks","chunkGraph","chunkModules","getChunkModules","getModules","m","m2","fileModules","outputFound","entrypoint","entrypoints","entryFiles","entryFilename","getChunkEntryModulesIterable","hasEntryModule","getBuildReportPlugins","vite","rollup","getCwd","dirs","highestPackage","currentDir","currentDepth","packagePath","getHighestPackageJsonDir","nearestDir","splitPaths","minLength","parts","commonParts","component","every","getNearestCommonDirectory","xpackPlugin","rawConfig","getBundlerReportPlugins","directories","handleOutputOptions","rollupPlugin","outdir","outfile","absWorkingDir","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","asyncHook","TrackedFilesMatcher","trackedFiles","trackedFilenames","getFilename","list","displaySource","src","srcmapPath","onSourcesNotFound","buff","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","errorTracking","shouldGetGitInfo","timeGit","repositoryData","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","item","commit","author","email","date","committer","getRepositoryData","baseDir","binary","maxConcurrentProcesses","simpleGit","newSimpleGit","DISTANT_FILE_RX","processLocalFile","readFile","processItem","getInjectedValue","timeout","timeoutId","race","clearTimeout","_","reject","setTimeout","processDistantFile","itemId","fallback","getContentToInject","contentToInject","addInjections","toInject","contentsToInject","results","BEFORE","processInjections","promises","onResolve","onLoad","tmpDir","realpathSync","os","tmpdir","absoluteFilePath","injectionRx","RegExp","initialInject","namespace","contents","banner","footer","AFTER","o","TO_INJECT_ID","TO_INJECT_SUFFIX","resolveId","importer","moduleSideEffects","resolution","entryId","getModuleInfo","hasDefaultExport","cache","WeakMap","ConcatSource","createRequire","require","webpackRequire","getConcatSource","rmSync","force","maxRetries","shutdown","done","failed","beforeRun","hookCb","canBeInitial","updateAsset","old","cached","processAssets","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","optimizeChunkAssets","initialEntry","injectedEntry","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","bundlerName","getTrueEndPlugins","asyncHookFn","syncHookFn","bothHookFns","closeBundle","onDispose","telemetry.CONFIG_KEY","telemetry.helpers","datadogRollupPlugin","createUnplugin","unpluginMetaContext","framework","esbuildHostName","bundlerVersion","variant","passedEnv","BUILD_PLUGINS_ENV","getContext","rspackVersion","VERSION","timeInit","pluginsToAdd","customPlugins","errorTracking.getPlugins","rum.getPlugins","telemetry.getPlugins","duplicates","n","factory.buildPluginFactory","pkg","factory.helpers"],"mappings":"igBAMO,MCFMA,EAAgB,wBAEhBC,EAAW,CAAC,cAAe,aAAc,QAazCC,EAAY,wBCYZC,EAAaC,MAAOC,EAAkBC,UAT9BF,OAAOG,GACjBC,EAAIC,MAAMF,EAAK,CAAEG,WAAW,IAS7BD,CAAME,EAAKC,QAAQP,UACnBG,EAAIK,UAA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IACnB,CAAC,MAAOC,IACR,CAAC,YAAaC,KAKlB,IAAA,MAAY99B,EAAM0H,KAAeg2B,EAC7Bj2B,EAAQuM,QAAQpP,QACT4C,EACCC,EACAC,EACA1H,EAHDwH,CAID,CACElD,UACAmD,UACA7I,aAMJ6I,EAAAQ,YAAYrD,QAAQ6C,EAAQuM,QAAQzQ,KAAKuE,GAAWA,EAAO9H,QAGnE,MAAM+9B,EAAa,IAAI7lB,IACnBzQ,EAAQQ,YAAYjC,QACfhG,GAASyH,EAAQQ,YAAYjC,QAAQg4B,GAAMA,IAAMh+B,IAAMyB,OAAS,KAGrE,GAAAs8B,EAAWl+B,KAAO,EAClB,MAAM,IAAI0I,MACN,2BAA2BC,EAAME,KAAKzE,IAAIoW,MAAMC,KAAKyjB,GAAYv6B,KAAK,UAO9E,OAHQiE,EAAAN,KAAK,OAAQM,GACrBg2B,EAASv3B,MAEFuB,EAAQuM,OAAA,GAClB,EC/H8BiqB,CAA2B,CAC1D35B,QAAS4sB,EACTrkB,QAASqxB,KACVhN,OAEUrkB,GAAUqxB,GACVva,GAAUwa"}
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/fs.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","../../../../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","../../../../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/telemetry/src/constants.ts","../../../../plugins/telemetry/src/common/filters.ts","../../../../plugins/telemetry/src/common/helpers.ts","../../../../plugins/telemetry/src/common/aggregator.ts","../../../../plugins/telemetry/src/common/metrics/common.ts","../../../../plugins/telemetry/src/common/output/files.ts","../../../../plugins/telemetry/src/common/output/text.ts","../../../../plugins/telemetry/src/esbuild-plugin/plugins.ts","../../../../plugins/telemetry/src/esbuild-plugin/index.ts","../../../../plugins/telemetry/src/webpack-plugin/loaders.ts","../../../../plugins/telemetry/src/webpack-plugin/tapables.ts","../../../../plugins/telemetry/src/webpack-plugin/index.ts","../../../../plugins/telemetry/src/index.ts","../../../../plugins/telemetry/src/common/sender.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 { Options, OptionsWithDefaults } from '@dd/core/types';\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n return {\n auth: {},\n disableGit: false,\n logLevel: 'warn',\n metadata: {},\n ...options,\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';\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 FULL_NAME_BUNDLERS = [\n 'esbuild',\n 'rollup',\n 'rspack',\n 'vite',\n 'webpack4',\n 'webpack5',\n] 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 { File } from 'buffer';\nimport fsp from 'fs/promises';\nimport fs from 'fs';\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 // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n return outputFile(filepath, dataString);\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 // @ts-expect-error openAsBlob is not in the NodeJS types until 19+\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n // @ts-expect-error openAsBlob is not in the NodeJS types until 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 { INJECTED_FILE } from '@dd/core/constants';\nimport { outputJsonSync } from '@dd/core/helpers/fs';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n GetCustomPlugins,\n GlobalContext,\n Input,\n IterableElement,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\nimport path from 'path';\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// Returns a customPlugin to output some debug files.\ntype CustomPlugins = ReturnType<GetCustomPlugins>;\nexport const debugFilesPlugins = (context: GlobalContext): CustomPlugins => {\n const outputFilePath = () =>\n path.resolve(context.bundler.outDir, `output.${context.bundler.fullName}.json`);\n const reportFilePath = () =>\n path.resolve(context.bundler.outDir, `report.${context.bundler.fullName}.json`);\n const xpackPlugin: IterableElement<CustomPlugins>['webpack'] &\n IterableElement<CustomPlugins>['rspack'] = (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\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 chunkModules: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n reasons: true,\n relatedAssets: true,\n warnings: true,\n });\n outputJsonSync(outputFilePath(), statsJson);\n });\n };\n\n return [\n {\n name: 'build-report',\n enforce: 'post',\n writeBundle() {\n outputJsonSync(reportFilePath(), serializeBuildReport(context.build));\n },\n },\n {\n name: 'bundler-outputs',\n enforce: 'post',\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n outputJsonSync(outputFilePath(), result.metafile);\n });\n },\n },\n rspack: xpackPlugin,\n rollup: {\n writeBundle(options, bundle) {\n outputJsonSync(outputFilePath(), bundle);\n },\n },\n vite: {\n writeBundle(options, bundle) {\n outputJsonSync(outputFilePath(), bundle);\n },\n },\n webpack: xpackPlugin,\n },\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 not disabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n return (\n !!options.errorTracking?.sourcemaps &&\n options.errorTracking?.sourcemaps.disableGit !== true &&\n options.disableGit !== true\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// 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.fullName}|${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.fullName,\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 stores.queue.push(\n getSendLog(data)({ message: content, context: { plugin: name, status: type } }),\n );\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) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\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 pause(endTime);\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 'loadInclude',\n 'resolveId',\n 'transform',\n 'transformInclude',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['cwd', '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 function called by a hook that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = (pluginName: string, hookName: HookName, hook: HookFn, log: Logger) => {\n return (...args: Parameters<HookFn>) => {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n // @ts-expect-error, can't type \"args\" correctly: \"A spread argument must either have a tuple type or be passed to a rest parameter.\"\n const result = hook(...args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n };\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 as PluginHookName];\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 { GlobalContext } 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 options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\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(context.bundler.outDir, minifiedFilePath);\n const minifiedUrl = joinUrlOrPath(options.minifiedPathPrefix, relativePath);\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\n): Sourcemap[] => {\n if (!context.build.outputs || context.build.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.build.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, context, 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 { 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, GlobalContext } 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\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 const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.auth?.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.bundler.fullName}-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.bundler.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.bundler.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.auth!.apiKey },\n url: options.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 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 const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: GlobalContext,\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.bundler.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 context,\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, GlobalContext } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { outdent } from 'outdent';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport { getSourcemapsFiles } from './files';\nimport { sendSourcemaps } from './sender';\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: GlobalContext,\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, context);\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(sourcemaps, options.sourcemaps, context, log);\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\nexport const defaultIntakeUrl = `https://sourcemap-intake.${process.env.DATADOG_SITE || 'datadoghq.com'}/api/v2/srcmap`;\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 disabled: !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 disableGit: false,\n dryRun: false,\n maxConcurrency: 20,\n intakeUrl:\n process.env.DATADOG_SOURCEMAP_INTAKE_URL ||\n validatedOptions.sourcemaps.intakeUrl ||\n defaultIntakeUrl,\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 type { GetPlugins } 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 disabled, return an empty array.\n if (validatedOptions.disabled) {\n return [];\n }\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async writeBundle() {\n if (validatedOptions.disabled) {\n return;\n }\n\n if (validatedOptions.sourcemaps) {\n const totalTime = log.time('sourcemaps process');\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n await uploadSourcemaps(\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n context,\n log,\n );\n totalTime.end();\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\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 { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\nimport type { TelemetryOptions } from '@dd/telemetry-plugin/types';\nimport type * as telemetry from '@dd/telemetry-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, FULL_NAME_BUNDLERS, 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 type Log = {\n bundler?: BundlerFullName;\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 BundlerFullName = (typeof FULL_NAME_BUNDLERS)[number];\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) => 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?: AuthOptions;\n build: BuildReport;\n bundler: BundlerReport;\n cwd: 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 cwd?: HookFn<[string]>;\n init?: HookFn<[GlobalContext]>;\n buildReport?: HookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n syncTrueEnd?: () => void;\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: Options;\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};\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n disableGit?: 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 [rum.CONFIG_KEY]?: RumOptions;\n [telemetry.CONFIG_KEY]?: TelemetryOptions;\n // #types-injection-marker\n customPlugins?: GetCustomPlugins;\n}\n\nexport type GetPluginsOptions = Required<BaseOptions>;\nexport type OptionsWithDefaults = Assign<Options, GetPluginsOptions>;\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?: AuthOptions;\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 fullName: BundlerFullName;\n variant: string; // e.g. Major version of the bundler (webpack 4, webpack 5)\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","// 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_MODULE_ID = '\\0datadog:privacy-helpers';\nexport const PRIVACY_HELPERS_FILE_NAME = 'privacy-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 { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport { createFilter } from '@rollup/pluginutils';\nimport path from 'node:path';\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 | undefined => {\n const log = context.getLogger(PLUGIN_NAME);\n\n if (pluginOptions.disabled) {\n return;\n }\n\n context.inject({\n type: 'file',\n position: InjectPosition.BEFORE,\n value: path.join(__dirname, './privacy-helpers.js'),\n });\n\n const transformOptions = buildTransformOptions(pluginOptions);\n const transformFilter = createFilter(pluginOptions.include, pluginOptions.exclude);\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 transformInclude(id) {\n return transformFilter(id);\n },\n async transform(code, id) {\n try {\n if (['esbuild', 'webpack', 'rspack'].includes(context.bundler.name)) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n return instrument({ id, code }, transformOptions);\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`);\n return {\n code,\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 if (sdkOpts.disabled) {\n return '';\n }\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.datadoghq.com/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 } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { PRIVACY_HELPERS_MODULE_ID } from './privacy/constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type { RumOptions, RumOptionsWithDefaults, SDKOptionsWithDefaults } from './types';\n\nexport const validateOptions = (options: Options, log: Logger): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options, log);\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 disabled: !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\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (options: Options): 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 || validatedOptions.sdk.disabled) {\n return toReturn;\n }\n\n if (validatedOptions.sdk) {\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\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (\n options: Options,\n log: Logger,\n): 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 helpersModule: PRIVACY_HELPERS_MODULE_ID,\n };\n\n toReturn.config = {\n ...privacyWithDefault,\n ...validatedOptions.privacy,\n };\n }\n\n log.debug(\n `datadog-rum-privacy plugin options: ${JSON.stringify(toReturn.config, (_, value) => {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\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 disabled, return an empty array.\n if (validatedOptions.disabled) {\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 const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n if (privacyPlugin) {\n plugins.push(privacyPlugin);\n }\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\nimport type { PrivacyOptionsWithDefaults } from './types';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(\n pluginOptions: PrivacyOptionsWithDefaults,\n): InstrumentationOptions {\n return {\n privacy: {\n addToDictionaryHelper: {\n expression: {\n code: `((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()`,\n },\n // import: {\n // cjsModule: `${pluginOptions.helpersModule}.cjs`,\n // esmModule: `${pluginOptions.helpersModule}.mjs`,\n // func: pluginOptions.addToDictionaryFunctionName ?? '$',\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 { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'telemetry' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-telemetry-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 { Metric } from '@dd/telemetry-plugin/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\n return metric.value > 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 { Options } from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/telemetry-plugin/constants';\nimport type {\n OptionsDD,\n Metric,\n MetricToSend,\n Module,\n Compilation,\n ValueContext,\n TelemetryOptionsWithDefaults,\n} from '@dd/telemetry-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const validateOptions = (opts: Options): TelemetryOptionsWithDefaults => {\n const endPoint = opts[CONFIG_KEY]?.endPoint || 'https://app.datadoghq.com';\n return {\n disabled: !opts[CONFIG_KEY],\n enableTracing: false,\n filters: defaultFilters,\n output: false,\n prefix: '',\n tags: [],\n ...opts[CONFIG_KEY],\n endPoint: endPoint.startsWith('http') ? endPoint : `https://${endPoint}`,\n };\n};\n\nexport const getMetric = (metric: Metric, opts: OptionsDD): MetricToSend => ({\n type: 'gauge',\n tags: [...metric.tags, ...opts.tags],\n metric: `${opts.prefix ? `${opts.prefix}.` : ''}${metric.metric}`,\n points: [[opts.timestamp, metric.value]],\n});\n\nexport const getOptionsDD = (options: TelemetryOptionsWithDefaults): OptionsDD => {\n return {\n timestamp: Math.floor((options.timestamp || Date.now()) / 1000),\n tags: options.tags,\n prefix: options.prefix,\n filters: options.filters,\n };\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 type { GlobalContext } from '@dd/core/types';\nimport type { Metric, MetricToSend, OptionsDD, Report } from '@dd/telemetry-plugin/types';\n\nimport { getMetric } from './helpers';\nimport { addPluginMetrics, addLoaderMetrics } from './metrics/common';\n\nconst addUniversalMetrics = (globalContext: GlobalContext, metrics: Set<Metric>) => {\n const inputs = globalContext.build.inputs || [];\n const outputs = globalContext.build.outputs || [];\n const entries = globalContext.build.entries || [];\n const nbWarnings = globalContext.build.warnings.length;\n const nbErrors = globalContext.build.errors.length;\n const duration = globalContext.build.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 value: outputs.length,\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n value: entries.length,\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n value: nbErrors,\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n value: inputs.length,\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n value: nbWarnings,\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n value: 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 value: input.size,\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n value: input.dependencies.size,\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n value: 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 value: output.size,\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n value: 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 value: entry.size,\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n value: entry.inputs.length,\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n value: entry.outputs.length,\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const addMetrics = (\n globalContext: GlobalContext,\n optionsDD: OptionsDD,\n metricsToSend: Set<MetricToSend>,\n report?: Report,\n): void => {\n const metrics: Set<Metric> = new Set();\n\n if (report) {\n const { timings } = report;\n\n if (timings) {\n if (timings.tapables) {\n addPluginMetrics(timings.tapables, metrics);\n }\n if (timings.loaders) {\n addLoaderMetrics(timings.loaders, metrics);\n }\n }\n }\n\n addUniversalMetrics(globalContext, metrics);\n\n // Format metrics to be DD ready and apply filters\n for (const metric of metrics) {\n if (optionsDD.filters?.length) {\n let filteredMetric: Metric | null = metric;\n for (const filter of optionsDD.filters) {\n // If it's already been filtered out, no need to keep going.\n if (!filteredMetric) {\n break;\n }\n filteredMetric = filter(metric);\n }\n if (filteredMetric) {\n metricsToSend.add(getMetric(filteredMetric, optionsDD));\n }\n } else {\n metricsToSend.add(getMetric(metric, optionsDD));\n }\n }\n\n // Add the number of metrics sent.\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n value: metricsToSend.size + 1,\n tags: [],\n },\n optionsDD,\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, Metric } from '@dd/telemetry-plugin/types';\n\nexport const addPluginMetrics = (plugins: TimingsMap, metrics: Set<Metric>): void => {\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n value: 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 value: hookDuration,\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n value: 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 value: pluginDuration,\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n value: pluginCount,\n tags: [`pluginName:${plugin.name}`],\n });\n }\n};\n\nexport const addLoaderMetrics = (loaders: TimingsMap, metrics: Set<Metric>): void => {\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n value: 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 value: loader.duration,\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n value: loader.increment,\n tags: [`loaderName:${loader.name}`],\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 { outputJson } from '@dd/core/helpers/fs';\nimport { formatDuration } from '@dd/core/helpers/strings';\nimport type { Logger } from '@dd/core/types';\nimport type { MetricToSend, OutputOptions, Report } from '@dd/telemetry-plugin/types';\nimport path from 'path';\n\ntype Files = 'timings' | 'metrics';\n\ntype FilesToWrite = {\n [key in Files]?: { content: any };\n};\n\nexport const outputFiles: (\n data: {\n report?: Report;\n metrics: Set<MetricToSend>;\n },\n outputOptions: OutputOptions,\n log: Logger,\n cwd: string,\n) => Promise<void> = async (data, outputOptions, log, cwd) => {\n // Don't write any file if it's not enabled.\n if (typeof outputOptions !== 'string' && typeof outputOptions !== 'object' && !outputOptions) {\n return;\n }\n\n const { report, metrics } = data;\n\n const startWriting = Date.now();\n let destination = '';\n const files = {\n timings: true,\n metrics: true,\n };\n\n if (typeof outputOptions === 'object') {\n destination = outputOptions.destination;\n files.timings = outputOptions.timings || false;\n files.metrics = outputOptions.metrics || false;\n } else if (typeof outputOptions === 'string') {\n destination = outputOptions;\n }\n\n const outputPath = path.resolve(cwd, destination);\n\n try {\n const errors: { [key: string]: Error } = {};\n const filesToWrite: FilesToWrite = {};\n\n if (files.timings && report?.timings) {\n filesToWrite.timings = {\n content: {\n tapables: report.timings.tapables\n ? Array.from(report.timings.tapables.values())\n : null,\n loaders: report.timings.loaders\n ? Array.from(report.timings.loaders.values())\n : null,\n modules: report.timings.modules\n ? Array.from(report.timings.modules.values())\n : null,\n },\n };\n }\n\n if (files.metrics) {\n filesToWrite.metrics = { content: Array.from(metrics) };\n }\n\n const proms = Object.entries(filesToWrite).map(async ([filename, file]): Promise<void> => {\n const start = Date.now();\n log.debug(`Start writing ${filename}.json.`);\n try {\n await outputJson(path.join(outputPath, `${filename}.json`), file.content);\n log.debug(`Wrote ${filename}.json in ${formatDuration(Date.now() - start)}`);\n } catch (e: any) {\n log.error(\n `Failed to write ${filename}.json in ${formatDuration(Date.now() - start)}`,\n );\n errors[filename] = e;\n }\n });\n\n // We can't use Promise.allSettled because we want to support NodeJS 10+\n await Promise.all(proms);\n log.debug(`Wrote files in ${formatDuration(Date.now() - startWriting)}.`);\n // If we had some errors.\n const fileErrored = Object.keys(errors);\n if (fileErrored.length) {\n log.error(\n `Couldn't write files.\\n${fileErrored.map(\n (file) => ` - ${file}: ${errors[file].toString()}`,\n )}`,\n );\n }\n } catch (e) {\n log.error(`Couldn't write files. ${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 { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type { Logger, Entry, GlobalContext, Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\nimport type { Report, TimingsMap } from '../../types';\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, report?: Report) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (report) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', report.timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', report.timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', report.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 { formatModuleName, getValueContext } from '@dd/telemetry-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/telemetry-plugin/constants';\nimport type { TimingsMap, Timing, Value } from '@dd/telemetry-plugin/types';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\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 // Skip the current plugin.\n if (plugin.name.includes(PLUGIN_NAME)) {\n continue;\n }\n\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 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 });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap });\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 { BundlerContext } from '@dd/telemetry-plugin/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n bundlerContext: BundlerContext,\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n globalContext.build.start = Date.now();\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.cwd);\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, modules } = getPluginsResults();\n timeResult.end();\n\n bundlerContext.report = {\n timings: {\n tapables: plugins,\n modules,\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 { getDisplayName, getModuleName, getLoaderNames } from '@dd/telemetry-plugin/common/helpers';\nimport type { Module, Event, Timing, Compilation, TimingsMap } from '@dd/telemetry-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 { getPluginName, getValueContext } from '@dd/telemetry-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/telemetry-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TimingsMap,\n ValueContext,\n TAP_TYPES,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n Timing,\n} from '@dd/telemetry-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 5 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/telemetry-plugin/constants';\nimport type { Compilation, BundlerContext } from '@dd/telemetry-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n bundlerContext: BundlerContext,\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n globalContext.build.start = Date.now();\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.cwd);\n const loaders = new Loaders(globalContext.cwd);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack 4 and 5 nonsense.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack 4 and 5 nonsense.\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 (compilation) => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n bundlerContext.report = {\n timings: {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\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 { GetPlugins, PluginOptions } from '@dd/core/types';\n\nimport { addMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getOptionsDD, validateOptions } from './common/helpers';\nimport { outputFiles } from './common/output/files';\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 { BundlerContext, Filter, Metric, MetricToSend, TelemetryOptions } 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 TelemetryOptions: TelemetryOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n const bundlerContext: BundlerContext = {\n start: Date.now(),\n };\n\n const validatedOptions = validateOptions(options);\n const plugins: PluginOptions[] = [];\n\n // If the plugin is disabled, return an empty array.\n if (validatedOptions.disabled) {\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(bundlerContext, context, log),\n webpack: getWebpackPlugin(bundlerContext, context),\n rspack: getWebpackPlugin(bundlerContext, context),\n };\n const timeBuild = log.time('build', { start: false });\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-telemetry-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n // Move as much as possible in the universal plugin.\n async writeBundle() {\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 metrics: Set<MetricToSend> = new Set();\n const optionsDD = getOptionsDD(validatedOptions);\n\n const timeMetrics = log.time(`aggregating metrics`);\n addMetrics(context, optionsDD, metrics, bundlerContext.report);\n timeMetrics.end();\n\n // TODO Extract the files output in an internal plugin.\n const timeWrite = log.time(`writing to files`);\n await outputFiles(\n { report: bundlerContext.report, metrics },\n validatedOptions.output,\n log,\n context.bundler.outDir,\n );\n timeWrite.end();\n const timeReport = log.time('outputing report');\n outputTexts(context, log, bundlerContext.report);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metrics,\n { apiKey: context.auth?.apiKey, endPoint: validatedOptions.endPoint },\n log,\n );\n timeSend.end();\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 { doRequest } from '@dd/core/helpers/request';\nimport type { Logger } from '@dd/core/types';\nimport type { MetricToSend } from '@dd/telemetry-plugin/types';\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; endPoint: 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 const metricIterations: Map<string, number> = new Map();\n for (const metric of metrics) {\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 ${metrics.size} metrics.\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `${auth.endPoint}/api/v1/series?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: Array.from(metrics) } satisfies {\n series: MetricToSend[];\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 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 { BundlerFullName, 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.cwd,\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: BundlerFullName) =>\n ['rspack', 'webpack4', 'webpack5', '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\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n let closestPackage;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closestPackage) {\n const packagePath = path.resolve(current, `package.json`);\n // Check if package.json exists in the current directory.\n if (existsSync(packagePath)) {\n closestPackage = packagePath;\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 closestPackage;\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 // We include the CWD because it's part of the paths we want to compare.\n if (cwd) {\n dirsToCompare.push(cwd);\n }\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 { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { GlobalContext } from '@dd/core/types';\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 (out dir and cwd).\nexport const cleanName = (context: GlobalContext, 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 getAbsolutePath(context.cwd, context.bundler.outDir),\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>, cwd: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(cwd, 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, 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((result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const cwd = context.cwd;\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, cwd);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, cwd);\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(cwd, 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(cwd, filename);\n const name = cleanName(context, 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(cwd, filename);\n const cleanedName = cleanName(context, 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 = reportInputsIndexed[getAbsolutePath(cwd, 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(cwd, 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(cwd, getRealPathFromInjectionProxy(output.entryPoint))\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) : cwd;\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(context, 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) : cwd;\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 context.hook('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 let importsReport: Record<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = {};\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds (eg. dev server).\n importsReport = {};\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[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[cleanId] = report;\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n writeBundle(options, bundle) {\n const timeBuildReport = log.time('build report');\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const tempOutputsImports: Record<string, Output> = {};\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n // Complete the importsReport with missing dependents and dependencies.\n const timeCompleteDeps = log.time('completing dependencies and dependents');\n for (const [filepath, { dependencies, dependents }] of Object.entries(importsReport)) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n if (!importsReport[cleanedDependency]) {\n importsReport[cleanedDependency] = {\n dependencies: new Set(),\n dependents: new Set(),\n };\n }\n\n if (importsReport[cleanedDependency].dependents.has(filepath)) {\n continue;\n }\n\n importsReport[cleanedDependency].dependents.add(filepath);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n if (!importsReport[cleanedDependent]) {\n importsReport[cleanedDependent] = {\n dependencies: new Set(),\n dependents: new Set(),\n };\n }\n\n if (importsReport[cleanedDependent].dependencies.has(filepath)) {\n continue;\n }\n\n importsReport[cleanedDependent].dependencies.add(filepath);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n const timeInputsOutputs = log.time('filling inputs and outputs');\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(context.bundler.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 = {\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.push(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 = {\n name: cleanName(context, 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\n reportInputsIndexed[moduleFile.filepath] = moduleFile;\n inputs.push(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 const importReport = importsReport[cleanedImport];\n if (!importReport) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports[\n getAbsolutePath(context.bundler.outDir, cleanedImport)\n ] = file;\n continue;\n }\n\n if (reportInputsIndexed[cleanedImport]) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = {\n name: cleanName(context, 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\n reportInputsIndexed[importFile.filepath] = importFile;\n inputs.push(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.push({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n reportOutputsIndexed[file.filepath] = file;\n outputs.push(file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of Object.entries(tempOutputsImports)) {\n const outputReport = reportOutputsIndexed[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 const timeDeps = log.time('filling dependencies and dependents');\n for (const input of inputs) {\n const importReport = importsReport[input.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 = reportInputsIndexed[dependency];\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(context, 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 = reportInputsIndexed[dependent];\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(context, 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.length) {\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[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 = (filepath: string, allOutputs: Record<string, Output> = {}) => {\n // We already processed it.\n if (allOutputs[filepath]) {\n return allOutputs;\n }\n const filename = cleanName(context, filepath);\n\n // Get its output.\n const foundOutput = reportOutputsIndexed[filepath];\n if (!foundOutput) {\n // If it's been reported in the indexes, it means it's an external here.\n const isExternal = !!reportInputsIndexed[filename];\n // Do not log about externals, we don't expect to find them.\n if (!isExternal) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs[filepath] = foundOutput;\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(context, 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(context.bundler.outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n const timeEntries = log.time('filling entries');\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Object.values(entryOutputs);\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 entries.push(entryFile);\n }\n timeEntries.end();\n\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n context.hook('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.includes('/webpack4/buildin/') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack 4 and 5.\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, 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.tap(PLUGIN_NAME, (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 chunkGraph\n ? // @ts-expect-error: Reconciliating Webpack 4, Webpack 5 and Rspack is hard.\n chunkGraph?.getChunkModules(chunk)\n : // This one is for webpack 4.\n 'getModules' in chunk && typeof chunk.getModules === 'function'\n ? (chunk.getModules() as Module[])\n : []\n )\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 // 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((chunk: Chunk) =>\n chunkGraph\n ? // @ts-expect-error: Reconciliating Webpack 4, Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk)\n : // This one is for webpack 4.\n 'hasEntryModule' in chunk &&\n typeof chunk.hasEntryModule === 'function'\n ? chunk.hasEntryModule()\n : 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 context.hook('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 {\n getAbsolutePath,\n getNearestCommonDirectory,\n getHighestPackageJsonDir,\n} from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\n// Compute the CWD based on a list of directories and the outDir.\nconst getCwd = (dirs: Set<string>, outDir: string) => {\n const highestPackage = getHighestPackageJsonDir(outDir);\n if (highestPackage) {\n return highestPackage;\n }\n\n // Fall back to the nearest common directory.\n const nearestDir = getNearestCommonDirectory(Array.from(dirs));\n if (nearestDir !== path.sep) {\n return nearestDir;\n }\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 context.bundler.outDir = compiler.options.output.path;\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.cwd = compiler.options.context;\n }\n context.hook('cwd', context.cwd);\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 directories: Set<string> = new Set();\n const handleOutputOptions = (outputOptions: any) => {\n if (!outputOptions) {\n return;\n }\n\n if (outputOptions.dir) {\n context.bundler.outDir = outputOptions.dir;\n directories.add(outputOptions.dir);\n } else if (outputOptions.file) {\n context.bundler.outDir = path.dirname(outputOptions.file);\n directories.add(context.bundler.outDir);\n }\n\n // We need an absolute path for rollup because of the way we have to compute its CWD.\n // It's relative to process.cwd(), because there is no cwd options for rollup.\n context.bundler.outDir = getAbsolutePath(process.cwd(), context.bundler.outDir);\n\n // Vite has the \"root\" option we're using.\n if (context.bundler.name === 'vite') {\n return;\n }\n\n context.cwd = getCwd(directories, context.bundler.outDir) || context.cwd;\n context.hook('cwd', context.cwd);\n };\n\n const rollupPlugin: () => PluginOptions['rollup'] = () => {\n return {\n options(options) {\n context.bundler.rawConfig = options;\n if (options.input) {\n if (Array.isArray(options.input)) {\n for (const input of options.input) {\n directories.add(path.dirname(input));\n }\n } else if (typeof options.input === 'object') {\n for (const input of Object.values(options.input)) {\n directories.add(path.dirname(input));\n }\n } else if (typeof options.input === 'string') {\n directories.add(path.dirname(options.input));\n } else {\n throw new Error('Invalid input type');\n }\n }\n\n if ('output' in options) {\n const outputOptions = Array.isArray(options.output)\n ? options.output\n : [options.output];\n for (const output of outputOptions) {\n handleOutputOptions(output);\n }\n }\n\n context.hook('bundlerReport', context.bundler);\n },\n };\n };\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.outdir) {\n context.bundler.outDir = build.initialOptions.outdir;\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = path.dirname(build.initialOptions.outfile);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (build.initialOptions.absWorkingDir) {\n context.cwd = build.initialOptions.absWorkingDir;\n }\n context.hook('cwd', context.cwd);\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 and Rollup have (almost) the same API.\n // They don't really support the CWD concept,\n // so we have to compute it based on existing configurations.\n // The basic idea is to compare input vs output and keep the common part of the paths.\n vite: {\n ...(rollupPlugin() as PluginOptions['vite']),\n config(config) {\n if (config.build?.outDir) {\n context.bundler.outDir = config.build.outDir;\n }\n\n if (config.root) {\n context.cwd = config.root;\n } else {\n context.cwd = getCwd(directories, context.bundler.outDir) || context.cwd;\n }\n\n context.hook('cwd', context.cwd);\n },\n },\n rollup: rollupPlugin(),\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 { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\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 return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n async buildStart() {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n const timeGit = log.time('get git information');\n // Add git information to the context.\n const repositoryData = await getRepositoryData(await newSimpleGit(context.cwd));\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\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","// 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 { getUniqueId } from '@dd/core/helpers/strings';\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 } 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 const filePath = `${getUniqueId()}.${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.cwd,\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.cwd, p);\n })\n .filter(Boolean) as string[];\n\n // Write the content.\n const proms = outputs.map(async (output) => {\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 });\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 { getUniqueId } from '@dd/core/helpers/strings';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport { createRequire } from 'module';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport { getContentToInject, addInjections } from './helpers';\nimport type { ContentsToInject } from './types';\n\n// A way to get the correct ConcatSource from either the bundler (rspack and webpack 5)\n// or from 'webpack-sources' for webpack 4.\nconst getConcatSource = (bundler: any): typeof import('webpack-sources').ConcatSource => {\n if (!bundler?.sources?.ConcatSource) {\n // We need to require it as if we were \"webpack\", hence the createRequire from 'webpack'.\n // This way, we don't have to declare them in our (peer)dependencies and always use the one\n // that is compatible with the 'webpack' we're currently using.\n const webpackRequire = createRequire(require.resolve('webpack'));\n return webpackRequire('webpack-sources').ConcatSource;\n }\n return bundler.sources.ConcatSource;\n};\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 const ConcatSource = getConcatSource(bundler);\n const filePath = path.resolve(\n context.bundler.outDir,\n `${getUniqueId()}.${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 // Webpack4 doesn't have the \"shutdown\" hook.\n if (compiler.hooks.shutdown) {\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n } else {\n compiler.hooks.done.tap(PLUGIN_NAME, hookFn);\n compiler.hooks.failed.tap(PLUGIN_NAME, hookFn);\n }\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 isWebpack4 = context.bundler.fullName === 'webpack4';\n\n // Webpack 4 doesn't support the \"import\" property.\n const injectedEntry = isWebpack4\n ? filePath\n : {\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 // @ts-expect-error - Badly typed for strings.\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.cwd);\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(\n banner,\n '\\n',\n // @ts-expect-error - This is webpack / rspack typing conflict.\n old,\n '\\n',\n footer,\n );\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 if (compilation.hooks.processAssets) {\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n } else {\n // @ts-expect-error - \"optimizeChunkAssets\" is for webpack 4.\n compilation.hooks.optimizeChunkAssets.tap({ name: PLUGIN_NAME }, hookCb);\n }\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 { isXpack } from '@dd/core/helpers/bundlers';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\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.fullName)) {\n plugin.loadInclude = (id) => {\n if (isInjectionFile(id)) {\n return true;\n }\n\n return null;\n };\n\n plugin.load = (id) => {\n if (isInjectionFile(id)) {\n return {\n code: getContentToInject(contentsToInject[InjectPosition.MIDDLE]),\n };\n }\n return null;\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.cwd);\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 if (compiler.hooks.shutdown) {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n } else {\n // Webpack 4 only.\n compiler.hooks.done.tapPromise(PLUGIN_NAME, bothHookFns);\n compiler.hooks.failed.tap(PLUGIN_NAME, syncHookFn);\n }\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 BundlerFullName,\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 rum from '@dd/rum-plugin';\nimport * as telemetry from '@dd/telemetry-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 RumTypes } from '@dd/rum-plugin';\nexport type { types as TelemetryTypes } from '@dd/telemetry-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [telemetry.CONFIG_KEY]: telemetry.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 const bundlerVariant = bundlerName === 'webpack' ? bundlerVersion.split('.')[0] : '';\n\n const data: GlobalData = {\n bundler: {\n name: bundlerName,\n fullName: `${bundlerName}${bundlerVariant}` as BundlerFullName,\n variant: bundlerVariant,\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 ['rum', rum.getPlugins],\n ['telemetry', telemetry.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 RumTypes,\n TelemetryTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport rollup from 'rollup';\n\nimport pkg from '../package.json';\n\nexport type RollupPluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n ErrorTrackingTypes,\n RumTypes,\n TelemetryTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogRollupPlugin = factory.buildPluginFactory({\n bundler: rollup,\n version: pkg.version,\n}).rollup;\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 cwd = 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: cwd,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n cwd,\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":["INJECTED_FILE","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","env","version","bundler","name","metadata","JSON","stringify","outputFile","filepath","dir","fsp","mkdir","recursive","path","dirname","writeFile","encoding","outputFileSync","fs","mkdirSync","writeFileSync","existsSync","code","getFile","options","openAsBlob","blob","contentType","File","filename","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","cleanPluginName","replace","isInjectionFile","formatDuration","duration","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","getUniqueId","now","performance","logPriority","debug","info","warn","none","cleanName","split","map","join","getTimeLogger","store","log","label","level","start","toLog","tags","timer","pluginName","spans","logLevel","total","push","getUncompleteSpans","filter","span","end","resume","startTime","c","dim","cyan","pause","pauseTime","uncompleteSpans","param","endTime","reduce","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","getLoggerFactory","stores","cleanedName","forward","color","logFn","console","red","yellow","prefix","fullName","content","logs","time","errors","warnings","queue","plugin","getLogFn","getLogger","subName","logger","timings","HOOKS_TO_TRACE","wrapHook","hookName","hook","args","Promise","finally","wrapGetPlugins","getPlugins","arg","initTimer","wrappedPlugins","wrappedPlugin","wrapPlugin","pluginNames","CONFIG_KEY","PLUGIN_NAME","decomposePath","sourcemapFilePath","extname","chalk","green","bold","minifiedFilePath","relativePath","relative","outDir","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","minifiedPathPrefix","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","pathParts","prefixParts","normalizedPath","i","partialPrefix","getPayload","sourcemap","git","resultMinFile","resultSourcemap","all","file","repeatedPrefix","getSourcemapValidity","Map","value","minified_url","set","files","trackedFilesMatcher","matchSourcemap","reason","basename","hash","repository_url","remote","defaultHeaders","form","FormData","gz","createGzip","key","Blob","append","req","Request","fromWeb","pipe","Object","fromEntries","entries","sendSourcemaps","sourcemaps","git_repository_url","git_commit_sha","plugin_version","project_path","releaseVersion","payloads","flat","errorMsg","bailOnError","uploadErrors","uploadWarnings","PQueue","default","concurrency","maxConcurrency","addPromises","get","add","intakeUrl","warningMessage","e","onIdle","upload","toString","fileMetadata","uploadSourcemaps","configurationString","sourcemapsTime","build","outputs","endsWith","getSourcemapsFiles","summary","outdent","sendTime","defaultIntakeUrl","process","DATADOG_SITE","validateSourcemapsOptions","config","validatedOptions","toReturn","validateMinifiedPathPrefix","sourcemapsWithDefaults","disableGit","dryRun","DATADOG_SOURCEMAP_INTAKE_URL","timeOptions","sourcemapsResults","disabled","validateOptions","enforce","writeBundle","totalTime","InjectPosition","InjectPosition2","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","attributes","client_token","validateSDKOptions","sdkWithDefault","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","site","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacy","privacyWithDefault","exclude","include","addToDictionaryFunctionName","helpersModule","_","RegExp","sdkResults","privacyResults","plugins","inject","position","MIDDLE","__dirname","privacyPlugin","pluginOptions","BEFORE","transformOptions","addToDictionaryHelper","expression","transformFilter","createFilter","transformInclude","id","transform","output","inlineSourceMap","embedCodeInSourceMap","instrument","getPrivacyPlugin","defaultFilters","metric","test","some","thresholds","count","getMetric","points","timestamp","formatCwd","cwd","getDisplayName","pop","formatModuleName","getModuleName","module","compilation","userRequest","issuer","moduleGraph","getIssuer","_identifier","getModulePath","formatLoaderName","loader","getValueContext","constructor","addMetrics","globalContext","optionsDD","metricsToSend","report","metrics","Set","tapables","values","pluginDuration","pluginCount","events","hookDuration","v","addPluginMetrics","loaders","increment","addLoaderMetrics","inputs","nbWarnings","nbErrors","entriesPerInput","assetsPerInput","entriesPerAsset","entry","input","has","cleanAssetName","entryName","assetName","dependencies","dependents","addUniversalMetrics","filters","filteredMetric","outputFiles","outputOptions","startWriting","destination","outputPath","resolve","filesToWrite","Array","from","modules","proms","dataString","outputJson","fileErrored","keys","numColor","nameColor","sortDesc","attr","a","b","aVal","bVal","getTimingValues","times","sort","durationsToPrint","top","outputTexts","valuesToPrint","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","serializedReport","jsonReport","writeDuration","newEntry","newInput","dependency","dependent","newOutput","serializeBuildReport","fileDependencies","fileDependents","dependenciesSet","dependentsSet","dep","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","prettyBytes","getModulesValues","nbModules","nbAssets","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","flatMap","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","FN_TO_WRAP","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","fn","cb","pluginTiming","initialFunction","modulePath","moduleTiming","statsObject","getEsbuildPlugin","bundlerContext","setup","initialOptions","metafile","timeWrap","initialPlugins","oldSetup","esbuild","wrapPlugins","onEnd","timeResult","Loaders","this","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","loaderTiming","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","current","getPromiseTapPatch","checkNewHooks","returnValue","apply","then","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","scope","call","newFn","replaceTaps","tap","tapAsync","tapPromise","patchHook","_fakeHook","patchHooks","hooksToPatch","throughHooks","getWebpackPlugin","compiler","HOOK_OPTIONS","compilerTime","thisCompilation","compilationTime","buildModule","succeedModule","failedModule","afterEmit","tapableTimings","loadersTimings","modulesTimings","helpers","realBuildEnd","endPoint","enableTracing","legacyPlugin","webpack","rspack","timeBuild","universalPlugin","buildStart","buildEnd","getOptionsDD","timeMetrics","timeWrite","timeReport","timeSend","metricIterations","metricsNames","nameA","nameB","localeCompare","series","catch","sendMetrics","getAnalyticsPlugins","sendLog","buildStartFn","getAsyncQueuePlugins","promise","wrappedPromise","asyncTrueEnd","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","isArray","fullPath","in","getAllEntryFiles","glob","sync","p","kind","resolveDir","resolved","original","resolutionError","getAbsolutePath","isAbsolute","EXTENSION_RX","QUERY_RX","getType","lastIndex","exec","BUNDLER_SPECIFICS","sep","cleanReport","cleanedReport","reportFilepath","cleanedPath","shift","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","obj","entryNames","resolvedEntries","timeBuildReport","onStart","clear","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","timeDeps","absoluteDependencyPath","dependencyFile","getRollupPlugin","timeModuleParsing","importsReport","onLog","logItem","renderError","moduleParsed","cleanId","newDependencies","dynamicallyImportedIds","importedIds","newDependents","dynamicImporters","importers","bundle","tempOutputsImports","timeCompleteDeps","cleanedDependency","cleanedDependent","timeInputsOutputs","asset","Buffer","byteLength","source","modulepath","moduleFile","originalLength","importName","cleanedImport","importFile","isEntry","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","getXpackPlugin","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","chunks","assets","getAssets","getChunkFiles","chunk","auxiliaryFiles","f","timeChunks","chunkGraph","chunkModules","getChunkModules","getModules","m","m2","fileModules","outputFound","entrypoint","entrypoints","entryFiles","entryFilename","getChunkEntryModulesIterable","hasEntryModule","getBuildReportPlugins","vite","rollup","getCwd","dirs","highestPackage","currentDir","currentDepth","packagePath","getHighestPackageJsonDir","nearestDir","splitPaths","minLength","parts","commonParts","component","every","getNearestCommonDirectory","xpackPlugin","rawConfig","getBundlerReportPlugins","directories","handleOutputOptions","rollupPlugin","outdir","outfile","absWorkingDir","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","asyncHook","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","errorTracking","shouldGetGitInfo","timeGit","repositoryData","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","item","commit","author","email","date","committer","getRepositoryData","baseDir","binary","maxConcurrentProcesses","simpleGit","newSimpleGit","DISTANT_FILE_RX","processLocalFile","readFile","processItem","getInjectedValue","timeout","timeoutId","race","clearTimeout","reject","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","o","TO_INJECT_ID","TO_INJECT_SUFFIX","resolveId","importer","moduleSideEffects","resolution","load","entryId","getModuleInfo","hasDefaultExport","cache","WeakMap","ConcatSource","createRequire","require","webpackRequire","getConcatSource","rmSync","force","maxRetries","shutdown","done","failed","beforeRun","hookCb","canBeInitial","updateAsset","old","cached","processAssets","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","optimizeChunkAssets","initialEntry","injectedEntry","import","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","bundlerName","loadInclude","getTrueEndPlugins","asyncHookFn","syncHookFn","bothHookFns","closeBundle","onDispose","telemetry.CONFIG_KEY","telemetry.helpers","datadogRollupPlugin","createUnplugin","unpluginMetaContext","framework","esbuildHostName","passedEnv","BUILD_PLUGINS_ENV","bundlerVersion","rspackVersion","VERSION","bundlerVariant","variant","getContext","timeInit","pluginsToAdd","customPlugins","errorTracking.getPlugins","rum.getPlugins","telemetry.getPlugins","duplicates","n","factory.buildPluginFactory","pkg","factory.helpers"],"mappings":"4eAMO,MCFMA,EAAgB,wBAEhBC,EAAW,CAAC,cAAe,aAAc,QAazCC,EAAY,wBCVZC,EAAuB,CAAC,IAAK,IAAK,KAGlCC,EAAgBC,IACnB,MAAAC,KAAEA,MAAMC,EAAKC,OAAAA,EAAS,cAAOC,EA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