@datadog/webpack-plugin 3.2.12 → 3.3.1-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../core/src/constants.ts","../../../../core/src/helpers/env.ts","../../../../factory/src/validate.ts","../../../../core/src/helpers/site.ts","../../../../core/src/helpers/request.ts","../../../../core/src/helpers/log.ts","../../../../core/src/helpers/plugins.ts","../../../../core/src/helpers/strings.ts","../../../../factory/src/helpers/logger.ts","../../../../factory/src/helpers/wrapPlugins.ts","../../../../core/src/helpers/options.ts","../../../../plugins/apps/src/constants.ts","../../../../plugins/apps/src/validate.ts","../../../../core/src/helpers/fs.ts","../../../../core/src/types.ts","../../../../core/src/helpers/oauth-request.ts","../../../../plugins/apps/src/auth.ts","../../../../plugins/apps/src/backend/ast-parsing/type-guards.ts","../../../../plugins/apps/src/backend/ast-parsing/extract-backend-functions.ts","../../../../plugins/apps/src/backend/encodeQueryName.ts","../../../../plugins/apps/src/backend/proxy-codegen.ts","../../../../plugins/apps/src/backend/shared.ts","../../../../plugins/apps/src/backend/virtual-entry.ts","../../../../plugins/apps/src/backend/ast-parsing/walk-ast.ts","../../../../plugins/apps/src/backend/ast-parsing/module-scope.ts","../../../../plugins/apps/src/backend/ast-parsing/action-catalog-call-sites.ts","../../../../plugins/apps/src/backend/ast-parsing/action-catalog-imports.ts","../../../../plugins/apps/src/backend/ast-parsing/static-definition-resolution.ts","../../../../plugins/apps/src/backend/ast-parsing/static-string-resolution.ts","../../../../plugins/apps/src/backend/ast-parsing/module-graph.ts","../../../../plugins/apps/src/backend/ast-parsing/extract-connection-ids-from-module-graph.ts","../../../../plugins/apps/src/backend/ast-parsing/walk-module-graph.ts","../../../../plugins/apps/src/vite/backend-module-graph-collector.ts","../../../../plugins/apps/src/vite/backend-connection-id-collector.ts","../../../../plugins/apps/src/vite/build-config.ts","../../../../plugins/apps/src/vite/dev-server.ts","../../../../plugins/apps/src/archive.ts","../../../../plugins/apps/src/assets.ts","../../../../core/src/helpers/paths.ts","../../../../plugins/apps/src/identifier.ts","../../../../plugins/apps/src/upload.ts","../../../../plugins/apps/src/vite/handle-upload.ts","../../../../plugins/apps/src/vite/index.ts","../../../../plugins/apps/src/vite/build-backend-functions.ts","../../../../plugins/apps/src/index.ts","../../../../plugins/error-tracking/src/constants.ts","../../../../plugins/error-tracking/src/sourcemaps/files.ts","../../../../plugins/error-tracking/src/sourcemaps/debugId.ts","../../../../plugins/error-tracking/src/sourcemaps/payload.ts","../../../../plugins/error-tracking/src/sourcemaps/upload-metrics.ts","../../../../plugins/error-tracking/src/sourcemaps/sender.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts","../../../../plugins/error-tracking/src/validate.ts","../../../../plugins/error-tracking/src/index.ts","../../../../plugins/live-debugger/src/constants.ts","../../../../plugins/live-debugger/src/runtime-bootstrap.ts","../../../../plugins/live-debugger/src/transform/cjs-interop.ts","../../../../plugins/live-debugger/src/transform/functionId.ts","../../../../plugins/live-debugger/src/transform/instrumentation.ts","../../../../plugins/live-debugger/src/transform/scopeTracker.ts","../../../../plugins/live-debugger/src/transform/index.ts","../../../../plugins/live-debugger/src/types.ts","../../../../plugins/live-debugger/src/validate.ts","../../../../plugins/live-debugger/src/index.ts","../../../../plugins/metrics/src/collector.ts","../../../../plugins/metrics/src/common/filters.ts","../../../../plugins/metrics/src/constants.ts","../../../../plugins/metrics/src/common/helpers.ts","../../../../plugins/metrics/src/common/output/text.ts","../../../../plugins/metrics/src/common/sender.ts","../../../../plugins/metrics/src/esbuild-plugin/plugins.ts","../../../../plugins/metrics/src/esbuild-plugin/index.ts","../../../../plugins/metrics/src/webpack-plugin/loaders.ts","../../../../plugins/metrics/src/webpack-plugin/tapables.ts","../../../../plugins/metrics/src/webpack-plugin/index.ts","../../../../plugins/metrics/src/index.ts","../../../../plugins/metrics/src/common/aggregator.ts","../../../../plugins/output/src/constants.ts","../../../../plugins/output/src/validate.ts","../../../../plugins/output/src/index.ts","../../../../plugins/rum/src/constants.ts","../../../../plugins/rum/src/debugId.ts","../../../../plugins/rum/src/getSourceCodeContextSnippet.ts","../../../../plugins/rum/src/privacy/constants.ts","../../../../plugins/rum/src/privacy/index.ts","../../../../plugins/rum/src/privacy/transform.ts","../../../../plugins/rum/src/sdk.ts","../../../../plugins/rum/src/validate.ts","../../../../plugins/rum/src/index.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","../../../../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\nexport const INJECTED_FILE = '__datadog-helper-file';\nexport const INJECTED_FILE_RX = new RegExp(INJECTED_FILE);\n\nexport const ALL_ENVS = ['development', 'production', 'test'] as const;\nexport const ALL_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack', 'rolldown', 'farm'];\nexport const SUPPORTED_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack'] as const;\n\n// source of truth: site parameter column of the site list in\n// https://docs.datadoghq.com/getting_started/site/\nexport const SITES = [\n 'datadoghq.com',\n 'us3.datadoghq.com',\n 'us5.datadoghq.com',\n 'datadoghq.eu',\n 'ddog-gov.com',\n 'us2.ddog-gov.com',\n 'ap1.datadoghq.com',\n 'ap2.datadoghq.com',\n 'datad0g.com',\n] as const;\n\nexport const DEFAULT_SITE = SITES[0];\n\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 chalk from 'chalk';\n\nimport type { Logger } from '../types';\n\nconst green = chalk.bold.green;\nconst yellow = chalk.bold.yellow;\n\n// All the variables that can be overriden, listed for easier code search:\n// - DD_API_KEY\n// - DATADOG_API_KEY\n// - DD_APP_KEY\n// - DATADOG_APP_KEY\n// - DD_SOURCEMAP_INTAKE_URL\n// - DATADOG_SOURCEMAP_INTAKE_URL\n// - DD_APPS_INTAKE_URL\n// - DATADOG_APPS_INTAKE_URL\n// - DD_APPS_PUBLISH\n// - DATADOG_APPS_PUBLISH\n// - DD_APPS_UPLOAD_ASSETS\n// - DATADOG_APPS_UPLOAD_ASSETS\n// - DD_APPS_VERSION_NAME\n// - DATADOG_APPS_VERSION_NAME\n// - DD_APPS_AUTH_METHOD\n// - DATADOG_APPS_AUTH_METHOD\n// - DD_SITE\n// - DATADOG_SITE\nexport const OVERRIDE_VARIABLES = [\n 'API_KEY',\n 'APP_KEY',\n 'SOURCEMAP_INTAKE_URL',\n 'APPS_INTAKE_URL',\n 'APPS_PUBLISH',\n 'APPS_UPLOAD_ASSETS',\n 'APPS_VERSION_NAME',\n 'APPS_AUTH_METHOD',\n 'SITE',\n] as const;\ntype ENV_KEY = (typeof OVERRIDE_VARIABLES)[number];\n\n// Return the environment variable that would be prefixed with either DATADOG_ or DD_.\nexport const getDDEnvValue = (key: ENV_KEY) => {\n return process.env[`DATADOG_${key}`] || process.env[`DD_${key}`];\n};\n\n// Parse a boolean env var that can be set as 0/1 or false/true (case-insensitive).\n// Returns defaultValue when the variable is not set or the value is unrecognized.\nexport const parseBoolEnv = (value: string | undefined, defaultValue: boolean): boolean => {\n if (value === undefined) {\n return defaultValue;\n }\n const lower = value.toLowerCase();\n if (['1', 'true', 'yes', 'on'].includes(lower)) {\n return true;\n }\n if (['0', 'false', 'no', 'off'].includes(lower)) {\n return false;\n }\n return defaultValue;\n};\n\n// Returns the keys that are defined in the environment.\nexport const getUsedKey = (key: ENV_KEY) => {\n const usedKeys: string[] = [];\n if (process.env[`DD_${key}`]) {\n usedKeys.push(`DD_${key}`);\n }\n if (process.env[`DATADOG_${key}`]) {\n usedKeys.push(`DATADOG_${key}`);\n }\n return usedKeys;\n};\n\n// Keep track of which configurations are overriden by the environment.\nexport const notifyOnEnvOverrides = (log: Logger) => {\n const overridenValues: string[] = [];\n\n for (const value of OVERRIDE_VARIABLES) {\n const usedKeys = getUsedKey(value);\n\n if (\n usedKeys.length > 1 &&\n !usedKeys.every((k) => process.env[k] === process.env[usedKeys[0]])\n ) {\n // Notify if more than one is defined, and that they are different.\n // Resulting in a conflict, given getDDEnvValue() we resolve with DATADOG_${value}.\n const keys = usedKeys.map((k) => yellow(k)).join(' and ');\n const usedKey = yellow(`DATADOG_${value}`);\n log.warn(`Conflicting keys ${keys}, will use ${usedKey}`);\n overridenValues.push(`${keys} (using ${usedKey})`);\n } else if (usedKeys.length) {\n // Key is used with no conflicts.\n const keys = usedKeys.map((k) => green(k)).join(' and ');\n overridenValues.push(`${keys} (same value)`);\n }\n }\n\n if (overridenValues.length) {\n log.info(`Overrides from environment:\\n - ${overridenValues.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 { DEFAULT_SITE } from '@dd/core/constants';\nimport { getDDEnvValue } from '@dd/core/helpers/env';\nimport { parseSite } from '@dd/core/helpers/site';\nimport type {\n AuthOptionsWithDefaults,\n BuildMetadata,\n Options,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nconst SITES_DOC_URL = 'https://docs.datadoghq.com/getting_started/site/';\n\nconst resolveSite = (\n value: string | undefined,\n source: string,\n errors: string[],\n): ReturnType<typeof parseSite> => {\n if (value === undefined) {\n return undefined;\n }\n const parsed = parseSite(value);\n if (parsed) {\n return parsed;\n }\n errors.push(\n `${source} \"${value}\" is not a supported Datadog site. See the site parameters in ${SITES_DOC_URL}.`,\n );\n return undefined;\n};\n\nconst validateMetadata = (metadata: BuildMetadata | undefined): string[] => {\n const errors: string[] = [];\n if (metadata === undefined) {\n return errors;\n }\n // TODO(next-major): also reject non-string `metadata.name`. Skipped today\n // because `metadata.name` has historically been unvalidated (and the root\n // README documents its default as `null`), so adding a type-check here\n // would be a breaking change for users who took the docs literally.\n if (metadata.version !== undefined && typeof metadata.version !== 'string') {\n errors.push('metadata.version must be a string');\n }\n return errors;\n};\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n const errors: string[] = validateMetadata(options.metadata);\n // DATADOG_SITE env var takes precedence over configuration; only validate\n // auth.site when no env var is set, so a stale auth.site can't block a\n // build that has already opted into an env override.\n const envRaw = getDDEnvValue('SITE');\n const resolvedSite =\n resolveSite(envRaw, 'DATADOG_SITE/DD_SITE', errors) ??\n resolveSite(options.auth?.site, 'auth.site', errors);\n\n const auth: AuthOptionsWithDefaults = {\n site: resolvedSite?.site ?? DEFAULT_SITE,\n siteSubdomain: resolvedSite?.subdomain,\n };\n\n if (errors.length) {\n throw new Error(`Invalid Datadog plugin configuration:\\n - ${errors.join('\\n - ')}`);\n }\n\n // Prevent these from being accidentally logged.\n Object.defineProperty(auth, 'apiKey', {\n value: getDDEnvValue('API_KEY') || options.auth?.apiKey,\n enumerable: false,\n });\n\n Object.defineProperty(auth, 'appKey', {\n value: getDDEnvValue('APP_KEY') || options.auth?.appKey,\n enumerable: false,\n });\n\n return {\n enableGit: true,\n logLevel: 'warn',\n metadata: {},\n ...options,\n auth,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { SITES } from '@dd/core/constants';\n\n// A site value can be a bare known site (e.g. \"datadoghq.com\") or a single-label\n// custom subdomain on top of one (e.g. \"myorg.us5.datadoghq.com\"), used by orgs\n// with a custom Datadog URL. Picks the longest (most specific) matching base site\n// so \"myorg.us5.datadoghq.com\" resolves to \"us5.datadoghq.com\", not \"datadoghq.com\".\n// Matching is case-insensitive; the returned site and subdomain are normalized to lowercase.\nexport const parseSite = (\n value: string,\n): { site: (typeof SITES)[number]; subdomain?: string } | undefined => {\n // Config isn't enforced by the type system at runtime (e.g. plain JS configs),\n // so a non-string can reach here despite the `string` signature.\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const lowerValue = value.toLowerCase();\n\n const exactMatch = SITES.find((s) => s === lowerValue);\n if (exactMatch) {\n return { site: exactMatch };\n }\n\n const suffixMatches = SITES.filter((s) => lowerValue.endsWith(`.${s}`));\n if (!suffixMatches.length) {\n return undefined;\n }\n\n const site = suffixMatches.reduce((longest, s) => (s.length > longest.length ? s : longest));\n const subdomain = lowerValue.slice(0, lowerValue.length - site.length - 1);\n if (!subdomain || !/^[a-z0-9-]+$/.test(subdomain)) {\n return undefined;\n }\n\n return { site, subdomain };\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\nconst formatErrorEntry = (e: unknown): string => {\n if (e === null || typeof e !== 'object') {\n return '';\n }\n return Object.entries(e)\n .map(\n ([key, value]) =>\n `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`,\n )\n .join(', ');\n};\n\nconst parseErrorDetails = (bodyText: string): string => {\n try {\n const body: unknown = JSON.parse(bodyText);\n if (body !== null && typeof body === 'object') {\n if ('errors' in body && Array.isArray(body.errors)) {\n const details = body.errors\n .map(formatErrorEntry)\n .filter((s) => s.length > 0)\n .join('\\n');\n if (details) {\n return details;\n }\n } else {\n const entry = formatErrorEntry(body);\n if (entry) {\n return entry;\n }\n }\n }\n } catch {\n // Body is not JSON.\n }\n return bodyText;\n};\n\nexport const getOriginHeaders = (opts: { bundler: string; plugin: string; version: string }) => {\n return {\n 'DD-EVP-ORIGIN': `${opts.bundler}-build-plugin_${opts.plugin}`,\n 'DD-EVP-ORIGIN-VERSION': opts.version,\n };\n};\n\nexport type RequestData = {\n data: ReadableStream;\n headers: Record<string, string>;\n};\n\nexport type FormBuilder = () => Promise<FormData> | FormData;\n\nexport const createRequestData = async (options: {\n getForm: FormBuilder;\n defaultHeaders: Record<string, string>;\n zip?: boolean;\n}): Promise<RequestData> => {\n const { getForm, defaultHeaders = {}, zip = true } = options;\n const form = await getForm();\n\n // Serialize FormData through Request to get a streaming body\n // and auto-generated headers (boundary) that we can forward while piping through gzip.\n const req = new Request('fake://url', { method: 'POST', body: form });\n\n // Use Web Streams pipeThrough instead of Node.js pipe() to keep the pipeline lazy.\n // Node.js pipe() immediately puts the source into flowing mode (starts reading blobs\n // via process.nextTick), which races with cleanup of file-backed blobs after the\n // request completes. Web Streams only start reading when the output is consumed.\n const data = zip ? req.body!.pipeThrough(new CompressionStream('gzip')) : req.body!;\n\n const headers = {\n 'Content-Encoding': zip ? 'gzip' : 'multipart/form-data',\n ...defaultHeaders,\n ...Object.fromEntries(req.headers.entries()),\n };\n\n return { data, headers };\n};\n\nexport const ERROR_CODES_NO_RETRY = [400, 401, 403, 404, 405, 409, 413];\nexport const NB_RETRIES = 5;\n\n// Do a retriable fetch.\nexport const doRequest = async <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 && 'accessToken' in auth) {\n if (auth.accessToken) {\n requestHeaders.Authorization = `Bearer ${auth.accessToken}`;\n }\n } else {\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\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 let errorMessage = `HTTP ${response.status} ${response.statusText}`;\n try {\n const bodyText = await response.text();\n const details = parseErrorDetails(bodyText);\n if (details) {\n errorMessage += `\\n${details}`;\n }\n } catch {\n // Ignore if body cannot be read.\n }\n if (ERROR_CODES_NO_RETRY.includes(response.status)) {\n bail(new Error(errorMessage));\n // bail(error) throws so the return is never executed.\n return {} as T;\n } else {\n // Trigger the retry.\n throw new Error(errorMessage);\n }\n }\n\n try {\n let result;\n // Await it so we catch any parsing error and bail.\n if (type === 'json') {\n result = await response.json();\n } else {\n result = await response.text();\n }\n\n return result as T;\n } catch (error: any) {\n // We don't want to retry on parsing errors.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n }, retryOpts);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '../constants';\nimport type { GlobalData, DdLogOptions } from '../types';\n\nimport { doRequest } from './request';\n\nexport const INTAKE_PATH = 'v1/input/pub44d5f4eb86e1392037b7501f7adc540e';\nexport const INTAKE_HOST = 'browser-http-intake.logs.datadoghq.com';\n\nexport const getSendLog =\n (data: GlobalData) =>\n ({ message, context }: DdLogOptions): Promise<void> => {\n return doRequest({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url: `https://${INTAKE_HOST}/${INTAKE_PATH}`,\n method: 'POST',\n type: 'json',\n getData: async () => {\n const payload = {\n ddsource: data.packageName || HOST_NAME,\n message,\n service: 'build-plugins',\n team: 'language-foundations',\n env: data.env,\n version: data.version,\n bundler: {\n name: data.bundler.name,\n version: data.bundler.version,\n },\n metadata: data.metadata,\n ...context,\n };\n return {\n data: JSON.stringify(payload),\n headers: {\n 'Content-Type': 'application/json',\n },\n };\n },\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n Input,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\n\nexport const cleanPluginName = (name: string) => {\n // Will remove the \"@dd/\", \"@dd/datadog-\", \"@dd/internal-\", \"datadog-\" prefixes and the \"-plugin\" suffix.\n return name.replace(/^@dd\\/(datadog-|internal-)?|^datadog-|-plugin$/g, '');\n};\n\n// Is the file coming from the injection plugin?\nexport const isInjectionFile = (filename: string) => filename.includes(INJECTED_FILE);\n\n// Returns an object that is safe to serialize to JSON.\n// Mostly useful for debugging and testing.\nexport const serializeBuildReport = (report: BuildReport): SerializedBuildReport => {\n // Report is an object that self reference some of its values.\n // To make it JSON serializable, we need to remove the self references\n // and replace them with strings, we'll use \"filepath\" to still have them uniquely identifiable.\n const jsonReport: SerializedBuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n entries: [],\n inputs: [],\n outputs: [],\n };\n\n for (const entry of report.entries || []) {\n const newEntry: SerializedEntry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs.map((file: FileReport) => file.filepath);\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.entries.push(newEntry);\n }\n\n for (const input of report.inputs || []) {\n const newInput: SerializedInput = { ...input, dependencies: [], dependents: [] };\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n newInput.dependencies.push(dependency.filepath);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n newInput.dependents.push(dependent.filepath);\n }\n }\n jsonReport.inputs.push(newInput);\n }\n\n for (const output of report.outputs || []) {\n const newOutput: SerializedOutput = { ...output, inputs: [] };\n if (output.inputs) {\n newOutput.inputs = output.inputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.outputs.push(newOutput);\n }\n\n return jsonReport;\n};\n\n// Returns an object that is unserialized from serializeBuildReport().\n// Mostly useful for debugging and testing.\nexport const unserializeBuildReport = (report: SerializedBuildReport): BuildReport => {\n const buildReport: BuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n };\n\n const reportInputs = report.inputs || [];\n const reportOutputs = report.outputs || [];\n\n const entries: Entry[] = [];\n\n // Prefill inputs and outputs as they are sometimes self-referencing themselves.\n const indexedInputs: Map<string, Input> = new Map();\n const inputs: Input[] = reportInputs.map<Input>((input) => {\n const newInput: Input = {\n ...input,\n // Keep them empty for now, we'll fill them later.\n dependencies: new Set(),\n dependents: new Set(),\n };\n indexedInputs.set(input.filepath, newInput);\n return newInput;\n });\n\n const indexedOutputs: Map<string, Output> = new Map();\n const outputs: Output[] = reportOutputs.map<Output>((output) => {\n const newOutput: Output = { ...output, inputs: [] };\n indexedOutputs.set(output.filepath, newOutput);\n return newOutput;\n });\n\n // Fill in the inputs' dependencies and dependents.\n for (const input of reportInputs) {\n const newInput: Input = indexedInputs.get(input.filepath)!;\n\n // Re-assign the dependencies and dependents to the actual objects.\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n const newDependency = indexedInputs.get(dependency)!;\n newInput.dependencies.add(newDependency);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n const newDependent = indexedInputs.get(dependent)!;\n newInput.dependents.add(newDependent);\n }\n }\n }\n\n // Fill in the outputs' inputs.\n for (const output of reportOutputs) {\n const newOutput: Output = indexedOutputs.get(output.filepath)!;\n if (output.inputs) {\n // Re-assign the inputs to the actual objects.\n newOutput.inputs = output.inputs\n .map<\n // Can be either an input or an output (for sourcemaps).\n Input | Output | undefined\n >((filepath: string) => indexedInputs.get(filepath) || indexedOutputs.get(filepath))\n .filter(Boolean) as (Input | Output)[];\n }\n }\n\n for (const entry of report.entries || []) {\n const newEntry: Entry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs\n .map((filepath: string) => indexedInputs.get(filepath))\n .filter(Boolean) as (Output | Input)[];\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs\n .map((filepath: string) => indexedOutputs.get(filepath))\n .filter(Boolean) as Output[];\n }\n entries.push(newEntry);\n }\n\n return {\n ...buildReport,\n entries,\n inputs,\n outputs,\n };\n};\n\n// Verify that we should get the git information based on the options.\n// Only get git information if sourcemaps are enabled and git is enabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n // If we don't have sourcemaps enabled, we don't need git.\n const gitEnabledFromSourcemaps = !!options.errorTracking?.sourcemaps;\n // If we have the 'enableGit' configuration at the root, use it and default to `true`.\n const gitEnabledFromRoot = options.enableGit ?? true;\n return gitEnabledFromSourcemaps && gitEnabledFromRoot;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport chalk from 'chalk';\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\nexport const normalizeTagValue = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_:./-]+/g, '_')\n .replace(/^_+|_+$/g, '') || 'unknown';\n\nconst formatValue = (value: unknown) => {\n if (value === undefined) {\n return 'undefined';\n }\n\n if (value === null) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n\n return value?.toString() ?? '';\n};\n\nexport const prettyObject = (obj: any) => {\n return Object.entries(obj)\n .map(([key, value]) => ` - ${key}: ${chalk.bold.green(formatValue(value))}`)\n .join('\\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, context } = {}) => {\n // By default (debug) we print dimmed.\n let color = c.dim;\n let logFn = console.log;\n\n if (type === 'error') {\n color = c.red;\n logFn = console.error;\n } else if (type === 'warn') {\n color = c.yellow;\n logFn = console.warn;\n } else if (type === 'info') {\n color = c.cyan;\n logFn = console.log;\n }\n\n const buildName = data.metadata?.name ? `${data.metadata.name}|` : '';\n const prefix = `[${buildName}${type}|${data.bundler.name}|${cleanedName}]`;\n\n // Keep a trace of the log in the build report.\n const content = typeof text === 'string' ? text : JSON.stringify(text, null, 2);\n stores.logs.push({\n bundler: data.bundler.name,\n pluginName: name,\n type,\n message: content,\n time: Date.now(),\n });\n\n if (type === 'error') {\n stores.errors.push(content);\n }\n if (type === 'warn') {\n stores.warnings.push(content);\n }\n\n if (forward) {\n const forwardLog = async () => {\n try {\n const sendLog = getSendLog(data);\n await sendLog({\n message: content,\n context: { plugin: name, status: type, ...context },\n });\n } catch (e) {\n // Log the error using the parent logger.\n const subLogger = getLogFn(name, data, stores, logLevel);\n subLogger(`Error forwarding log: ${e}`, 'debug');\n }\n };\n stores.queue.push(forwardLog());\n }\n\n // Only log if the log level is high enough.\n if (logPriority[type] >= logPriority[logLevel]) {\n logFn(`${color(prefix)} ${content}`);\n }\n };\n};\n\nexport const getTimeLogger = (\n name: string,\n store: GlobalStores['timings'],\n log: LogFn,\n): TimeLog => {\n return (label, opts = {}) => {\n const { level = 'debug', start = true, log: toLog = true, tags = [] } = opts;\n const timer: Timer = {\n pluginName: name,\n label,\n spans: [],\n tags: [...tags, `plugin:${name}`, `level:${level}`],\n logLevel: level,\n total: 0,\n };\n\n // Add it to the build report.\n store.push(timer);\n\n const getUncompleteSpans = () => timer.spans.filter((span) => !span.end);\n\n // Push a new span.\n const resume: TimeLogger['resume'] = (startTime?: number) => {\n // Ignore if there is already an ongoing span.\n const uncompleteSpans = getUncompleteSpans();\n if (uncompleteSpans.length) {\n return;\n }\n\n // Log the start if it's the first span.\n if (!timer.spans.length && toLog) {\n log(c.dim(`[${c.cyan(label)}] : start`), 'debug');\n }\n\n // Add the new span.\n timer.spans.push({\n start: startTime || Date.now(),\n tags: [`plugin:${name}`],\n });\n };\n\n // Complete all the uncompleted spans.\n const pause: TimeLogger['pause'] = (pauseTime?: number, warn: boolean = true) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n if (warn) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\n }\n return;\n }\n\n if (uncompleteSpans.length > 1) {\n log(`Timer ${c.cyan(label)} has more than one ongoing span.`, 'debug');\n }\n\n for (const span of uncompleteSpans) {\n span.end = pauseTime || Date.now();\n }\n };\n\n // End the timer and add it to the build report.\n const end: TimeLogger['end'] = (endTime?: number) => {\n // We don't want to log a warning if the timer is already paused.\n pause(endTime, false);\n // Compute the total duration.\n const duration = timer.spans.reduce((acc, span) => acc + (span.end! - span.start), 0);\n timer.total = duration;\n if (toLog) {\n log(`[${c.cyan(label)}] : ${c.cyan(formatDuration(duration))}`, level);\n }\n };\n\n // Add a tag to the timer or the ongoing spans.\n const tag: TimeLogger['tag'] = (tagsToAdd, tagOpts = {}) => {\n const { span = false } = tagOpts;\n if (span) {\n const uncompleteSpans = getUncompleteSpans();\n for (const uncompleteSpan of uncompleteSpans) {\n uncompleteSpan.tags.push(...tagsToAdd);\n }\n } else {\n timer.tags.push(...tagsToAdd);\n }\n };\n\n // Auto start the timer.\n if (start) {\n let param: number | undefined;\n if (typeof start === 'number') {\n param = start;\n }\n resume(param);\n }\n\n const timeLogger: TimeLogger = {\n timer,\n resume,\n end,\n pause,\n tag,\n };\n\n return timeLogger;\n };\n};\n\nexport const getLoggerFactory =\n (data: GlobalData, stores: GlobalStores, logLevel: LogLevel = 'warn'): GetLogger =>\n (name) => {\n const log = getLogFn(name, data, stores, logLevel);\n return {\n getLogger: (subName: string) => {\n const logger = getLoggerFactory(data, stores, logLevel);\n return logger(`${cleanName(name)}${NAME_SEP}${subName}`);\n },\n time: getTimeLogger(name, stores.timings, log),\n error: (text: any, opts?: LogOptions) => log(text, 'error', opts),\n warn: (text: any, opts?: LogOptions) => log(text, 'warn', opts),\n info: (text: any, opts?: LogOptions) => log(text, 'info', opts),\n debug: (text: any, opts?: LogOptions) => log(text, 'debug', opts),\n };\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '@dd/core/constants';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport type {\n CustomPluginOptions,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPluginsArg,\n GetPlugins,\n GlobalContext,\n Logger,\n PluginOptions,\n GetWrappedPlugins,\n CustomHooks,\n} from '@dd/core/types';\nimport type { UnpluginOptions } from 'unplugin';\n\n// Unplugin universal hooks.\nconst UNPLUGIN_HOOKS = [\n 'buildEnd',\n 'buildStart',\n 'load',\n 'resolveId',\n 'transform',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['buildRoot', 'init', 'buildReport', 'bundlerReport', 'git'] as const;\n\n// All the hooks that we want to trace.\nconst HOOKS_TO_TRACE = [...UNPLUGIN_HOOKS, ...CUSTOM_HOOKS];\n\n// Represents the hook names a plugin can have (including those we're not tracing).\ntype PluginHookName = keyof (PluginOptions | CustomPluginOptions);\n// Represents the custom hook names.\ntype CustomHookName = (typeof CUSTOM_HOOKS)[number];\n// Represents the unplugin hook names.\ntype UnpluginHookName = (typeof UNPLUGIN_HOOKS)[number];\n// Represents the hook names that we want to trace.\ntype HookName = CustomHookName | UnpluginHookName;\n// Represents the hook handler that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = <T extends HookFn>(\n pluginName: string,\n hookName: HookName,\n hook: T,\n log: Logger,\n): T => {\n // Create a wrapper function that adds timing to any hook function\n const wrapWithTiming = <F extends (...args: any[]) => any>(fn: F): F => {\n return function (this: any, ...args) {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n const result = fn.apply(this, args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n } as F;\n };\n\n // Handle object hooks (with filter/handler pattern)\n if (typeof hook === 'object' && hook !== null && 'handler' in hook) {\n return {\n ...hook,\n handler: wrapWithTiming(hook.handler),\n };\n }\n\n // Handle function hooks\n return wrapWithTiming(hook) as T;\n};\n\nexport const wrapPlugin = (plugin: PluginOptions | CustomPluginOptions, log: Logger) => {\n const wrappedPlugin: PluginOptions | CustomPluginOptions = {\n ...plugin,\n };\n const name = cleanPluginName(plugin.name);\n\n // Wrap all the hooks that we want to trace.\n for (const hookName of HOOKS_TO_TRACE) {\n const hook = plugin[hookName];\n if (hook) {\n wrappedPlugin[hookName as PluginHookName] = wrapHook(name, hookName, hook, log);\n }\n }\n\n return wrappedPlugin;\n};\n\nexport const wrapGetPlugins = (\n context: GlobalContext,\n getPlugins: GetPlugins | GetCustomPlugins | GetInternalPlugins,\n name: string,\n): GetWrappedPlugins => {\n const log = context.getLogger(HOST_NAME);\n // Return the getPlugins function wrapped, so we can measure the initialization time.\n return (arg: GetPluginsArg) => {\n // Start our timer.\n const initTimer = log.time(`hook | init ${name}`, { log: false });\n\n // Wrap all the plugins that are returned by the initial getPlugins function.\n const wrappedPlugins = getPlugins(arg).map((plugin) => wrapPlugin(plugin, log));\n\n // Tag our timer with the plugin names.\n const pluginNames = wrappedPlugins.map((plugin) => `plugin:${plugin.name}`);\n initTimer.tag(pluginNames);\n\n // End of initialization.\n initTimer.end();\n return wrappedPlugins;\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\n\nconst warnedKeys = new Set<string>();\n\n/**\n * Resolve the `enable` value for a plugin config key, emitting a deprecation\n * warning when the caller passes a non-boolean truthy/falsy value.\n *\n * Semantics:\n * - Config key absent / undefined / falsy → false (plugin disabled).\n * - Config key is a truthy object without an `enable` property → true.\n * - Config key is a truthy object with `enable` set → coerce to boolean,\n * warning once per key if it isn't already a boolean.\n */\nexport const resolveEnable = <T extends { [K in C]?: unknown }, C extends string>(\n options: T,\n configKey: C,\n log: Logger,\n): boolean => {\n const pluginConfig = options[configKey];\n\n if (pluginConfig && typeof pluginConfig === 'object' && 'enable' in pluginConfig) {\n const value = pluginConfig.enable;\n\n if (typeof value !== 'boolean' && value !== undefined) {\n if (!warnedKeys.has(configKey)) {\n warnedKeys.add(configKey);\n log.warn(\n `\\`${configKey}.enable\\` should be a boolean, got ${typeof value}. ` +\n `Non-boolean values are coerced today but will be rejected in the next major.`,\n );\n }\n }\n\n if (value !== undefined) {\n // TODO(next major): drop this coercion and reject non-boolean `enable`\n // outright. The warning above gives callers one major to migrate.\n return !!value;\n }\n }\n\n return !!pluginConfig;\n};\n\n/** @internal Exposed only for tests to reset the warn-once set between cases. */\nexport const resetEnableWarnings = (): void => {\n warnedKeys.clear();\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 = 'apps' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-apps-plugin' as const;\n\nexport const APPS_API_PATH = 'api/unstable/app-builder-code/apps';\nexport const ARCHIVE_FILENAME = 'datadog-apps-assets.zip';\nexport const BACKEND_FILE_RE = /\\.backend\\.(ts|tsx|js|jsx)$/;\nexport const BACKEND_CODE_EXTENSIONS = [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.mts',\n '.cts',\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 { getDDEnvValue, parseBoolEnv } from '@dd/core/helpers/env';\nimport type { Options } from '@dd/core/types';\n\nimport { CONFIG_KEY } from './constants';\nimport type { AppsOptions, AppsOptionsWithDefaults, AuthMethod } from './types';\n\nconst AUTH_METHODS: AuthMethod[] = ['apiKey', 'oauth'];\n\nconst resolveAuthMethod = (value: string | undefined): AuthMethod | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n if (AUTH_METHODS.includes(value as AuthMethod)) {\n return value as AuthMethod;\n }\n\n throw new Error(`apps.authOverrides.method must be one of: ${AUTH_METHODS.join(', ')}`);\n};\n\nconst hasApiKeyAuth = (options: Options): boolean =>\n Boolean(\n (getDDEnvValue('API_KEY') || options.auth?.apiKey) &&\n (getDDEnvValue('APP_KEY') || options.auth?.appKey),\n );\n\nexport const validateOptions = (options: Options): AppsOptionsWithDefaults => {\n const resolvedOptions = (options[CONFIG_KEY] || {}) as AppsOptions;\n const method =\n resolveAuthMethod(\n getDDEnvValue('APPS_AUTH_METHOD') || resolvedOptions.authOverrides?.method,\n ) || (hasApiKeyAuth(options) ? 'apiKey' : 'oauth');\n\n // Only spread optional app-property fields when explicitly configured — omitting\n // them entirely (rather than setting them to undefined) keeps the returned object\n // shape stable for callers that use hasOwnProperty / 'in' checks. The != null\n // coercion also guards against null values being passed through to the manifest builder.\n return {\n include: resolvedOptions.include || [],\n dryRun: resolvedOptions.dryRun ?? !parseBoolEnv(getDDEnvValue('APPS_UPLOAD_ASSETS'), false),\n identifier: resolvedOptions.identifier?.trim(),\n name: resolvedOptions.name?.trim() || options.metadata?.name?.trim(),\n ...(resolvedOptions.description != null && { description: resolvedOptions.description }),\n ...(resolvedOptions.selfService != null && { selfService: resolvedOptions.selfService }),\n ...(resolvedOptions.permissions != null && { permissions: resolvedOptions.permissions }),\n authOverrides: {\n method,\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 { JsonStreamStringify } from 'json-stream-stringify';\nimport path from 'path';\nimport { Readable } from 'stream';\n\nimport type { FileValidity, LocalAppendOptions } from '../types';\n\n// Replacing fs-extra with local helpers.\n// Delete folders recursively.\nexport const rm = async (dir: string) => {\n return fsp.rm(dir, { force: true, maxRetries: 3, recursive: true });\n};\nexport const rmSync = (dir: string) => {\n return fs.rmSync(dir, { force: true, maxRetries: 3, recursive: true });\n};\n\n// Mkdir recursively.\nexport const mkdir = async (dir: string) => {\n return fsp.mkdir(dir, { recursive: true });\n};\n\nexport const mkdirSync = (dir: string) => {\n return fs.mkdirSync(dir, { recursive: true });\n};\n\n// Write a file but first ensure the directory exists.\nexport const outputFile = async (filepath: string, data: string) => {\n await mkdir(path.dirname(filepath));\n await fsp.writeFile(filepath, data, { encoding: 'utf-8' });\n};\n\nexport const outputFileSync = (filepath: string, data: string) => {\n mkdirSync(path.dirname(filepath));\n fs.writeFileSync(filepath, data, { encoding: 'utf-8' });\n};\n\n// Output a JSON file.\nexport const outputJson = async (filepath: string, data: any) => {\n await mkdir(path.dirname(filepath));\n // Use streams so it doesn't crash on very large data.\n const writable = fs.createWriteStream(filepath);\n const readable = new JsonStreamStringify(data, undefined, 2);\n const prom = new Promise<void>((resolve, reject) => {\n readable.on('end', () => {\n resolve();\n });\n\n readable.on('error', (err) => {\n reject(err);\n });\n });\n readable.pipe(writable);\n return prom;\n};\n\nexport const outputJsonSync = (filepath: string, data: any) => {\n // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n outputFileSync(filepath, dataString);\n};\n\n// Read a JSON file.\nexport const readJsonSync = (filepath: string) => {\n const data = fs.readFileSync(filepath, { encoding: 'utf-8' });\n return JSON.parse(data);\n};\n\n// Read a file.\nexport const readFile = (filepath: string) => {\n return fsp.readFile(filepath, { encoding: 'utf-8' });\n};\n\nexport const readFileSync = (filepath: string) => {\n return fs.readFileSync(filepath, { encoding: 'utf-8' });\n};\n\nexport const existsSync = (filepath: string) => {\n try {\n return fs.existsSync(filepath);\n } catch (error: any) {\n // If the file does not exist, return false.\n if (error.code === 'ENOENT') {\n return false;\n }\n // If some other error occurs, rethrow it.\n throw error;\n }\n};\n\n// Some other more specific helpers.\n\n// From a path, returns a File to use with native FormData and fetch.\nexport const getFile = async (filepath: string, options: LocalAppendOptions) => {\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n const blob = await fs.openAsBlob(filepath, { type: options.contentType });\n return new File([blob], options.filename);\n } else {\n // Support NodeJS 18-\n const stream = Readable.toWeb(fs.createReadStream(filepath));\n const blob = await new Response(stream).blob();\n const file = new File([blob], options.filename, { type: options.contentType });\n return file;\n }\n};\n\n// Verify that every files are available.\nexport const checkFile = async (filePath: string): Promise<FileValidity> => {\n const validity: FileValidity = {\n empty: false,\n exists: true,\n };\n\n try {\n const { size } = await fsp.stat(filePath);\n if (size === 0) {\n validity.empty = true;\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n validity.exists = false;\n } else {\n // Other kind of error\n throw error;\n }\n }\n\n return validity;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\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 { AppsOptions } from '@dd/apps-plugin/types';\nimport type * as apps from '@dd/apps-plugin';\nimport type { ErrorTrackingOptions } from '@dd/error-tracking-plugin/types';\nimport type * as errorTracking from '@dd/error-tracking-plugin';\nimport type { LiveDebuggerOptions } from '@dd/live-debugger-plugin/types';\nimport type * as liveDebugger from '@dd/live-debugger-plugin';\nimport type { MetricsOptions } from '@dd/metrics-plugin/types';\nimport type * as metrics from '@dd/metrics-plugin';\nimport type { OutputOptions } from '@dd/output-plugin/types';\nimport type * as output from '@dd/output-plugin';\nimport type { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\n// #imports-injection-marker\n/* eslint-enable arca/import-ordering */\nimport type { BodyInit } from 'undici-types';\nimport type { UnpluginOptions } from 'unplugin';\n\nimport type { ALL_ENVS, SITES, SUPPORTED_BUNDLERS } from './constants';\n\nexport type Assign<A, B> = Omit<A, keyof B> & B;\nexport type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };\nexport type IterableElement<IterableType extends Iterable<unknown>> =\n IterableType extends Iterable<infer ElementType> ? ElementType : never;\n\nexport interface RepositoryData {\n commit: {\n hash: string;\n message: string;\n author: {\n name: string;\n email: string;\n date: string;\n };\n committer: {\n name: string;\n email: string;\n date: string;\n };\n };\n hash: string;\n branch: string;\n remote: string;\n trackedFilesMatcher: TrackedFilesMatcher;\n}\n\nexport type FileReport = { filepath: string; name: string; size: number; type: string };\nexport type Input = FileReport & { dependencies: Set<Input>; dependents: Set<Input> };\nexport type Output = FileReport & { inputs: (Input | Output)[] };\nexport type Entry = Output & { outputs: Output[] };\n\nexport type SerializedEntry = Assign<Entry, { inputs: string[]; outputs: string[] }>;\nexport type SerializedInput = Assign<Input, { dependencies: string[]; dependents: string[] }>;\nexport type SerializedOutput = Assign<Output, { inputs: string[] }>;\n\nexport interface Metric {\n metric: string;\n type: 'count' | 'size' | 'duration';\n points: [number, number][];\n tags: string[];\n}\n\nexport interface MetricToSend extends Metric {\n toSend: boolean;\n}\n\nexport type Log = {\n bundler?: BundlerName;\n pluginName: string;\n type: LogLevel;\n message: string;\n time: number;\n};\nexport type LogTags = string[];\nexport type Timer = {\n label: string;\n pluginName: string;\n spans: { start: number; end?: number; tags: LogTags }[];\n tags: LogTags;\n total: number;\n logLevel: LogLevel;\n};\n\nexport type BuildMetadata = {\n name?: string;\n version?: string;\n};\n\nexport type BuildReport = {\n bundler: GlobalData['bundler'];\n errors: GlobalStores['errors'];\n warnings: GlobalStores['warnings'];\n logs: GlobalStores['logs'];\n timings: GlobalStores['timings'];\n metadata: GlobalData['metadata'];\n entries?: Entry[];\n inputs?: Input[];\n outputs?: Output[];\n start?: number;\n end?: number;\n duration?: number;\n writeDuration?: number;\n};\n\n// A JSON safe version of the report.\nexport type SerializedBuildReport = Assign<\n BuildReport,\n {\n entries: SerializedEntry[];\n inputs: SerializedInput[];\n outputs: SerializedOutput[];\n }\n>;\n\nexport type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];\nexport type BundlerReport = GlobalData['bundler'] & {\n outDir: string;\n rawConfig?: any;\n};\n\nexport type ChunkInfo = {\n sourceOrHash: string;\n fileName: string;\n isEntry: boolean;\n};\n\n// Static string, lazy async loader (e.g. file fetch), or per-chunk code generator.\nexport type InjectedValue = string | (() => Promise<string>) | ((chunk?: ChunkInfo) => string);\n\nexport enum InjectPosition {\n BEFORE,\n MIDDLE,\n AFTER,\n}\n\nexport type ToInjectItem = {\n type: 'file' | 'code';\n value: InjectedValue;\n fallback?: ToInjectItem;\n} & (\n | { position?: InjectPosition.BEFORE | InjectPosition.AFTER; injectIntoAllChunks?: boolean }\n | { position: InjectPosition.MIDDLE }\n);\n\nexport type TimeLogger = {\n timer: Timer;\n resume: (startTime?: number) => void;\n end: (endTime?: number) => void;\n pause: (pauseTime?: number, warn?: boolean) => void;\n tag: (tags: LogTags, opts?: { span?: boolean }) => void;\n};\n\n// The rest parameter is a LogLevel or a boolean to auto start the timer.\nexport type TimeLog = (\n label: string,\n opts?: { level?: LogLevel; start?: boolean | number; log?: boolean; tags?: LogTags },\n) => TimeLogger;\nexport type GetLogger = (name: string) => Logger;\nexport type LogOptions = { forward?: boolean; context?: LogData };\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 addMetric: (metric: Metric) => void;\n asyncHook: TriggerHook<Promise<void[]>>;\n auth: AuthOptionsWithDefaults;\n build: BuildReport;\n bundler: BundlerReport;\n buildRoot: string;\n env: GlobalData['env'];\n getLogger: GetLogger;\n git?: RepositoryData;\n hook: TriggerHook<void>;\n inject: (item: ToInjectItem) => void;\n pluginNames: string[];\n plugins: (PluginOptions | CustomPluginOptions)[];\n queue: (promise: Promise<any>) => void;\n sendLog: (args: DdLogOptions) => Promise<void>;\n start: number;\n version: GlobalData['version'];\n};\n\nexport type FactoryMeta = {\n bundler: any;\n version: string;\n};\n\nexport type HookFn<T extends Array<any>> = (...args: T) => void;\nexport type AsyncHookFn<T extends Array<any>> = (...args: T) => Promise<void> | void;\nexport type CustomHooks = {\n asyncTrueEnd?: () => Promise<void> | void;\n buildRoot?: HookFn<[string]>;\n flush?: () => Promise<void> | void;\n init?: HookFn<[GlobalContext]>;\n buildReport?: AsyncHookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n metrics?: AsyncHookFn<[Set<Metric>]>;\n syncTrueEnd?: () => void;\n timings?: AsyncHookFn<[TimingsReport]>;\n};\n\nexport type PluginOptions = Assign<\n UnpluginOptions & CustomHooks,\n {\n name: PluginName;\n }\n>;\n\nexport type CustomPluginOptions = Assign<\n PluginOptions,\n {\n name: string;\n }\n>;\n\nexport type GetPluginsArg = {\n bundler: any;\n context: GlobalContext;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n};\nexport type GetPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetCustomPlugins = (arg: GetPluginsArg) => CustomPluginOptions[];\nexport type GetInternalPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetWrappedPlugins = (arg: GetPluginsArg) => (PluginOptions | CustomPluginOptions)[];\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\nexport type Site = (typeof SITES)[number];\nexport type AuthOptions = {\n apiKey?: string;\n appKey?: string;\n site?: string;\n};\n\nexport type AuthOptionsWithDefaults = Omit<AuthOptions, 'site'> & {\n site: Site;\n // A single-label custom subdomain on top of `site`, e.g. \"myorg\" for\n // \"myorg.us5.datadoghq.com\". Only used to direct the user to their org's\n // custom URL in the OAuth authorization step; API calls stay on `site`.\n siteSubdomain?: string;\n};\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n enableGit?: boolean;\n logLevel?: LogLevel;\n}\n\nexport interface Options extends BaseOptions {\n // Each product should have a unique entry.\n // #types-injection-marker\n [apps.CONFIG_KEY]?: AppsOptions;\n [errorTracking.CONFIG_KEY]?: ErrorTrackingOptions;\n [liveDebugger.CONFIG_KEY]?: LiveDebuggerOptions;\n [metrics.CONFIG_KEY]?: MetricsOptions;\n [output.CONFIG_KEY]?: OutputOptions;\n [rum.CONFIG_KEY]?: RumOptions;\n // #types-injection-marker\n customPlugins?: GetCustomPlugins;\n}\n\nexport type OptionsWithDefaults = Assign<\n Assign<Options, Required<BaseOptions>>,\n { auth: AuthOptionsWithDefaults }\n>;\n\nexport type PluginName = `datadog-${Lowercase<string>}-plugin`;\n\nexport type ApiKeyRequestAuthOptions = {\n apiKey?: string;\n appKey?: string;\n};\n\nexport type OAuthRequestAuthOptions = {\n accessToken: string;\n};\n\n// Request-local auth. OAuth callers must resolve tokens before calling doRequest.\nexport type RequestAuthOptions = ApiKeyRequestAuthOptions | OAuthRequestAuthOptions;\n\ntype Data = { data?: BodyInit; headers?: Record<string, string> };\nexport type RequestOpts = {\n url: string;\n auth?: RequestAuthOptions;\n method?: string;\n getData?: () => Promise<Data> | Data;\n type?: 'json' | 'text';\n onRetry?: (error: Error, attempt: number) => void;\n retries?: number;\n minTimeout?: number;\n maxTimeout?: number;\n};\n\nexport type ResolvedEntry = { name?: string; resolved: string; original: string };\n\nexport interface LocalAppendOptions {\n contentType: string;\n filename: string;\n}\n\nexport type FileValidity = {\n empty: boolean;\n exists: boolean;\n};\n\nexport type GlobalData = {\n bundler: {\n name: BundlerName;\n version: string;\n };\n env: Env;\n metadata: BuildMetadata;\n packageName: string;\n version: string;\n};\n\nexport type GlobalStores = {\n errors: string[];\n logs: Log[];\n metrics: Set<Metric>;\n queue: Promise<any>[];\n timings: Timer[];\n warnings: string[];\n};\n\n/* Legacy Telemetry types */\nexport type TAP_TYPES = 'default' | 'async' | 'promise';\n\nexport interface ValueContext {\n type: string;\n name: string;\n value?: string;\n}\n\nexport interface Value {\n start: number;\n end: number;\n duration: number;\n context?: ValueContext[];\n type?: TAP_TYPES; // Only for webpack.\n}\n\nexport interface Timing {\n name: string;\n duration: number;\n increment: number;\n events: {\n [key: string]: {\n name: string;\n values: Value[];\n };\n };\n}\nexport type TimingsMap = Map<string, Timing>;\n\nexport interface TimingsReport {\n tapables?: TimingsMap;\n loaders?: TimingsMap;\n modules?: TimingsMap;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport chalk from 'chalk';\nimport { spawn } from 'child_process';\nimport { createHash, randomBytes } from 'crypto';\nimport http from 'http';\n\nimport type { AuthOptionsWithDefaults, Logger, RequestOpts } from '../types';\n\nimport { doRequest } from './request';\n\nconst KEYRING_PACKAGE_NAME = '@napi-rs/keyring';\n\ntype OAuthAuthorizationServer = import('oauth4webapi').AuthorizationServer;\ntype OAuthClient = import('oauth4webapi').Client;\ntype OAuthModule = typeof import('oauth4webapi');\ntype OAuthTokenEndpointResponse = import('oauth4webapi').TokenEndpointResponse;\ntype KeyringModule = typeof import('@napi-rs/keyring');\n\n// oauth4webapi is ESM-only; dynamic import lets CommonJS consumers import these\n// helpers without requiring oauth4webapi at module load time.\nconst loadOauth = () => import('oauth4webapi') as Promise<OAuthModule>;\n\n// Load through a variable specifier so bundlers leave the native keyring binary\n// as a runtime require instead of inlining it. Node caches modules by specifier,\n// so repeated calls reuse the same instance.\nconst loadKeyring = () => import(KEYRING_PACKAGE_NAME) as Promise<KeyringModule>;\n\nexport type OAuthConfig = {\n authorizationUrl: string;\n cacheTokens: boolean;\n clientId: string;\n openBrowser: boolean;\n redirectUri: string;\n timeoutMs: number;\n tokenUrl: string;\n};\n\nexport const DEFAULT_OAUTH_CLIENT_ID = 'e17b9ffa-3daf-4124-ba1b-4ac8c547d506';\nexport const DATAD0G_OAUTH_CLIENT_ID = 'f4bacdd2-0c8c-49f5-bf3e-a62ba3ec02e6';\nexport const DEFAULT_OAUTH_REDIRECT_URI = 'http://localhost:8060';\nexport const DEFAULT_OAUTH_TIMEOUT_MS = 5 * 60 * 1000;\nexport const OAUTH_TOKEN_EXPIRY_SKEW_MS = 5 * 60 * 1000;\nexport const OAUTH_KEYCHAIN_SERVICE = 'datadog-build-plugins:oauth';\n\ntype OAuthCallback = {\n callbackParameters: URLSearchParams;\n};\n\nexport type OAuthToken = {\n accessToken: string;\n expiresAt?: number;\n expiresIn?: number;\n refreshToken?: string;\n scope?: string;\n site: string;\n tokenType?: string;\n};\n\nexport type CachedOAuthToken = Omit<OAuthToken, 'expiresIn'> & {\n clientId: string;\n};\n\nexport type ResolvedOAuthToken = {\n persistAfterSuccessfulRequest: boolean;\n token: OAuthToken;\n};\n\ntype StoredOAuthCredential = {\n token: CachedOAuthToken;\n version: 1;\n};\n\nconst cyan = chalk.cyan.bold;\n\nconst base64Url = (buffer: Buffer) => buffer.toString('base64url');\n\nexport const generateCodeVerifier = () => base64Url(randomBytes(32));\n\nexport const generateCodeChallenge = async (codeVerifier: string) => {\n const oauth = await loadOauth();\n return oauth.calculatePKCECodeChallenge(codeVerifier);\n};\n\nexport const getOAuthClientId = (site: string) => {\n switch (site) {\n case 'datad0g.com':\n return DATAD0G_OAUTH_CLIENT_ID;\n default:\n return DEFAULT_OAUTH_CLIENT_ID;\n }\n};\n\nexport const getDatadogOAuthConfig = (site: string, subdomain?: string): OAuthConfig => {\n const clientId = getOAuthClientId(site);\n // Custom subdomains are a web-UI alias for the org's \"app.\" host; API/token\n // calls always stay on the base site.\n const authorizationHost = subdomain ? `${subdomain}.${site}` : `app.${site}`;\n const authorizationUrl = `https://${authorizationHost}/oauth2/v1/authorize`;\n const tokenUrl = `https://api.${site}/oauth2/v1/token`;\n\n return {\n authorizationUrl,\n cacheTokens: true,\n clientId,\n openBrowser: true,\n redirectUri: DEFAULT_OAUTH_REDIRECT_URI,\n timeoutMs: DEFAULT_OAUTH_TIMEOUT_MS,\n tokenUrl,\n };\n};\n\nconst getOAuthClient = (clientId: string): OAuthClient => ({ client_id: clientId });\n\nconst getAuthorizationServer = (\n options: Pick<OAuthConfig, 'authorizationUrl' | 'tokenUrl'>,\n): OAuthAuthorizationServer => {\n return {\n issuer: new URL(options.authorizationUrl).origin,\n authorization_endpoint: options.authorizationUrl,\n token_endpoint: options.tokenUrl,\n };\n};\n\nconst getOAuthCredentialFingerprint = (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n) =>\n createHash('sha256')\n .update([options.clientId, site, options.authorizationUrl, options.tokenUrl].join('|'))\n .digest('hex')\n .slice(0, 16);\n\nconst getOAuthCredentialAccount = (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n) => `${site}:${options.clientId}:${getOAuthCredentialFingerprint(site, options)}`;\n\nexport const buildAuthorizationUrl = (opts: {\n authorizationUrl: string;\n clientId: string;\n codeChallenge: string;\n redirectUri: string;\n state: string;\n}) => {\n const url = new URL(opts.authorizationUrl);\n url.searchParams.set('redirect_uri', opts.redirectUri);\n url.searchParams.set('client_id', opts.clientId);\n url.searchParams.set('response_type', 'code');\n url.searchParams.set('code_challenge', opts.codeChallenge);\n url.searchParams.set('code_challenge_method', 'S256');\n url.searchParams.set('state', opts.state);\n return url;\n};\n\nconst tryOpenBrowser = (url: string, log: Logger) => {\n const opener =\n process.platform === 'darwin'\n ? { command: 'open', args: [url] }\n : process.platform === 'win32'\n ? { command: 'cmd', args: ['/c', 'start', '', url] }\n : { command: 'xdg-open', args: [url] };\n\n try {\n const child = spawn(opener.command, opener.args, {\n detached: true,\n stdio: 'ignore',\n });\n child.once('error', (error) => {\n log.warn(`Could not open browser automatically: ${getErrorMessage(error)}`);\n });\n child.unref();\n } catch (error) {\n log.warn(`Could not open browser automatically: ${getErrorMessage(error)}`);\n }\n};\n\nconst respond = (res: http.ServerResponse, statusCode: number, body: string) => {\n res.writeHead(statusCode, { 'Content-Type': 'text/html; charset=UTF-8' });\n res.end(body);\n};\n\nexport const waitForOAuthCallback = async (opts: {\n authorizationServer: OAuthAuthorizationServer;\n client: OAuthClient;\n oauth: OAuthModule;\n redirectUri: string;\n state: string;\n timeoutMs: number;\n}): Promise<OAuthCallback> => {\n const redirectUrl = new URL(opts.redirectUri);\n const port = Number(redirectUrl.port || 80);\n\n if (redirectUrl.protocol !== 'http:') {\n throw new Error('OAuth redirect URI must use http for the local OAuth callback.');\n }\n\n if (!Number.isInteger(port) || port <= 0) {\n throw new Error('OAuth redirect URI must include a valid port.');\n }\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n\n const server = http.createServer();\n\n try {\n return await new Promise<OAuthCallback>((resolve, reject) => {\n const finish = (fn: () => void) => {\n if (settled) {\n return;\n }\n settled = true;\n fn();\n };\n\n server.on('request', (req, res) => {\n const reqUrl = new URL(req.url || '/', redirectUrl.origin);\n if (reqUrl.pathname !== redirectUrl.pathname) {\n respond(res, 404, 'Not found.');\n return;\n }\n\n let callbackParameters: URLSearchParams;\n try {\n callbackParameters = opts.oauth.validateAuthResponse(\n opts.authorizationServer,\n opts.client,\n reqUrl,\n opts.state,\n );\n } catch (error) {\n respond(res, 400, 'OAuth authorization failed. You may now close this tab.');\n finish(() => reject(error instanceof Error ? error : new Error(String(error))));\n return;\n }\n\n const code = callbackParameters.get('code');\n if (!code) {\n respond(\n res,\n 400,\n 'Missing OAuth authorization code. You may now close this tab.',\n );\n finish(() => reject(new Error('Missing OAuth authorization code.')));\n return;\n }\n\n respond(res, 200, 'OAuth authorization complete. You may now close this tab.');\n finish(() => resolve({ callbackParameters }));\n });\n\n server.once('error', (error) => finish(() => reject(error)));\n\n timeout = setTimeout(() => {\n finish(() =>\n reject(\n new Error(\n `Timed out waiting for OAuth callback after ${opts.timeoutMs}ms.`,\n ),\n ),\n );\n }, opts.timeoutMs);\n\n try {\n const hostname =\n redirectUrl.hostname === 'localhost' ? undefined : redirectUrl.hostname;\n server.listen(port, hostname);\n } catch (error) {\n finish(() => reject(error instanceof Error ? error : new Error(String(error))));\n }\n });\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n if (server.listening) {\n server.close();\n server.closeAllConnections?.();\n server.closeIdleConnections?.();\n }\n }\n};\n\nexport const exchangeAuthorizationCode = async (opts: {\n callbackParameters: URLSearchParams;\n clientId: string;\n codeVerifier: string;\n redirectUri: string;\n site: string;\n tokenUrl: string;\n authorizationUrl: string;\n}): Promise<OAuthToken> => {\n const oauth = await loadOauth();\n const authorizationServer = getAuthorizationServer(opts);\n const client = getOAuthClient(opts.clientId);\n const response = await oauth.authorizationCodeGrantRequest(\n authorizationServer,\n client,\n oauth.None(),\n opts.callbackParameters,\n opts.redirectUri,\n opts.codeVerifier,\n );\n const tokenResponse = await oauth.processAuthorizationCodeResponse(\n authorizationServer,\n client,\n response,\n );\n\n return tokenResponseToOAuthToken(tokenResponse, opts.site);\n};\n\nexport const validateOAuthCallback = async (\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n callbackUrl: URL,\n state: string,\n) => {\n const oauth = await loadOauth();\n return oauth.validateAuthResponse(\n getAuthorizationServer(options),\n getOAuthClient(options.clientId),\n callbackUrl,\n state,\n );\n};\n\nexport const refreshOAuthToken = async (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n refreshToken: string,\n): Promise<OAuthToken> => {\n const oauth = await loadOauth();\n const authorizationServer = getAuthorizationServer(options);\n const client = getOAuthClient(options.clientId);\n const response = await oauth.refreshTokenGrantRequest(\n authorizationServer,\n client,\n oauth.None(),\n refreshToken,\n );\n const tokenResponse = await oauth.processRefreshTokenResponse(\n authorizationServer,\n client,\n response,\n );\n\n return tokenResponseToOAuthToken(\n {\n ...tokenResponse,\n refresh_token: tokenResponse.refresh_token || refreshToken,\n },\n site,\n );\n};\n\nconst tokenResponseToOAuthToken = (\n tokenResponse: OAuthTokenEndpointResponse,\n site: string,\n receivedAt = Date.now(),\n): OAuthToken => {\n return {\n accessToken: tokenResponse.access_token,\n expiresAt:\n typeof tokenResponse.expires_in === 'number'\n ? receivedAt + tokenResponse.expires_in * 1000\n : undefined,\n expiresIn: tokenResponse.expires_in,\n refreshToken: tokenResponse.refresh_token,\n scope: tokenResponse.scope,\n site,\n tokenType: tokenResponse.token_type,\n };\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst getErrorCode = (error: unknown) =>\n isObject(error) && typeof error.code === 'string' ? error.code : undefined;\n\nconst getErrorMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\nconst isNoEntryError = (error: unknown) => {\n const message = getErrorMessage(error).toLowerCase();\n return (\n getErrorCode(error) === 'NoEntry' ||\n message.includes('noentry') ||\n message.includes('no matching entry') ||\n message.includes('not found')\n );\n};\n\nconst assertStoredOAuthCredential = (value: unknown): StoredOAuthCredential | undefined => {\n if (\n isObject(value) &&\n value.version === 1 &&\n isObject(value.token) &&\n typeof value.token.accessToken === 'string' &&\n typeof value.token.clientId === 'string' &&\n typeof value.token.site === 'string'\n ) {\n return value as StoredOAuthCredential;\n }\n\n return undefined;\n};\n\nconst createOAuthCredentialEntry = async (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n) => {\n const { AsyncEntry } = await loadKeyring();\n return new AsyncEntry(OAUTH_KEYCHAIN_SERVICE, getOAuthCredentialAccount(site, options));\n};\n\nconst secureStorageError = (operation: string, error: unknown) =>\n new Error(\n `Could not ${operation} Datadog OAuth token in the OS credential store. ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n\nexport const readOAuthTokenFromKeychain = async (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n): Promise<CachedOAuthToken | undefined> => {\n try {\n const entry = await createOAuthCredentialEntry(site, options);\n const raw = await entry.getPassword();\n if (!raw) {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(raw);\n return assertStoredOAuthCredential(parsed)?.token;\n } catch (error) {\n if (isNoEntryError(error)) {\n return undefined;\n }\n\n throw secureStorageError('read', error);\n }\n};\n\nexport const writeOAuthTokenToKeychain = async (\n site: string,\n token: CachedOAuthToken,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n) => {\n try {\n const entry = await createOAuthCredentialEntry(site, options);\n const credential: StoredOAuthCredential = { version: 1, token };\n await entry.setPassword(JSON.stringify(credential));\n } catch (error) {\n throw secureStorageError('save', error);\n }\n};\n\nexport const deleteOAuthTokenFromKeychain = async (\n site: string,\n options: Pick<OAuthConfig, 'authorizationUrl' | 'clientId' | 'tokenUrl'>,\n) => {\n try {\n const entry = await createOAuthCredentialEntry(site, options);\n await entry.deletePassword();\n } catch (error) {\n if (!isNoEntryError(error)) {\n throw secureStorageError('delete', error);\n }\n }\n};\n\nconst isCachedTokenValid = (token: CachedOAuthToken) =>\n token.expiresAt === undefined || token.expiresAt > Date.now() + OAUTH_TOKEN_EXPIRY_SKEW_MS;\n\nconst toCachedToken = (token: OAuthToken, clientId: string): CachedOAuthToken => ({\n accessToken: token.accessToken,\n clientId,\n expiresAt: token.expiresAt,\n refreshToken: token.refreshToken,\n scope: token.scope,\n site: token.site,\n tokenType: token.tokenType,\n});\n\nconst fromCachedToken = (token: CachedOAuthToken): OAuthToken => ({\n accessToken: token.accessToken,\n expiresAt: token.expiresAt,\n refreshToken: token.refreshToken,\n scope: token.scope,\n site: token.site,\n tokenType: token.tokenType,\n});\n\nconst saveOAuthToken = async (\n token: OAuthToken,\n options: OAuthConfig,\n log: Logger,\n cacheSite = token.site,\n) => {\n if (!options.cacheTokens) {\n return;\n }\n\n try {\n await writeOAuthTokenToKeychain(cacheSite, toCachedToken(token, options.clientId), options);\n log.debug('Saved Datadog OAuth token to the OS credential store.');\n } catch (error) {\n log.warn(\n `Could not save Datadog OAuth token to the OS credential store; continuing without a persistent cache. ${getErrorMessage(error)}`,\n );\n }\n};\n\nconst deleteOAuthToken = async (site: string, options: OAuthConfig, log: Logger): Promise<void> => {\n if (!options.cacheTokens) {\n return;\n }\n\n try {\n await deleteOAuthTokenFromKeychain(site, options);\n } catch (error) {\n log.warn(`Could not delete cached Datadog OAuth token. ${getErrorMessage(error)}`);\n }\n};\n\nconst getCachedOAuthToken = async (\n site: string,\n options: OAuthConfig,\n log: Logger,\n): Promise<OAuthToken | undefined> => {\n if (!options.cacheTokens) {\n return undefined;\n }\n\n let cachedToken: CachedOAuthToken | undefined;\n try {\n cachedToken = await readOAuthTokenFromKeychain(site, options);\n } catch (error) {\n log.warn(\n `Could not read cached Datadog OAuth token; starting browser authorization. ${getErrorMessage(error)}`,\n );\n }\n if (!cachedToken) {\n return undefined;\n }\n\n if (isCachedTokenValid(cachedToken)) {\n log.debug('Using cached Datadog OAuth access token.');\n return fromCachedToken(cachedToken);\n }\n\n if (!cachedToken.refreshToken) {\n return undefined;\n }\n\n try {\n log.debug('Refreshing cached Datadog OAuth access token.');\n const refreshedToken = await refreshOAuthToken(site, options, cachedToken.refreshToken);\n await saveOAuthToken(refreshedToken, options, log);\n return refreshedToken;\n } catch (error) {\n log.warn(\n `Cached Datadog OAuth token could not be refreshed; starting browser authorization. ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n await deleteOAuthToken(site, options, log);\n return undefined;\n }\n};\n\nexport const authorizeWithPKCE = async (\n site: string,\n options: OAuthConfig,\n log: Logger,\n): Promise<OAuthToken> => {\n const oauth = await loadOauth();\n const authorizationServer = getAuthorizationServer(options);\n const client = getOAuthClient(options.clientId);\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n const state = base64Url(randomBytes(32));\n const authorizationUrl = buildAuthorizationUrl({\n authorizationUrl: options.authorizationUrl,\n clientId: options.clientId,\n codeChallenge,\n redirectUri: options.redirectUri,\n state,\n });\n\n const callbackPromise = waitForOAuthCallback({\n authorizationServer,\n client,\n oauth,\n redirectUri: options.redirectUri,\n state,\n timeoutMs: options.timeoutMs,\n });\n\n log.info(`Authorize Datadog Apps upload:\\n ${cyan(authorizationUrl.toString())}`);\n\n if (options.openBrowser) {\n tryOpenBrowser(authorizationUrl.toString(), log);\n }\n\n const callback = await callbackPromise;\n return exchangeAuthorizationCode({\n callbackParameters: callback.callbackParameters,\n clientId: options.clientId,\n codeVerifier,\n redirectUri: options.redirectUri,\n site,\n tokenUrl: options.tokenUrl,\n authorizationUrl: options.authorizationUrl,\n });\n};\n\nexport const getOAuthToken = async (\n site: string,\n options: OAuthConfig,\n log: Logger,\n): Promise<OAuthToken> => {\n const cachedToken = await getCachedOAuthToken(site, options, log);\n if (cachedToken) {\n return cachedToken;\n }\n\n const token = await authorizeWithPKCE(site, options, log);\n await saveOAuthToken(token, options, log, site);\n return token;\n};\n\n// Memoize per site+subdomain+client for the lifetime of the process so concurrent\n// requests (and the sequential upload + release calls) share a single browser authorization.\nconst tokenCache = new Map<string, Promise<ResolvedOAuthToken>>();\n\nconst resolveOAuthTokenFromStorage = async (\n site: string,\n options: OAuthConfig,\n log: Logger,\n): Promise<ResolvedOAuthToken> => {\n const cachedToken = await getCachedOAuthToken(site, options, log);\n if (cachedToken) {\n return { persistAfterSuccessfulRequest: false, token: cachedToken };\n }\n\n const token = await authorizeWithPKCE(site, options, log);\n return { persistAfterSuccessfulRequest: true, token };\n};\n\nexport const resolveOAuthToken = async (\n site: string,\n log: Logger,\n subdomain?: string,\n): Promise<ResolvedOAuthToken> => {\n const options = getDatadogOAuthConfig(site, subdomain);\n const key = `${site}:${subdomain ?? ''}:${options.clientId}`;\n let pending = tokenCache.get(key);\n if (!pending) {\n pending = resolveOAuthTokenFromStorage(site, options, log).catch((error) => {\n tokenCache.delete(key);\n throw error;\n });\n tokenCache.set(key, pending);\n }\n return pending;\n};\n\nexport type OAuthRequestOpts = Omit<RequestOpts, 'auth'> & {\n auth: AuthOptionsWithDefaults;\n log: Logger;\n};\n\nexport const doOAuthRequest = async <T>({ auth, log, ...opts }: OAuthRequestOpts): Promise<T> => {\n const { site, siteSubdomain } = auth;\n const { persistAfterSuccessfulRequest, token } = await resolveOAuthToken(\n site,\n log,\n siteSubdomain,\n );\n\n if (!token.accessToken) {\n throw new Error('OAuth authentication did not return an access token.');\n }\n\n const result = await doRequest<T>({\n ...opts,\n auth: {\n accessToken: token.accessToken,\n },\n });\n\n if (persistAfterSuccessfulRequest) {\n await saveOAuthToken(token, getDatadogOAuthConfig(site, siteSubdomain), log, site);\n }\n\n return result;\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 { doOAuthRequest } from '@dd/core/helpers/oauth-request';\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { AuthOptionsWithDefaults, Logger, RequestOpts } from '@dd/core/types';\n\nimport type { AuthMethod } from './types';\n\nexport const AUTH_GUIDANCE =\n 'Set apps.authOverrides.method: \"oauth\" or DD_APPS_AUTH_METHOD=oauth to use OAuth, ' +\n 'or set DD_API_KEY and DD_APP_KEY to use API/App key auth.';\n\nexport type DoAuthenticatedRequest = <T>(opts: Omit<RequestOpts, 'auth'>) => Promise<T>;\n\nexport class MissingAuthenticationError extends Error {\n public statusCode = 400;\n\n constructor() {\n super(`Missing authentication. ${AUTH_GUIDANCE}`);\n this.name = 'MissingAuthenticationError';\n }\n}\n\n// Build the authenticated request function from the resolved method + base credentials.\nexport const getAuthenticatedRequest = (\n method: AuthMethod,\n auth: AuthOptionsWithDefaults,\n log: Logger,\n): DoAuthenticatedRequest => {\n if (method === 'oauth') {\n return (opts) => doOAuthRequest({ ...opts, auth, log });\n }\n\n if (auth.apiKey && auth.appKey) {\n return (opts) =>\n doRequest({\n ...opts,\n auth: {\n apiKey: auth.apiKey,\n appKey: auth.appKey,\n },\n });\n }\n\n throw new MissingAuthenticationError();\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 { BaseNode, Program, SimpleLiteral } from 'estree';\n\nexport type StringLiteral = SimpleLiteral & { value: string };\n\ninterface TypeScriptImportExportMetadata {\n importKind?: 'type' | 'value';\n exportKind?: 'type' | 'value';\n}\n\ntype TypeOnlyAwareNode = BaseNode & TypeScriptImportExportMetadata;\n\nexport function ensureProgram(node: BaseNode, filePath: string): Program {\n if (!isProgramNode(node)) {\n throw new Error(\n `Expected a Program node from this.parse() for ${filePath}, got ${node.type}`,\n );\n }\n return node;\n}\n\nexport function isProgramNode(node: BaseNode): node is Program {\n return node.type === 'Program';\n}\n\nexport function isStringLiteral(node: unknown): node is StringLiteral {\n return (\n typeof node === 'object' &&\n node !== null &&\n (node as { type?: string }).type === 'Literal' &&\n typeof (node as { value?: unknown }).value === 'string'\n );\n}\n\nexport function isTypeOnly(node: TypeOnlyAwareNode): boolean {\n return node.importKind === 'type' || node.exportKind === 'type';\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 { BaseNode, Declaration, Expression, Program } from 'estree';\n\nimport { ensureProgram } from './type-guards';\nimport type { BackendExport } from './types';\n\n/**\n * Extract exported value (non-type) symbols from an ESTree AST.\n * Expects plain JavaScript — TypeScript types must already be stripped\n * (e.g. by Vite's built-in esbuild transform that runs before our hook).\n *\n * Throws on invalid exports (e.g. default exports) and unexpected AST shapes.\n * Returns an empty array when the file has no named exports.\n *\n * @param ast - ESTree node from `this.parse()` in unplugin's transform hook\n * @param filePath - Path to the source file (used in error messages)\n */\nexport function extractExportedFunctions(ast: BaseNode, filePath: string): string[] {\n return enumerateBackendExports(ast, filePath).map((backendExport) => backendExport.name);\n}\n\nexport function enumerateBackendExports(ast: BaseNode, filePath: string): BackendExport[] {\n const program = ensureProgram(ast, filePath);\n\n // Build a map of top-level declarations so we can validate export specifiers.\n const declarations = buildDeclarationMap(program);\n\n const backendExports: BackendExport[] = [];\n for (const node of program.body) {\n // handles: export default ...\n if (node.type === 'ExportDefaultDeclaration') {\n throw new Error(\n `Default exports are not supported in .backend.ts files. Use a named export instead: ${filePath}`,\n );\n }\n // handles: export * from '...'\n if (node.type === 'ExportAllDeclaration') {\n throw new Error(\n `\"export *\" is not supported in .backend.ts files. Use explicit named exports instead: ${filePath}`,\n );\n }\n if (node.type !== 'ExportNamedDeclaration') {\n continue;\n }\n\n // handles: export function add() {} / export const add = ...\n if (node.declaration) {\n backendExports.push(\n ...namesFromDeclaration(node.declaration, filePath).map((name) => ({\n kind: 'local' as const,\n name,\n localName: name,\n })),\n );\n }\n\n const source = typeof node.source?.value === 'string' ? node.source.value : null;\n for (const spec of node.specifiers) {\n if (spec.exported.type !== 'Identifier') {\n continue;\n }\n // handles: export { add as default }\n if (spec.exported.name === 'default') {\n throw new Error(\n `Default exports are not supported in .backend.ts files. Use a named export instead: ${filePath}`,\n );\n }\n // Validate specifier binding is callable when we can resolve it.\n // e.g. `const VERSION = '1.0'; export { VERSION };` — rejected\n // e.g. `function add() {}; export { add };` — allowed\n const localName =\n spec.local.type === 'Identifier'\n ? spec.local.name\n : typeof spec.local.value === 'string'\n ? spec.local.value\n : null;\n if (!localName) {\n continue;\n }\n\n if (source) {\n backendExports.push({\n kind: 're-export',\n name: spec.exported.name,\n localName,\n source,\n });\n continue;\n }\n\n if (spec.local.type === 'Identifier') {\n validateSpecifierBinding(localName, declarations, filePath);\n }\n backendExports.push({\n kind: 'local',\n name: spec.exported.name,\n localName,\n });\n }\n }\n return backendExports;\n}\n\n/** Init types that are definitively non-callable at runtime. */\nconst NON_CALLABLE_INIT_TYPES = new Set([\n 'ArrayExpression',\n 'Literal',\n 'ObjectExpression',\n 'TemplateLiteral',\n]);\n\n/**\n * Return `true` when the initializer is known to be non-callable.\n * `ArrowFunctionExpression` / `FunctionExpression` are clearly callable.\n * Ambiguous forms (`Identifier`, `CallExpression`, …) are allowed — the\n * user may legitimately re-export an imported function or a factory result.\n */\nfunction isNonCallableInit(init: Expression | null | undefined): boolean {\n return init === null || init === undefined || NON_CALLABLE_INIT_TYPES.has(init.type);\n}\n\n/**\n * Extract identifier names from an exported declaration node.\n * Handles `export function foo()` and `export const foo = ...` forms.\n * Throws when a variable export has a non-callable initializer.\n */\nfunction namesFromDeclaration(decl: Declaration, filePath: string): string[] {\n // export function add(a, b) { return a + b; }\n if (decl.type === 'FunctionDeclaration' && decl.id) {\n return [decl.id.name];\n }\n // export class MyClass {} — classes are not callable as RPC endpoints\n if (decl.type === 'ClassDeclaration') {\n throw new Error(\n `Class exports are not supported in .backend.ts files. Only function exports are allowed: ${filePath}`,\n );\n }\n if (decl.type === 'VariableDeclaration') {\n return decl.declarations.flatMap((d) => {\n // export const { a, b } = obj;\n // export const [a, b] = arr;\n if (d.id.type !== 'Identifier') {\n throw new Error(\n `Destructured exports are not supported in backend files. Use individual named exports instead: ${filePath}`,\n );\n }\n // export const VERSION = '1.0'; — non-callable, throws\n // export const config = { ... }; — non-callable, throws\n if (isNonCallableInit(d.init)) {\n throw new Error(\n `Non-function export \"${d.id.name}\" in backend file ${filePath}. Only function exports are supported — use \"export function ${d.id.name}(…) { }\" instead.`,\n );\n }\n // export const add = (a, b) => a + b;\n // export const handler = importedFn; — ambiguous, allowed\n return [d.id.name];\n });\n }\n throw new Error(\n `Unsupported export declaration type \"${decl.type}\" in backend file ${filePath}. Only function and variable exports are allowed.`,\n );\n}\n\n/**\n * Describes a top-level declaration for specifier validation.\n * 'function' and 'import' are always allowed (callable or ambiguous).\n * 'class' is rejected. 'variable' is checked via its initializer.\n */\ntype DeclInfo =\n | { kind: 'function' | 'import' | 'class' }\n | { kind: 'variable'; init: Expression | null | undefined };\n\n/**\n * Build a map from identifier name → declaration info for all top-level\n * statements. Used to validate `export { name }` specifiers.\n */\nfunction buildDeclarationMap(ast: Program): Map<string, DeclInfo> {\n const map = new Map<string, DeclInfo>();\n for (const node of ast.body) {\n if (node.type === 'FunctionDeclaration' && node.id) {\n // handles: function add(a, b) { return a + b; }\n map.set(node.id.name, { kind: 'function' });\n } else if (node.type === 'ClassDeclaration' && node.id) {\n // handles: class MyService {}\n map.set(node.id.name, { kind: 'class' });\n } else if (node.type === 'VariableDeclaration') {\n // handles: const add = (a, b) => a + b; / const VERSION = '1.0';\n for (const d of node.declarations) {\n if (d.id.type === 'Identifier') {\n map.set(d.id.name, { kind: 'variable', init: d.init });\n }\n }\n } else if (node.type === 'ImportDeclaration') {\n // handles: import { handler } from './other';\n // For this case, we allow exporting handler and accept that it may not be a function.\n for (const spec of node.specifiers) {\n map.set(spec.local.name, { kind: 'import' });\n }\n }\n }\n return map;\n}\n\n/**\n * Validate that an export specifier's local binding is callable.\n * Throws for known non-callable bindings (classes, non-callable variables).\n * Allows unresolved bindings (e.g. from other export patterns) and imports.\n */\nfunction validateSpecifierBinding(\n localName: string,\n declarations: Map<string, DeclInfo>,\n filePath: string,\n): void {\n const info = declarations.get(localName);\n if (!info) {\n // Unresolved — could come from a pattern we don't track. Allow it.\n return;\n }\n if (info.kind === 'class') {\n throw new Error(\n `Class exports are not supported in .backend.ts files. Only function exports are allowed: ${filePath}`,\n );\n }\n if (info.kind === 'variable' && isNonCallableInit(info.init)) {\n throw new Error(\n `Non-function export \"${localName}\" in backend file ${filePath}. Only function exports are supported — use \"export function ${localName}(…) { }\" instead.`,\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 { createHash } from 'crypto';\nimport path from 'path';\n\nimport type { BackendFunction } from './types';\n\n/**\n * Encode a BackendFunction into an opaque query name string.\n * Uses the full SHA-256 hash of the path so that backend file structure\n * is never leaked into frontend assets.\n *\n * This is the single source of truth for query name encoding — used by\n * proxy codegen, the production build, and the dev server.\n */\nexport function encodeQueryName(ref: Pick<BackendFunction, 'relativePath' | 'name'>): string {\n // Normalize to forward slashes so the hash is consistent across platforms.\n const posixPath = ref.relativePath.split(path.sep).join('/');\n const pathHash = createHash('sha256').update(posixPath).digest('hex');\n return `${pathHash}.${ref.name}`;\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\ninterface ProxyExport {\n /** The JS export name (e.g. \"add\") */\n exportName: string;\n /** The pre-computed opaque query name (e.g. \"a1b2c3d4e5f6.add\") */\n queryName: string;\n}\n\n/**\n * Generate a proxy module for a `.backend.ts` file. Each exported function\n * is replaced with a wrapper that calls `executeBackendFunction` from the\n * runtime exposed on `globalThis.DD_APPS_RUNTIME` by the apps plugin's\n * injection (see packages/plugins/apps/src/built/apps-runtime.ts).\n *\n * The raw backend file path is never present in the generated code — only\n * the hashed query name appears, preventing backend file structure from\n * leaking into frontend bundles.\n *\n * @param exports - The export name + pre-computed query name for each export\n * @returns Generated proxy module source code\n */\nexport function generateProxyModule(exports: ProxyExport[]): string {\n const lines: string[] = [];\n\n for (const { exportName, queryName } of exports) {\n lines.push(`export async function ${exportName}(...args) {`);\n lines.push(\n ` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(queryName)}, args);`,\n );\n lines.push('}');\n lines.push('');\n }\n\n return lines.join('\\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\nfunction isPackageExportInstalled(packageExport: string, fromDir: string): boolean {\n try {\n require.resolve(packageExport, { paths: [fromDir] });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if @datadog/action-catalog is installed using Node's module resolution.\n * Resolves from the given directory so the check works even when the plugin\n * itself is loaded from a different location (e.g. linked).\n */\nexport function isActionCatalogInstalled(fromDir: string): boolean {\n return isPackageExportInstalled('@datadog/action-catalog/action-execution', fromDir);\n}\n\n/** Check if the @datadog/apps-backend \"JS Function with Actions\" runtime factory is installed. */\nexport function isDatadogAppsBackendInstalled(fromDir: string): boolean {\n return isPackageExportInstalled('@datadog/apps-backend/runtime/jsFunctionWithActions', fromDir);\n}\n\n/** The import line to pull action-catalog's setExecuteActionImplementation into bundles. */\nexport const ACTION_CATALOG_IMPORT =\n \"import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';\";\n\n/** The import line that exposes @datadog/apps-backend backend context initialization. */\nexport const DATADOG_APPS_BACKEND_IMPORT = `\\\nimport { buildRuntimeFromJsFunctionWithActions } from '@datadog/apps-backend/runtime/jsFunctionWithActions';\nimport { setBackend } from '@datadog/apps-backend/runtime';`;\n\n/** Script snippet that supplies the backend runtime context to @datadog/apps. */\nexport const SET_BACKEND_CONTEXT_SNIPPET = `\\\n if (typeof buildRuntimeFromJsFunctionWithActions === 'function' && typeof setBackend === 'function') {\n setBackend(buildRuntimeFromJsFunctionWithActions($));\n }`;\n\n/** Script snippet that registers the $.Actions-based executeAction implementation at runtime. */\nexport const SET_EXECUTE_ACTION_SNIPPET = `\\\n if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\\\.datadoghq\\\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }`;\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 ACTION_CATALOG_IMPORT,\n DATADOG_APPS_BACKEND_IMPORT,\n SET_BACKEND_CONTEXT_SNIPPET,\n SET_EXECUTE_ACTION_SNIPPET,\n isActionCatalogInstalled,\n isDatadogAppsBackendInstalled,\n} from './shared';\n\n/**\n * Generate the virtual entry source for a backend function.\n * The host bundler resolves imports, so no export-stripping is needed.\n */\nexport function generateVirtualEntryContent(\n functionName: string,\n entryPath: string,\n projectRoot: string,\n): string {\n const lines: string[] = [];\n const hasDatadogAppsBackendRuntime = isDatadogAppsBackendInstalled(projectRoot);\n\n lines.push(`import { ${functionName} } from ${JSON.stringify(entryPath)};`);\n\n if (hasDatadogAppsBackendRuntime) {\n lines.push(DATADOG_APPS_BACKEND_IMPORT);\n }\n\n if (isActionCatalogInstalled(projectRoot)) {\n lines.push(ACTION_CATALOG_IMPORT);\n }\n\n lines.push('');\n lines.push('/** @param {import(\"./context.types\").Context} $ */');\n lines.push('export async function main($) {');\n lines.push(' globalThis.$ = $;');\n lines.push('');\n if (hasDatadogAppsBackendRuntime) {\n lines.push(' // Supply the backend runtime context');\n lines.push(SET_BACKEND_CONTEXT_SNIPPET);\n lines.push('');\n }\n lines.push(` // Register the $.Actions-based implementation for executeAction`);\n lines.push(SET_EXECUTE_ACTION_SNIPPET);\n lines.push('');\n lines.push(' const args = $.backendFunctionArgs ?? [];');\n lines.push(` const result = await ${functionName}(...args);`);\n lines.push(' return result;');\n lines.push('}');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the virtual entry source for a backend function (dev server).\n * Identical to production: args are read from $.backendFunctionArgs at runtime.\n */\nexport function generateDevVirtualEntryContent(\n functionName: string,\n entryPath: string,\n projectRoot?: string,\n): string {\n return generateVirtualEntryContent(functionName, entryPath, projectRoot ?? process.cwd());\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 { BaseNode, Node as EstreeNode } from 'estree';\n\n/**\n * Object passed to every visitor.\n *\n * `state` is shared for the whole walk. This helper intentionally does not\n * thread child-specific state because current AST analysis only needs one\n * shared collection/lookup object.\n */\nexport interface WalkAstContext<State> {\n state: State;\n}\n\n/**\n * Function called when the walker reaches a matching node.\n *\n * `Node` is the broad tree type passed to `walkAst`, while `CurrentNode` is the\n * narrowed node type for a specialized visitor such as `CallExpression`.\n */\nexport type WalkAstVisitor<Node extends BaseNode, State, CurrentNode extends BaseNode = Node> = (\n node: CurrentNode,\n context: WalkAstContext<State>,\n) => void;\n\n/**\n * Visitor map for concrete ESTree node types.\n *\n * The runtime walker is generic and does not special-case ESTree types. This\n * mapped type only exists to make visitor callbacks typed when users write\n * keys like `CallExpression` or `VariableDeclarator`.\n */\ntype SpecializedWalkAstVisitors<Node extends BaseNode, State> = {\n [Type in EstreeNode['type']]?: WalkAstVisitor<Node, State, Extract<EstreeNode, { type: Type }>>;\n};\n\n/**\n * Visitors accepted by `walkAst`.\n *\n * `_` is a universal visitor that runs for every node. Keys matching concrete\n * ESTree node types run only for nodes with that `type`.\n */\nexport type WalkAstVisitors<Node extends BaseNode, State> = SpecializedWalkAstVisitors<\n Node,\n State\n> & {\n _?: WalkAstVisitor<Node, State>;\n};\n\n/**\n * Walks an ESTree-shaped AST without maintaining a hardcoded visitor-key table.\n *\n * Any object with a string `type` property is treated as a child node. Primitive\n * values, arrays entries without `type`, and metadata objects such as `loc` are\n * ignored.\n */\nexport function walkAst<Node extends BaseNode, State>(\n node: Node,\n state: State,\n visitors: WalkAstVisitors<Node, State>,\n): void {\n const context: WalkAstContext<State> = { state };\n\n const visit = (currentNode: Node): void => {\n visitors._?.(currentNode, context);\n getSpecializedVisitor(currentNode, visitors)?.(currentNode, context);\n\n for (const key of Object.keys(currentNode)) {\n if (key === 'type') {\n continue;\n }\n\n visitChildren((currentNode as Record<string, unknown>)[key]);\n }\n };\n\n const visitChildren = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isAstNode(item)) {\n visit(item as Node);\n }\n }\n return;\n }\n\n if (isAstNode(value)) {\n visit(value as Node);\n }\n };\n\n visit(node);\n}\n\nfunction isAstNode(value: unknown): value is BaseNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n typeof value.type === 'string'\n );\n}\n\nfunction getSpecializedVisitor<Node extends BaseNode, State>(\n node: Node,\n visitors: WalkAstVisitors<Node, State>,\n): WalkAstVisitor<BaseNode, State> | undefined {\n return (visitors as Record<string, WalkAstVisitor<BaseNode, State> | undefined>)[node.type];\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 * as eslintScope from 'eslint-scope';\nimport type { Identifier, Node, Program } from 'estree';\n\nimport { walkAst } from './walk-ast';\n\n/**\n * Generic eslint-scope facts for one parsed ES module.\n *\n * This intentionally has no action-catalog or connection ID concepts. Consumers\n * can use it to resolve an identifier node back to the declaration variable\n * eslint-scope found for that exact source location.\n */\nexport interface ModuleScopeAnalysis {\n scopeManager: eslintScope.ScopeManager;\n referencesByIdentifier: Map<Identifier, eslintScope.Reference>;\n moduleScope: eslintScope.Scope;\n}\n\ntype NodeWithRange = Node & { start?: number; end?: number; range?: [number, number] };\n\nexport function analyzeModuleScope(ast: Program): ModuleScopeAnalysis {\n ensureRanges(ast);\n const scopeManager = eslintScope.analyze(ast, {\n ecmaVersion: 2022,\n ignoreEval: true,\n sourceType: 'module',\n });\n\n const referencesByIdentifier = new Map<Identifier, eslintScope.Reference>();\n for (const scope of scopeManager.scopes) {\n for (const reference of scope.references) {\n referencesByIdentifier.set(reference.identifier, reference);\n }\n }\n\n return {\n scopeManager,\n referencesByIdentifier,\n moduleScope: getModuleScope(scopeManager),\n };\n}\n\nexport function resolveIdentifier(\n identifier: Identifier,\n scopeAnalysis: ModuleScopeAnalysis,\n): eslintScope.Variable | undefined {\n return scopeAnalysis.referencesByIdentifier.get(identifier)?.resolved ?? undefined;\n}\n\nexport function resolvesTo(\n identifier: Identifier,\n variables: ReadonlySet<eslintScope.Variable>,\n scopeAnalysis: ModuleScopeAnalysis,\n): boolean {\n const variable = resolveIdentifier(identifier, scopeAnalysis);\n return !!variable && variables.has(variable);\n}\n\nexport function isImportVariable(variable: eslintScope.Variable): boolean {\n return variable.defs.some((definition) => definition.type === 'ImportBinding');\n}\n\nexport function getModuleVariable(\n name: string,\n scopeAnalysis: ModuleScopeAnalysis,\n): eslintScope.Variable | undefined {\n return scopeAnalysis.moduleScope.set.get(name);\n}\n\nfunction getModuleScope(scopeManager: eslintScope.ScopeManager): eslintScope.Scope {\n return scopeManager.scopes.find((scope) => scope.type === 'module') ?? scopeManager.globalScope;\n}\n\nfunction ensureRanges(node: Node): void {\n walkAst(node, null, {\n _(child) {\n const nodeWithRange = child as NodeWithRange;\n if (\n !nodeWithRange.range &&\n typeof nodeWithRange.start === 'number' &&\n typeof nodeWithRange.end === 'number'\n ) {\n nodeWithRange.range = [nodeWithRange.start, nodeWithRange.end];\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 * as eslintScope from 'eslint-scope';\nimport type {\n AssignmentExpression,\n Identifier,\n MemberExpression,\n Node,\n Pattern,\n Program,\n SimpleCallExpression,\n VariableDeclarator,\n} from 'estree';\n\nimport type { ActionCatalogImports } from './action-catalog-imports';\nimport {\n isImportVariable,\n type ModuleScopeAnalysis,\n resolveIdentifier,\n resolvesTo as resolvesToModuleVariable,\n} from './module-scope';\nimport { walkAst } from './walk-ast';\n\n// Do not trust names alone when deciding whether `request(...)` is an\n// action-catalog call. A local parameter or variable can reuse the same name:\n//\n// import { request } from '@datadog/action-catalog/http/http';\n// request({ connectionId: 'real' });\n//\n// function run(request) {\n// request({ connectionId: 'local' });\n// }\n//\n// Both calls use the text `request`, but only the first one refers to the\n// imported action-catalog function. eslint-scope tells us which declaration\n// each identifier refers to; this analysis adds action-catalog-specific import\n// sets on top of the generic module scope facts.\nexport interface ActionCatalogScopeAnalysis {\n moduleScope: ModuleScopeAnalysis;\n actionFunctions: Set<eslintScope.Variable>;\n actionNamespaces: Set<eslintScope.Variable>;\n}\n\ninterface ActionCatalogCallState {\n scopeAnalysis: ActionCatalogScopeAnalysis;\n unsupportedAliases: Set<eslintScope.Variable>;\n}\n\nexport function analyzeActionCatalogScopes(\n moduleScope: ModuleScopeAnalysis,\n imports: ActionCatalogImports,\n): ActionCatalogScopeAnalysis {\n const actionFunctions = new Set<eslintScope.Variable>();\n const actionNamespaces = new Set<eslintScope.Variable>();\n\n for (const scope of moduleScope.scopeManager.scopes) {\n // Save the actual import declarations that came from action-catalog.\n // Later, when we see `request(...)`, we check whether that `request`\n // points back to one of these declarations instead of to a local\n // parameter or variable with the same name.\n for (const variable of scope.variables) {\n if (!isImportVariable(variable)) {\n continue;\n }\n if (imports.functions.has(variable.name)) {\n actionFunctions.add(variable);\n }\n if (imports.namespaces.has(variable.name)) {\n actionNamespaces.add(variable);\n }\n }\n }\n\n return { moduleScope, actionFunctions, actionNamespaces };\n}\n\nexport function findActionCatalogCallSites(\n ast: Program,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n filePath: string,\n): SimpleCallExpression[] {\n const callState: ActionCatalogCallState = {\n scopeAnalysis,\n unsupportedAliases: collectUnsupportedActionCatalogAliases(ast, scopeAnalysis),\n };\n const callSites: SimpleCallExpression[] = [];\n\n walkAst(ast, callState, {\n CallExpression(node, { state }) {\n if (classifyActionCatalogCall(node, state, filePath)) {\n callSites.push(node);\n }\n },\n });\n\n return callSites;\n}\n\nfunction classifyActionCatalogCall(\n node: SimpleCallExpression,\n state: ActionCatalogCallState,\n filePath: string,\n): boolean {\n const callee = node.callee;\n\n if (callee.type === 'Identifier') {\n if (resolvesTo(callee, state.unsupportedAliases, state.scopeAnalysis)) {\n throw unsupportedActionCatalogCall(filePath, 'action-catalog call aliases');\n }\n if (resolvesTo(callee, state.scopeAnalysis.actionFunctions, state.scopeAnalysis)) {\n if (node.optional) {\n throw unsupportedActionCatalogCall(filePath, 'optional action-catalog calls');\n }\n return true;\n }\n return false;\n }\n\n if (callee.type !== 'MemberExpression') {\n return false;\n }\n\n if (!isNamespaceMember(callee, state.scopeAnalysis)) {\n return false;\n }\n\n if (node.optional || hasUnsupportedMemberAccess(callee)) {\n throw unsupportedActionCatalogCall(\n filePath,\n 'optional or computed action-catalog namespace calls',\n );\n }\n return true;\n}\n\nfunction collectUnsupportedActionCatalogAliases(\n ast: Program,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): Set<eslintScope.Variable> {\n const unsupportedAliases = new Set<eslintScope.Variable>();\n\n walkAst(ast, scopeAnalysis, {\n VariableDeclarator(node, { state }) {\n for (const aliasVariable of getActionCatalogAliasVariables(node, state)) {\n unsupportedAliases.add(aliasVariable);\n }\n },\n AssignmentExpression(node, { state }) {\n for (const aliasVariable of getAssignedActionCatalogAliasVariables(node, state)) {\n unsupportedAliases.add(aliasVariable);\n }\n },\n });\n\n return unsupportedAliases;\n}\n\n/**\n * Finds variables declared as aliases of an action-catalog function.\n *\n * Examples this catches:\n * - `const action = request`\n * - `const action = http.request`\n * - `const { request: action } = http`\n *\n * We do not try to follow these aliases. Instead, we mark them as unsupported\n * so a later `action(...)` call fails closed instead of silently missing a\n * `connectionId`.\n */\nfunction getActionCatalogAliasVariables(\n node: VariableDeclarator,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n // `const action = request`\n if (\n node.id.type === 'Identifier' &&\n node.init?.type === 'Identifier' &&\n resolvesTo(node.init, scopeAnalysis.actionFunctions, scopeAnalysis)\n ) {\n return getDeclaredVariables(node, scopeAnalysis, [node.id.name]);\n }\n\n // `const action = http.request`\n if (\n node.id.type === 'Identifier' &&\n node.init?.type === 'MemberExpression' &&\n isNamespaceMember(node.init, scopeAnalysis)\n ) {\n return getDeclaredVariables(node, scopeAnalysis, [node.id.name]);\n }\n\n // Ignore declarations that are not destructuring an action-catalog namespace,\n // then handle `const { request: action } = http` below.\n if (\n node.id.type !== 'ObjectPattern' ||\n node.init?.type !== 'Identifier' ||\n !resolvesTo(node.init, scopeAnalysis.actionNamespaces, scopeAnalysis)\n ) {\n return [];\n }\n\n // In a declaration, eslint-scope can give us declared variables from the\n // whole `const { request: action } = http` node. We only need identifier\n // names to pick the alias variables out of that declaration result.\n const aliasNames = node.id.properties\n .flatMap((property) => {\n if (property.type === 'RestElement' || property.computed) {\n return [];\n }\n return collectPatternIdentifiers(property.value);\n })\n .map((identifier) => identifier.name);\n return getDeclaredVariables(node, scopeAnalysis, aliasNames);\n}\n\n/**\n * Finds existing variables that are assigned an action-catalog function after\n * they have already been declared.\n *\n * Examples this catches:\n * - `let action; action = request`\n * - `let action; action = http.request`\n * - `let action; ({ request: action } = http)`\n *\n * These are the assignment-expression versions of the declarations handled by\n * `getActionCatalogAliasVariables`.\n */\nfunction getAssignedActionCatalogAliasVariables(\n node: AssignmentExpression,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n // `let action; action = request`\n if (\n node.left.type === 'Identifier' &&\n node.right.type === 'Identifier' &&\n resolvesTo(node.right, scopeAnalysis.actionFunctions, scopeAnalysis)\n ) {\n return getResolvedVariables([node.left], scopeAnalysis);\n }\n\n // `let action; action = http.request`\n if (\n node.left.type === 'Identifier' &&\n node.right.type === 'MemberExpression' &&\n isNamespaceMember(node.right, scopeAnalysis)\n ) {\n return getResolvedVariables([node.left], scopeAnalysis);\n }\n\n // Ignore assignments that are not destructuring an action-catalog namespace,\n // then handle `let action; ({ request: action } = http)` below.\n if (\n node.left.type !== 'ObjectPattern' ||\n node.right.type !== 'Identifier' ||\n !resolvesTo(node.right, scopeAnalysis.actionNamespaces, scopeAnalysis)\n ) {\n return [];\n }\n\n // In an assignment, the variables already exist. Keep the actual identifier\n // nodes so eslint-scope can resolve each one back to the existing variable.\n const aliasIdentifiers = node.left.properties.flatMap((property) => {\n if (property.type === 'RestElement' || property.computed) {\n return [];\n }\n return collectPatternIdentifiers(property.value);\n });\n return getResolvedVariables(aliasIdentifiers, scopeAnalysis);\n}\n\n/**\n * Returns true when a property access starts from an imported action-catalog\n * namespace.\n *\n * For `http.request(...)`, this checks that `http` is the namespace imported by\n * `import * as http from '@datadog/action-catalog/...'`, not a local variable\n * that happens to be named `http`.\n */\nfunction isNamespaceMember(\n node: MemberExpression,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): boolean {\n const root = getMemberExpressionRoot(node);\n return !!root && resolvesTo(root, scopeAnalysis.actionNamespaces, scopeAnalysis);\n}\n\n/**\n * Returns the left-most identifier in a property access chain.\n *\n * Examples:\n * - `http.request` -> `http`\n * - `catalog.http.request` -> `catalog`\n *\n * The root name is what scope analysis can resolve back to an import or local\n * declaration.\n */\nfunction getMemberExpressionRoot(node: MemberExpression): Identifier | undefined {\n if (node.object.type === 'Identifier') {\n return node.object;\n }\n if (node.object.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\n/**\n * Detects namespace call shapes we intentionally do not support.\n *\n * We only support direct, non-optional property access like `http.request(...)`.\n * Computed or optional forms such as `http['request'](...)` and\n * `http?.request(...)` could hide what action is called, so they fail closed.\n */\nfunction hasUnsupportedMemberAccess(node: MemberExpression): boolean {\n if (node.optional || node.computed) {\n return true;\n }\n return node.object.type === 'MemberExpression' && hasUnsupportedMemberAccess(node.object);\n}\n\n/**\n * Checks whether an identifier points to one of the exact variables we care\n * about.\n *\n * This is the shadowing-safe comparison. For example, a local function\n * parameter named `request` has the same text as an imported `request`, but\n * eslint-scope resolves it to a different variable.\n *\n * @param identifier - The exact identifier node from the AST, such as the\n * `request` in `request(...)`.\n * @param variables - The set of allowed target variables, such as the imported\n * action-catalog function declarations.\n * @param scopeAnalysis - The precomputed eslint-scope lookup tables that map\n * identifier nodes back to the variables they reference.\n */\nfunction resolvesTo(\n identifier: Identifier,\n variables: ReadonlySet<eslintScope.Variable>,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): boolean {\n return resolvesToModuleVariable(identifier, variables, scopeAnalysis.moduleScope);\n}\n\n/**\n * Converts identifier nodes into the variables they refer to.\n *\n * This is used for assignment aliases because the variable already exists:\n * `action = request` does not declare `action`, it only assigns to it. We ask\n * eslint-scope which existing variable that `action` identifier points to.\n */\nfunction getResolvedVariables(\n identifiers: Identifier[],\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n return identifiers.flatMap((identifier) => {\n const variable = resolveIdentifier(identifier, scopeAnalysis.moduleScope);\n return variable ? [variable] : [];\n });\n}\n\n/**\n * Returns variables created by a declaration node, limited to the names we\n * extracted from the declaration pattern.\n *\n * This is used for alias declarations like `const action = request`, where the\n * declaration itself creates the `action` variable we need to remember.\n */\nfunction getDeclaredVariables(\n node: Node,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n names: string[],\n): eslintScope.Variable[] {\n // Alias declarations are tracked as Variables too, so later `action(...)`\n // calls can fail closed only when they resolve to the alias we identified.\n const wantedNames = new Set(names);\n return scopeAnalysis.moduleScope.scopeManager\n .getDeclaredVariables(node)\n .filter((variable) => wantedNames.has(variable.name));\n}\n\n/**\n * Pulls identifier nodes out of a declaration or assignment pattern.\n *\n * Patterns are the left side of declarations or assignments, such as:\n * - `const action = ...`\n * - `const { request: action } = ...`\n * - `({ request: action } = ...)`\n *\n * Declarations use the identifier names to filter variables created by the\n * declaration. Assignments use the identifier nodes directly, because\n * eslint-scope resolves those nodes to existing variables.\n */\nfunction collectPatternIdentifiers(pattern: Pattern): Identifier[] {\n switch (pattern.type) {\n case 'Identifier':\n return [pattern];\n case 'ObjectPattern':\n return pattern.properties.flatMap((property) => {\n if (property.type === 'RestElement') {\n return collectPatternIdentifiers(property.argument);\n }\n return collectPatternIdentifiers(property.value);\n });\n case 'ArrayPattern':\n return pattern.elements.flatMap((element) =>\n element ? collectPatternIdentifiers(element) : [],\n );\n case 'RestElement':\n return collectPatternIdentifiers(pattern.argument);\n case 'AssignmentPattern':\n return collectPatternIdentifiers(pattern.left);\n case 'MemberExpression':\n return [];\n }\n}\n\nfunction unsupportedActionCatalogCall(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported action-catalog call in ${filePath}: ${unsupported} could hide a connectionId.`,\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 { Program } from 'estree';\n\nimport { isTypeOnly } from './type-guards';\n\nconst ACTION_CATALOG_PACKAGE = '@datadog/action-catalog';\n\nexport interface ActionCatalogImports {\n functions: Set<string>;\n namespaces: Set<string>;\n}\n\nexport function collectActionCatalogImports(ast: Program): ActionCatalogImports {\n const functions = new Set<string>();\n const namespaces = new Set<string>();\n\n for (const node of ast.body) {\n if (node.type !== 'ImportDeclaration' || !isActionCatalogSource(node.source.value)) {\n continue;\n }\n if (isTypeOnly(node)) {\n continue;\n }\n\n for (const specifier of node.specifiers) {\n if (isTypeOnly(specifier)) {\n continue;\n }\n\n if (specifier.type === 'ImportNamespaceSpecifier') {\n namespaces.add(specifier.local.name);\n } else {\n functions.add(specifier.local.name);\n }\n }\n }\n\n return { functions, namespaces };\n}\n\nexport function hasActionCatalogImports(imports: ActionCatalogImports): boolean {\n return imports.functions.size > 0 || imports.namespaces.size > 0;\n}\n\nfunction isActionCatalogSource(source: unknown): boolean {\n return (\n typeof source === 'string' &&\n (source === ACTION_CATALOG_PACKAGE || source.startsWith(`${ACTION_CATALOG_PACKAGE}/`))\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 * as eslintScope from 'eslint-scope';\nimport type { Identifier } from 'estree';\n\nimport type {\n ConstStaticBinding,\n ExportBinding,\n ImportBinding,\n MutableStaticBinding,\n ParsedModuleRecord,\n} from './module-graph';\nimport { resolveIdentifier } from './module-scope';\n\nexport type StaticDefinition = LocalStaticDefinition | UnsupportedStaticDefinition;\n\nexport interface LocalStaticDefinition {\n kind: 'local';\n moduleId: string;\n variable: eslintScope.Variable;\n binding: ConstStaticBinding;\n hops: StaticDefinitionHop[];\n}\n\nexport type UnsupportedStaticDefinition =\n | AmbiguousStarExportStaticDefinition\n | CycleStaticDefinition\n | DefaultExportStaticDefinition\n | DefaultImportStaticDefinition\n | MissingExportStaticDefinition\n | MissingModuleRecordForExportStaticDefinition\n | MissingModuleRecordForVariableStaticDefinition\n | MissingStaticBindingStaticDefinition\n | MutableBindingStaticDefinition\n | NamespaceImportStaticDefinition\n | UnresolvedIdentifierStaticDefinition\n | UnsupportedBindingStaticDefinition\n | UnsupportedExportStaticDefinition;\n\nexport type StaticDefinitionUnsupportedReason = UnsupportedStaticDefinition['reason'];\n\ninterface UnsupportedStaticDefinitionBase {\n kind: 'unsupported';\n moduleId: string;\n message: string;\n hops: StaticDefinitionHop[];\n}\n\nexport interface AmbiguousStarExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'ambiguous-star-export';\n exportName: string;\n}\n\nexport interface CycleStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'cycle';\n exportName: string;\n}\n\nexport interface DefaultExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'default-export';\n exportName: string;\n}\n\nexport interface DefaultImportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'default-import';\n variableName: string;\n}\n\nexport interface MissingExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'missing-export';\n exportName: string;\n}\n\nexport interface MissingModuleRecordForExportStaticDefinition\n extends UnsupportedStaticDefinitionBase {\n reason: 'missing-module-record';\n requestKind: 'export';\n exportName: string;\n}\n\nexport interface MissingModuleRecordForVariableStaticDefinition\n extends UnsupportedStaticDefinitionBase {\n reason: 'missing-module-record';\n requestKind: 'variable';\n variableName: string;\n}\n\nexport interface MissingStaticBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'missing-static-binding';\n variableName: string;\n}\n\nexport interface MutableBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'mutable-binding';\n variableName: string;\n declarationKind: MutableStaticBinding['declarationKind'];\n}\n\nexport interface NamespaceImportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'namespace-import';\n variableName: string;\n}\n\nexport interface UnresolvedIdentifierStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unresolved-identifier';\n variableName: string;\n}\n\nexport interface UnsupportedBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unsupported-binding';\n variableName: string;\n bindingReason: string;\n}\n\nexport interface UnsupportedExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unsupported-export';\n exportName: string;\n exportReason: string;\n}\n\nexport type StaticDefinitionHop =\n | ImportStaticDefinitionHop\n | LocalExportStaticDefinitionHop\n | ReExportStaticDefinitionHop\n | StarExportStaticDefinitionHop;\n\nexport interface ImportStaticDefinitionHop {\n kind: 'import';\n moduleId: string;\n localName: string;\n exportName: string;\n sourceModuleId: string;\n}\n\nexport interface LocalExportStaticDefinitionHop {\n kind: 'local-export';\n moduleId: string;\n exportName: string;\n localName: string;\n}\n\nexport interface ReExportStaticDefinitionHop {\n kind: 're-export';\n moduleId: string;\n exportName: string;\n sourceModuleId: string;\n sourceExportName: string;\n}\n\nexport interface StarExportStaticDefinitionHop {\n kind: 'star-export';\n moduleId: string;\n exportName: string;\n sourceModuleId: string;\n}\n\ninterface ResolverState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n visitedExports: Set<string>;\n}\n\nexport function resolveStaticDefinitionForIdentifier(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n moduleId: string,\n identifier: Identifier,\n): StaticDefinition {\n const record = modules.get(moduleId);\n if (!record) {\n return unsupportedMissingModuleRecordForVariable(moduleId, [], identifier.name);\n }\n\n const variable = resolveIdentifier(identifier, record.scopeAnalysis);\n if (!variable) {\n // Example: request({ connectionId: HTTP_ID }); when HTTP_ID is not in scope.\n return unsupportedUnresolvedIdentifier(moduleId, [], identifier.name);\n }\n if (isDefinitionIdentifier(identifier, variable)) {\n // Example: const HTTP_ID = 'conn-http'; when HTTP_ID is the declaration itself.\n return unsupportedUnresolvedIdentifier(moduleId, [], identifier.name);\n }\n\n return resolveVariable({ modules, visitedExports: new Set() }, moduleId, variable, []);\n}\n\nfunction isDefinitionIdentifier(identifier: Identifier, variable: eslintScope.Variable): boolean {\n return variable.defs.some((definition) => definition.name === identifier);\n}\n\nfunction resolveExport(\n state: ResolverState,\n moduleId: string,\n exportName: string,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n const record = state.modules.get(moduleId);\n if (!record) {\n return unsupportedMissingModuleRecordForExport(moduleId, hops, exportName);\n }\n\n if (exportName === 'default') {\n // Example: export { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultExport(moduleId, hops, exportName);\n }\n\n const visitKey = `${moduleId}\\0${exportName}`;\n if (state.visitedExports.has(visitKey)) {\n // Example: export * from './index.js'; when index.js eventually points back here.\n return unsupportedCycle(moduleId, hops, exportName);\n }\n\n state.visitedExports.add(visitKey);\n try {\n const explicitExport = record.exportsByName.get(exportName);\n if (explicitExport) {\n return resolveExplicitExport(state, record, exportName, explicitExport, hops);\n }\n\n return resolveStarExport(state, record, exportName, hops);\n } finally {\n state.visitedExports.delete(visitKey);\n }\n}\n\nfunction resolveExplicitExport(\n state: ResolverState,\n record: ParsedModuleRecord,\n exportName: string,\n binding: ExportBinding,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n if (binding.kind === 'unsupported') {\n // Example: export * as ids from './ids.js';\n return unsupportedExport(record.id, hops, exportName, binding.reason);\n }\n\n if (binding.kind === 're-export') {\n if (binding.importedName === 'default') {\n // Example: export { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultExport(record.id, hops, exportName);\n }\n\n return resolveExport(state, binding.resolvedId, binding.importedName, [\n ...hops,\n {\n kind: 're-export',\n moduleId: record.id,\n exportName,\n sourceModuleId: binding.resolvedId,\n sourceExportName: binding.importedName,\n },\n ]);\n }\n\n return resolveVariable(state, record.id, binding.variable, [\n ...hops,\n {\n kind: 'local-export',\n moduleId: record.id,\n exportName,\n localName: binding.variable.name,\n },\n ]);\n}\n\nfunction resolveStarExport(\n state: ResolverState,\n record: ParsedModuleRecord,\n exportName: string,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n let candidate: LocalStaticDefinition | undefined;\n\n for (const starExport of record.starExports) {\n const result = resolveExport(state, starExport.resolvedId, exportName, [\n ...hops,\n {\n kind: 'star-export',\n moduleId: record.id,\n exportName,\n sourceModuleId: starExport.resolvedId,\n },\n ]);\n\n if (result.kind === 'unsupported') {\n if (result.reason === 'missing-export') {\n continue;\n }\n\n return result;\n }\n\n if (candidate && isSameLocalDefinition(candidate, result)) {\n continue;\n }\n\n if (candidate) {\n // Example: export * from './one.js'; export * from './two.js';\n return unsupportedAmbiguousStarExport(record.id, hops, exportName);\n }\n candidate = result;\n }\n\n // Example: export * from './ids.js'; when ids.js does not export HTTP_ID.\n return candidate ?? unsupportedMissingExport(record.id, hops, exportName);\n}\n\nfunction isSameLocalDefinition(left: LocalStaticDefinition, right: LocalStaticDefinition): boolean {\n return left.moduleId === right.moduleId && left.variable === right.variable;\n}\n\nfunction resolveVariable(\n state: ResolverState,\n moduleId: string,\n variable: eslintScope.Variable,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n const record = state.modules.get(moduleId);\n if (!record) {\n // Example: resolving HTTP_ID after following an import to a module that was not collected.\n return unsupportedMissingModuleRecordForVariable(moduleId, hops, variable.name);\n }\n\n const importBinding = record.importsByVariable.get(variable);\n if (importBinding) {\n return resolveImportBinding(state, record.id, variable.name, importBinding, hops);\n }\n\n const binding = record.topLevelBindingsByVariable.get(variable);\n if (!binding) {\n // Example: export { HTTP_ID }; when HTTP_ID is not a recorded top-level binding.\n return unsupportedMissingStaticBinding(record.id, hops, variable.name);\n }\n\n if (binding.kind === 'const') {\n return { kind: 'local', moduleId: record.id, variable, binding, hops };\n }\n\n if (binding.kind === 'mutable') {\n // Example: export let HTTP_ID = 'conn-http';\n return unsupportedMutableBinding(record.id, hops, variable.name, binding.declarationKind);\n }\n\n // Example: export function getId() { return 'conn-http'; }\n return unsupportedBinding(record.id, hops, variable.name, binding.reason);\n}\n\nfunction resolveImportBinding(\n state: ResolverState,\n moduleId: string,\n localName: string,\n binding: ImportBinding,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n if (binding.kind === 'default') {\n // Example: import HTTP_ID from './ids.js';\n return unsupportedDefaultImport(moduleId, hops, localName);\n }\n\n if (binding.kind === 'namespace') {\n // Example: import * as ids from './ids.js';\n return unsupportedNamespaceImport(moduleId, hops, localName);\n }\n\n if (binding.importedName === 'default') {\n // Example: import { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultImport(moduleId, hops, localName);\n }\n\n return resolveExport(state, binding.resolvedId, binding.importedName, [\n ...hops,\n {\n kind: 'import',\n moduleId,\n localName,\n exportName: binding.importedName,\n sourceModuleId: binding.resolvedId,\n },\n ]);\n}\n\nfunction unsupportedAmbiguousStarExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): AmbiguousStarExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'ambiguous-star-export',\n exportName,\n message: `Module '${moduleId}' exposes ambiguous star exports for '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedCycle(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): CycleStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'cycle',\n exportName,\n message: `Resolving export '${exportName}' from module '${moduleId}' would cycle through the module graph.`,\n hops,\n };\n}\n\nfunction unsupportedDefaultExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): DefaultExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'default-export',\n exportName,\n message: `Export '${exportName}' from module '${moduleId}' resolves through an unsupported default export.`,\n hops,\n };\n}\n\nfunction unsupportedDefaultImport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): DefaultImportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'default-import',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' is an unsupported default import.`,\n hops,\n };\n}\n\nfunction unsupportedMissingExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): MissingExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-export',\n exportName,\n message: `Module '${moduleId}' does not expose export '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingModuleRecordForExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): MissingModuleRecordForExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-module-record',\n requestKind: 'export',\n exportName,\n message: `Module '${moduleId}' was not collected while resolving export '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingModuleRecordForVariable(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): MissingModuleRecordForVariableStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-module-record',\n requestKind: 'variable',\n variableName,\n message: `Module '${moduleId}' was not collected while resolving variable '${variableName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingStaticBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): MissingStaticBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-static-binding',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' does not have a recorded top-level static binding.`,\n hops,\n };\n}\n\nfunction unsupportedMutableBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n declarationKind: MutableStaticBinding['declarationKind'],\n): MutableBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'mutable-binding',\n variableName,\n declarationKind,\n message: `Variable '${variableName}' in module '${moduleId}' is declared with mutable '${declarationKind}'.`,\n hops,\n };\n}\n\nfunction unsupportedNamespaceImport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): NamespaceImportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'namespace-import',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' is an unsupported namespace import.`,\n hops,\n };\n}\n\nfunction unsupportedUnresolvedIdentifier(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): UnresolvedIdentifierStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unresolved-identifier',\n variableName,\n message: `Identifier '${variableName}' in module '${moduleId}' is not a resolvable reference.`,\n hops,\n };\n}\n\nfunction unsupportedBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n bindingReason: string,\n): UnsupportedBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-binding',\n variableName,\n bindingReason,\n message: `Variable '${variableName}' in module '${moduleId}' has unsupported binding: ${bindingReason}.`,\n hops,\n };\n}\n\nfunction unsupportedExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n exportReason: string,\n): UnsupportedExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-export',\n exportName,\n exportReason,\n message: `Export '${exportName}' from module '${moduleId}' is unsupported: ${exportReason}.`,\n hops,\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 * as eslintScope from 'eslint-scope';\nimport type {\n Expression,\n Identifier,\n Literal,\n MemberExpression,\n ObjectExpression,\n Pattern,\n Property,\n Super,\n TemplateLiteral,\n VariableDeclaration,\n VariableDeclarator,\n} from 'estree';\n\nimport type { ParsedModuleRecord } from './module-graph';\nimport { isImportVariable, resolveIdentifier } from './module-scope';\nimport {\n resolveStaticDefinitionForIdentifier,\n type UnsupportedStaticDefinition,\n} from './static-definition-resolution';\nimport { walkAst } from './walk-ast';\n\nexport type StaticStringValueResolution = ResolvedStaticStringValue | UnsupportedStaticStringValue;\n\nexport interface ResolvedStaticStringValue {\n kind: 'resolved';\n moduleId: string;\n value: string;\n}\n\nexport type UnsupportedStaticStringValue =\n | AccessorObjectPropertyStaticStringValue\n | ComputedMemberExpressionStaticStringValue\n | ComputedObjectPropertyStaticStringValue\n | CycleStaticStringValue\n | DuplicateObjectPropertyStaticStringValue\n | DynamicTemplateLiteralStaticStringValue\n | ImportedObjectMutationStaticStringValue\n | MissingObjectPropertyStaticStringValue\n | NonObjectMemberValueStaticStringValue\n | NonStaticMemberPropertyStaticStringValue\n | NonStringLiteralStaticStringValue\n | ObjectSpreadStaticStringValue\n | OptionalMemberExpressionStaticStringValue\n | StaticDefinitionUnsupportedStaticStringValue\n | UninitializedConstStaticStringValue\n | UnsupportedExpressionStaticStringValue\n | UnsupportedObjectPropertyValueStaticStringValue;\n\nexport type StaticStringValueUnsupportedReason = UnsupportedStaticStringValue['reason'];\n\ninterface UnsupportedStaticStringValueBase {\n kind: 'unsupported';\n moduleId: string;\n message: string;\n}\n\n// Example: const CONNECTIONS = { get HTTP() { return 'conn-http'; } };\nexport interface AccessorObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'accessor-object-property';\n propertyName: string;\n}\n\n// Example: CONNECTIONS[key]\nexport interface ComputedMemberExpressionStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'computed-member-expression';\n}\n\n// Example: const CONNECTIONS = { [key]: 'conn-http' };\nexport interface ComputedObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'computed-object-property';\n}\n\n// Example: const A = B; const B = A;\nexport interface CycleStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'cycle';\n variableName: string;\n}\n\n// Example: const CONNECTIONS = { HTTP: 'a', HTTP: 'b' };\nexport interface DuplicateObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'duplicate-object-property';\n propertyName: string;\n}\n\n// Example: const VALUE = `${prefix}-http`;\nexport interface DynamicTemplateLiteralStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'dynamic-template-literal';\n}\n\n// Example: import { CONNECTIONS } from './ids.js'; CONNECTIONS.HTTP = 'conn-b';\nexport interface ImportedObjectMutationStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'imported-object-mutation';\n variableName: string;\n}\n\n// Example: const CONNECTIONS = { SLACK: 'conn-slack' }; CONNECTIONS.HTTP\nexport interface MissingObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'missing-object-property';\n propertyName: string;\n}\n\n// Example: const CONNECTIONS = { HTTP: 'conn-http' }; CONNECTIONS.HTTP.PROD\nexport interface NonObjectMemberValueStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-object-member-value';\n expressionType: string;\n}\n\n// Example: object.#privateValue\nexport interface NonStaticMemberPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-static-member-property';\n propertyType: string;\n}\n\n// Example: const VALUE = 123;\nexport interface NonStringLiteralStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-string-literal';\n valueType: string;\n}\n\n// Example: const CONNECTIONS = { ...baseConnections };\nexport interface ObjectSpreadStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'object-spread';\n}\n\n// Example: CONNECTIONS?.HTTP\nexport interface OptionalMemberExpressionStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'optional-member-expression';\n}\n\n// Example: import HTTP_ID from './ids.js';\nexport interface StaticDefinitionUnsupportedStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'static-definition-unsupported';\n variableName: string;\n definition: UnsupportedStaticDefinition;\n}\n\n// Defensive parser edge: a const binding exists without an initializer expression.\nexport interface UninitializedConstStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'uninitialized-const';\n variableName: string;\n}\n\n// Example: getConnectionId()\nexport interface UnsupportedExpressionStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'unsupported-expression';\n expressionType: string;\n}\n\n// Defensive parser edge: an object property value is a pattern instead of an expression.\nexport interface UnsupportedObjectPropertyValueStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'unsupported-object-property-value';\n propertyName: string;\n valueType: string;\n}\n\ninterface ResolverState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n mutatedImportedObjectVariables: ReadonlySet<eslintScope.Variable>;\n seenVariables: Set<eslintScope.Variable>;\n}\n\ninterface ImportedObjectMutationState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n mutatedVariables: Set<eslintScope.Variable>;\n record: ParsedModuleRecord;\n}\n\ninterface ResolvedStaticExpression {\n kind: 'resolved';\n moduleId: string;\n expression: Expression;\n}\n\ntype StaticExpressionResolution = ResolvedStaticExpression | UnsupportedStaticStringValue;\n\ninterface ResolvedStaticObjectExpression {\n kind: 'resolved';\n moduleId: string;\n expression: ObjectExpression;\n}\n\ntype StaticObjectExpressionResolution =\n | ResolvedStaticObjectExpression\n | UnsupportedStaticStringValue;\n\ntype StaticObjectProperty = Property & { value: Expression };\n\ntype TypeScriptExpressionWrapper = Expression & {\n expression?: Expression;\n};\n\nexport function resolveStaticStringValue(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n moduleId: string,\n expression: Expression,\n): StaticStringValueResolution {\n return resolveExpression(\n {\n modules,\n mutatedImportedObjectVariables: collectMutatedImportedObjectVariables(modules),\n seenVariables: new Set(),\n },\n moduleId,\n expression,\n );\n}\n\nfunction resolveExpression(\n state: ResolverState,\n moduleId: string,\n rawExpression: Expression,\n): StaticStringValueResolution {\n const expression = unwrapStaticExpression(rawExpression);\n\n switch (expression.type) {\n case 'Literal':\n return resolveLiteral(moduleId, expression);\n case 'TemplateLiteral':\n return resolveTemplateLiteral(moduleId, expression);\n case 'Identifier':\n return resolveIdentifierValue(state, moduleId, expression);\n case 'MemberExpression':\n return resolveMemberExpressionValue(state, moduleId, expression);\n default:\n return unsupportedExpression(moduleId, expression.type);\n }\n}\n\nfunction resolveLiteral(moduleId: string, expression: Literal): StaticStringValueResolution {\n if (typeof expression.value === 'string') {\n return {\n kind: 'resolved',\n moduleId,\n value: expression.value,\n };\n }\n\n return unsupportedNonStringLiteral(moduleId, typeof expression.value);\n}\n\nfunction resolveTemplateLiteral(\n moduleId: string,\n expression: TemplateLiteral,\n): StaticStringValueResolution {\n if (expression.expressions.length > 0) {\n return unsupportedDynamicTemplateLiteral(moduleId);\n }\n\n return {\n kind: 'resolved',\n moduleId,\n value: expression.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(''),\n };\n}\n\nfunction resolveIdentifierValue(\n state: ResolverState,\n moduleId: string,\n identifier: Identifier,\n): StaticStringValueResolution {\n // Follow local bindings, imports, and exports to the const definition that owns the value.\n const definition = resolveStaticDefinitionForIdentifier(state.modules, moduleId, identifier);\n\n if (definition.kind === 'unsupported') {\n return unsupportedStaticDefinition(definition, identifier.name);\n }\n\n if (!definition.binding.expression) {\n return unsupportedUninitializedConst(definition.moduleId, definition.variable.name);\n }\n\n // Track the resolved variable so aliases and reexports share the same cycle guard.\n if (state.seenVariables.has(definition.variable)) {\n return unsupportedCycle(definition.moduleId, definition.variable.name);\n }\n\n state.seenVariables.add(definition.variable);\n try {\n return resolveExpression(state, definition.moduleId, definition.binding.expression);\n } finally {\n state.seenVariables.delete(definition.variable);\n }\n}\n\nfunction resolveMemberExpressionValue(\n state: ResolverState,\n moduleId: string,\n expression: MemberExpression,\n): StaticStringValueResolution {\n const resolvedExpression = resolveObjectMemberExpression(state, moduleId, expression);\n if (resolvedExpression.kind === 'unsupported') {\n return resolvedExpression;\n }\n\n return resolveExpression(state, resolvedExpression.moduleId, resolvedExpression.expression);\n}\n\nfunction resolveObjectMemberExpression(\n state: ResolverState,\n moduleId: string,\n expression: MemberExpression,\n): StaticExpressionResolution {\n if (expression.optional) {\n // Example: CONNECTIONS?.HTTP\n return unsupportedOptionalMemberExpression(moduleId);\n }\n if (expression.computed) {\n // Example: CONNECTIONS[key]\n return unsupportedComputedMemberExpression(moduleId);\n }\n if (expression.property.type !== 'Identifier') {\n return unsupportedNonStaticMemberProperty(moduleId, expression.property.type);\n }\n\n const objectExpression = resolveObjectExpressionValue(state, moduleId, expression.object);\n if (objectExpression.kind === 'unsupported') {\n return objectExpression;\n }\n\n return resolveObjectPropertyExpression(\n objectExpression.moduleId,\n objectExpression.expression,\n expression.property.name,\n );\n}\n\nfunction resolveObjectExpressionValue(\n state: ResolverState,\n moduleId: string,\n rawExpression: Expression | Super,\n): StaticObjectExpressionResolution {\n if (rawExpression.type === 'Super') {\n return unsupportedNonObjectMemberValue(moduleId, rawExpression.type);\n }\n\n const expression = unwrapStaticExpression(rawExpression);\n\n if (expression.type === 'ObjectExpression') {\n return {\n kind: 'resolved',\n moduleId,\n expression,\n };\n }\n\n if (expression.type === 'MemberExpression') {\n const memberExpression = resolveObjectMemberExpression(state, moduleId, expression);\n if (memberExpression.kind === 'unsupported') {\n return memberExpression;\n }\n\n return resolveObjectExpressionValue(\n state,\n memberExpression.moduleId,\n memberExpression.expression,\n );\n }\n\n if (expression.type !== 'Identifier') {\n return unsupportedNonObjectMemberValue(moduleId, expression.type);\n }\n\n const definition = resolveStaticDefinitionForIdentifier(state.modules, moduleId, expression);\n\n if (definition.kind === 'unsupported') {\n return unsupportedStaticDefinition(definition, expression.name);\n }\n\n if (!definition.binding.expression) {\n return unsupportedUninitializedConst(definition.moduleId, definition.variable.name);\n }\n\n if (state.mutatedImportedObjectVariables.has(definition.variable)) {\n return unsupportedImportedObjectMutation(definition.moduleId, definition.variable.name);\n }\n\n if (state.seenVariables.has(definition.variable)) {\n return unsupportedCycle(definition.moduleId, definition.variable.name);\n }\n\n state.seenVariables.add(definition.variable);\n try {\n return resolveObjectExpressionValue(\n state,\n definition.moduleId,\n definition.binding.expression,\n );\n } finally {\n state.seenVariables.delete(definition.variable);\n }\n}\n\nfunction resolveObjectPropertyExpression(\n moduleId: string,\n objectExpression: ObjectExpression,\n propertyName: string,\n): StaticExpressionResolution {\n let match: StaticObjectProperty | undefined;\n\n for (const property of objectExpression.properties) {\n if (property.type === 'SpreadElement') {\n // Example: const CONNECTIONS = { ...baseConnections };\n return unsupportedObjectSpread(moduleId);\n }\n if (property.computed) {\n // Example: const CONNECTIONS = { [key]: 'conn-http' };\n return unsupportedComputedObjectProperty(moduleId);\n }\n\n const key = getStaticPropertyKey(property);\n if (key !== propertyName) {\n continue;\n }\n\n if (match) {\n // Example: const CONNECTIONS = { HTTP: 'a', HTTP: 'b' };\n return unsupportedDuplicateObjectProperty(moduleId, propertyName);\n }\n if (property.kind !== 'init') {\n // Example: const CONNECTIONS = { get HTTP() { return 'conn-http'; } };\n return unsupportedAccessorObjectProperty(moduleId, propertyName);\n }\n if (!hasExpressionValue(property)) {\n return unsupportedObjectPropertyValue(moduleId, propertyName, property.value.type);\n }\n\n match = property;\n }\n\n if (!match) {\n return unsupportedMissingObjectProperty(moduleId, propertyName);\n }\n\n return {\n kind: 'resolved',\n moduleId,\n expression: match.value,\n };\n}\n\nfunction hasExpressionValue(property: Property): property is Property & { value: Expression } {\n const { value } = property;\n return (\n value.type !== 'ObjectPattern' &&\n value.type !== 'ArrayPattern' &&\n value.type !== 'RestElement' &&\n value.type !== 'AssignmentPattern'\n );\n}\n\nfunction collectMutatedImportedObjectVariables(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n): Set<eslintScope.Variable> {\n const mutatedVariables = new Set<eslintScope.Variable>();\n\n for (const record of modules.values()) {\n walkAst(\n record.ast,\n { modules, mutatedVariables, record },\n {\n AssignmentExpression(node, { state }) {\n markMutatedImportedPattern(node.left, state);\n },\n UpdateExpression(node, { state }) {\n markMutatedImportedPattern(node.argument, state);\n },\n UnaryExpression(node, { state }) {\n if (node.operator === 'delete') {\n markMutatedImportedPattern(node.argument, state);\n }\n },\n ForInStatement(node, { state }) {\n markMutatedImportedForIterationTarget(node.left, state);\n },\n ForOfStatement(node, { state }) {\n markMutatedImportedForIterationTarget(node.left, state);\n },\n },\n );\n }\n\n return mutatedVariables;\n}\n\nfunction markMutatedImportedForIterationTarget(\n left: Pattern | VariableDeclaration,\n state: ImportedObjectMutationState,\n): void {\n if (left.type !== 'VariableDeclaration') {\n markMutatedImportedPattern(left, state);\n }\n}\n\nfunction markMutatedImportedPattern(\n pattern: Pattern | Expression,\n state: ImportedObjectMutationState,\n): void {\n if (pattern.type === 'Identifier') {\n markMutatedImportedIdentifier(pattern, state);\n return;\n }\n\n if (pattern.type === 'MemberExpression') {\n const root = getMemberExpressionRoot(pattern);\n if (root) {\n markMutatedImportedIdentifier(root, state);\n }\n return;\n }\n\n if (pattern.type === 'ObjectPattern') {\n for (const property of pattern.properties) {\n markMutatedImportedPattern(\n property.type === 'RestElement' ? property.argument : property.value,\n state,\n );\n }\n return;\n }\n\n if (pattern.type === 'ArrayPattern') {\n for (const element of pattern.elements) {\n if (element) {\n markMutatedImportedPattern(element, state);\n }\n }\n return;\n }\n\n if (pattern.type === 'RestElement') {\n markMutatedImportedPattern(pattern.argument, state);\n return;\n }\n\n if (pattern.type === 'AssignmentPattern') {\n markMutatedImportedPattern(pattern.left, state);\n }\n}\n\nfunction markMutatedImportedIdentifier(\n identifier: Identifier,\n state: ImportedObjectMutationState,\n): void {\n const variable = resolveImportedObjectAlias(state, identifier, new Set());\n if (variable) {\n state.mutatedVariables.add(variable);\n }\n}\n\nfunction resolveImportedObjectAlias(\n state: ImportedObjectMutationState,\n identifier: Identifier,\n seenVariables: Set<eslintScope.Variable>,\n): eslintScope.Variable | undefined {\n const variable = resolveIdentifier(identifier, state.record.scopeAnalysis);\n if (!variable || seenVariables.has(variable)) {\n return undefined;\n }\n seenVariables.add(variable);\n\n if (isImportVariable(variable)) {\n const definition = resolveStaticDefinitionForIdentifier(\n state.modules,\n state.record.id,\n identifier,\n );\n return definition.kind === 'local' ? definition.variable : undefined;\n }\n\n const initializer = getVariableInitializer(variable);\n if (!initializer) {\n return undefined;\n }\n\n const root = getImportedObjectAliasRoot(initializer);\n if (!root) {\n return undefined;\n }\n\n return resolveImportedObjectAlias(state, root, seenVariables);\n}\n\nfunction getVariableInitializer(variable: eslintScope.Variable): Expression | undefined {\n for (const definition of variable.defs) {\n const node = definition.node as VariableDeclarator;\n if (node.type === 'VariableDeclarator' && node.init) {\n return node.init;\n }\n }\n\n return undefined;\n}\n\nfunction getImportedObjectAliasRoot(rawExpression: Expression): Identifier | undefined {\n const expression = unwrapStaticExpression(rawExpression);\n if (expression.type === 'Identifier') {\n return expression;\n }\n if (expression.type === 'MemberExpression') {\n return getMemberExpressionRoot(expression);\n }\n return undefined;\n}\n\nfunction getMemberExpressionRoot(node: Expression | Super): Identifier | undefined {\n if (node.type === 'Identifier') {\n return node;\n }\n if (node.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\nfunction getStaticPropertyKey(property: Property): string | undefined {\n if (property.key.type === 'Identifier') {\n return property.key.name;\n }\n if (property.key.type === 'Literal' && typeof property.key.value === 'string') {\n return property.key.value;\n }\n return undefined;\n}\n\nfunction unwrapStaticExpression(expression: Expression): Expression {\n let current = expression;\n\n while (isTypeScriptExpressionWrapper(current)) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction isTypeScriptExpressionWrapper(\n expression: Expression,\n): expression is TypeScriptExpressionWrapper & { expression: Expression } {\n const type = (expression as { type: string }).type;\n return (\n (type === 'TSAsExpression' ||\n type === 'TSSatisfiesExpression' ||\n type === 'TSNonNullExpression' ||\n type === 'TSTypeAssertion') &&\n !!(expression as TypeScriptExpressionWrapper).expression\n );\n}\n\nfunction unsupportedAccessorObjectProperty(\n moduleId: string,\n propertyName: string,\n): AccessorObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'accessor-object-property',\n propertyName,\n message: `Static object property '${propertyName}' in module '${moduleId}' is an accessor.`,\n };\n}\n\nfunction unsupportedComputedMemberExpression(\n moduleId: string,\n): ComputedMemberExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'computed-member-expression',\n message: `Computed member expressions in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedComputedObjectProperty(\n moduleId: string,\n): ComputedObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'computed-object-property',\n message: `Computed object properties in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedCycle(moduleId: string, variableName: string): CycleStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'cycle',\n variableName,\n message: `Resolving variable '${variableName}' in module '${moduleId}' would cycle through static string values.`,\n };\n}\n\nfunction unsupportedDuplicateObjectProperty(\n moduleId: string,\n propertyName: string,\n): DuplicateObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'duplicate-object-property',\n propertyName,\n message: `Static object in module '${moduleId}' has duplicate property '${propertyName}'.`,\n };\n}\n\nfunction unsupportedDynamicTemplateLiteral(\n moduleId: string,\n): DynamicTemplateLiteralStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'dynamic-template-literal',\n message: `Dynamic template literals in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedImportedObjectMutation(\n moduleId: string,\n variableName: string,\n): ImportedObjectMutationStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'imported-object-mutation',\n variableName,\n message: `Imported object '${variableName}' from module '${moduleId}' is mutated in the module graph.`,\n };\n}\n\nfunction unsupportedMissingObjectProperty(\n moduleId: string,\n propertyName: string,\n): MissingObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-object-property',\n propertyName,\n message: `Static object in module '${moduleId}' does not have property '${propertyName}'.`,\n };\n}\n\nfunction unsupportedNonObjectMemberValue(\n moduleId: string,\n expressionType: string,\n): NonObjectMemberValueStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-object-member-value',\n expressionType,\n message: `Expression type '${expressionType}' in module '${moduleId}' is not a static object value.`,\n };\n}\n\nfunction unsupportedNonStaticMemberProperty(\n moduleId: string,\n propertyType: string,\n): NonStaticMemberPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-static-member-property',\n propertyType,\n message: `Member property type '${propertyType}' in module '${moduleId}' is not statically named.`,\n };\n}\n\nfunction unsupportedNonStringLiteral(\n moduleId: string,\n valueType: string,\n): NonStringLiteralStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-string-literal',\n valueType,\n message: `Literal value type '${valueType}' in module '${moduleId}' is not a string.`,\n };\n}\n\nfunction unsupportedObjectPropertyValue(\n moduleId: string,\n propertyName: string,\n valueType: string,\n): UnsupportedObjectPropertyValueStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-object-property-value',\n propertyName,\n valueType,\n message: `Static object property '${propertyName}' in module '${moduleId}' has unsupported value type '${valueType}'.`,\n };\n}\n\nfunction unsupportedObjectSpread(moduleId: string): ObjectSpreadStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'object-spread',\n message: `Object spreads in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedOptionalMemberExpression(\n moduleId: string,\n): OptionalMemberExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'optional-member-expression',\n message: `Optional member expressions in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedStaticDefinition(\n definition: UnsupportedStaticDefinition,\n variableName: string,\n): StaticDefinitionUnsupportedStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId: definition.moduleId,\n reason: 'static-definition-unsupported',\n variableName,\n definition,\n message: `Variable '${variableName}' could not be resolved to a static definition: ${definition.message}`,\n };\n}\n\nfunction unsupportedUninitializedConst(\n moduleId: string,\n variableName: string,\n): UninitializedConstStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'uninitialized-const',\n variableName,\n message: `Const variable '${variableName}' in module '${moduleId}' does not have an initializer.`,\n };\n}\n\nfunction unsupportedExpression(\n moduleId: string,\n expressionType: string,\n): UnsupportedExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-expression',\n expressionType,\n message: `Expression type '${expressionType}' in module '${moduleId}' cannot be resolved to a static string.`,\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 * as eslintScope from 'eslint-scope';\nimport type {\n BaseNode,\n ExportAllDeclaration,\n ExportNamedDeclaration,\n Expression,\n Identifier,\n ImportExpression,\n Literal,\n ModuleDeclaration,\n Pattern,\n Program,\n SimpleCallExpression,\n Super,\n VariableDeclaration,\n} from 'estree';\nimport path from 'path';\n\nimport { BACKEND_CODE_EXTENSIONS } from '../../constants';\n\nimport {\n analyzeModuleScope,\n getModuleVariable,\n isImportVariable,\n type ModuleScopeAnalysis,\n resolveIdentifier,\n} from './module-scope';\nimport { ensureProgram, isStringLiteral } from './type-guards';\nimport { walkAst } from './walk-ast';\n\n/**\n * Parsed app-local backend module plus reusable static facts about its module\n * boundary and top-level declarations. These facts are intentionally\n * domain-neutral: action-catalog and connection ID logic consume them later,\n * but they are not encoded into the record itself.\n */\nexport interface ParsedModuleRecord {\n id: string;\n ast: Program;\n scopeAnalysis: ModuleScopeAnalysis;\n staticDependencies: StaticModuleDependency[];\n unsupportedDependencies: ModuleDependency[];\n importsByVariable: Map<eslintScope.Variable, ImportBinding>;\n /**\n * Export names that can be answered directly by this module. Bare\n * `export *` edges stay in `starExports` because they must be probed by\n * requested export name during resolution.\n */\n exportsByName: Map<string, ExportBinding>;\n starExports: StarExport[];\n topLevelBindingsByVariable: Map<eslintScope.Variable, StaticBinding>;\n}\n\nexport interface StaticModuleDependency {\n source: string;\n resolvedId: string;\n}\n\nexport interface ModuleDependency {\n specifier: string;\n kind: 'dynamic-import' | 'require';\n}\n\n/**\n * Import binding keyed by the local eslint-scope variable, not the local text\n * name, so later lookups remain safe when names are shadowed.\n */\nexport type ImportBinding = NamedImportBinding | DefaultImportBinding | NamespaceImportBinding;\n\nexport interface NamedImportBinding {\n kind: 'named';\n importedName: string;\n resolvedId: string;\n}\n\nexport interface DefaultImportBinding {\n kind: 'default';\n resolvedId: string;\n}\n\nexport interface NamespaceImportBinding {\n kind: 'namespace';\n resolvedId: string;\n}\n\n/**\n * Export binding for names this module can answer without probing star\n * exports. Unsupported records preserve the fact that an export name exists\n * even when later static definition resolution will reject its form.\n */\nexport type ExportBinding = LocalExportBinding | ReExportBinding | UnsupportedExportBinding;\n\nexport interface LocalExportBinding {\n kind: 'local';\n variable: eslintScope.Variable;\n}\n\nexport interface ReExportBinding {\n kind: 're-export';\n importedName: string;\n resolvedId: string;\n}\n\nexport interface UnsupportedExportBinding {\n kind: 'unsupported';\n reason: string;\n resolvedId?: string;\n}\n\nexport interface StarExport {\n resolvedId: string;\n}\n\n/**\n * Top-level declaration summary. This records whether a local variable has a\n * static expression later resolvers can inspect, without deciding whether that\n * expression is meaningful for any particular domain.\n */\nexport type StaticBinding = ConstStaticBinding | MutableStaticBinding | UnsupportedStaticBinding;\n\nexport interface ConstStaticBinding {\n kind: 'const';\n expression: Expression | null;\n}\n\nexport interface MutableStaticBinding {\n kind: 'mutable';\n declarationKind: Exclude<VariableDeclaration['kind'], 'const'>;\n}\n\nexport interface UnsupportedStaticBinding {\n kind: 'unsupported';\n reason: string;\n}\n\ntype ImportCallExpression = SimpleCallExpression & { callee: { type: 'Import' } };\ntype ModuleExportName = Identifier | Literal;\n\nconst PACKAGE_MANAGER_DIRS = new Set(['node_modules', '.yarn']);\n\n/**\n * Creates the per-module analysis record consumed by backend-entry reachability\n * analysis. The caller supplies canonical module IDs and already-resolved\n * static dependency IDs instead of asking this module to resolve/load files.\n *\n * Returns null when the module is outside the analyzable app-local backend\n * graph, allowing build collectors to skip package/generated modules without\n * duplicating graph filtering rules.\n */\nexport function createParsedModuleRecord(\n moduleId: string,\n buildRoot: string,\n ast: BaseNode,\n staticDependencies: string[] = [],\n): ParsedModuleRecord | null {\n if (!shouldTraverseCollectedModule(moduleId, buildRoot)) {\n return null;\n }\n\n const program = ensureProgram(ast, moduleId);\n const scopeAnalysis = analyzeModuleScope(program);\n const staticModuleDependencies = collectStaticModuleDependencies(program, staticDependencies);\n\n return {\n id: moduleId,\n ast: program,\n scopeAnalysis,\n staticDependencies: staticModuleDependencies,\n unsupportedDependencies: collectUnsupportedModuleDependencies(program),\n importsByVariable: collectImportBindings(program, scopeAnalysis, staticModuleDependencies),\n exportsByName: collectExportBindings(program, scopeAnalysis, staticModuleDependencies),\n starExports: collectStarExports(program, staticModuleDependencies),\n topLevelBindingsByVariable: collectTopLevelBindings(program, scopeAnalysis),\n };\n}\n\nfunction collectStaticModuleDependencies(\n ast: Program,\n staticDependencyIds: string[],\n): StaticModuleDependency[] {\n const staticModuleSources = getStaticModuleSources(ast);\n\n return staticDependencyIds.map((resolvedId, index) => ({\n source: staticModuleSources[index] ?? resolvedId,\n resolvedId,\n }));\n}\n\nfunction getStaticModuleSources(ast: Program): string[] {\n return ast.body.flatMap((node) => {\n if (\n (node.type === 'ImportDeclaration' ||\n node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportAllDeclaration') &&\n node.source &&\n isStringLiteral(node.source)\n ) {\n return [node.source.value];\n }\n\n return [];\n });\n}\n\nfunction collectImportBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n): Map<eslintScope.Variable, ImportBinding> {\n const importsByVariable = new Map<eslintScope.Variable, ImportBinding>();\n\n for (const node of ast.body) {\n if (node.type !== 'ImportDeclaration' || !isStringLiteral(node.source)) {\n continue;\n }\n\n const resolvedId = getResolvedSource(staticDependencies, node.source.value);\n for (const specifier of node.specifiers) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(specifier);\n if (!variable) {\n continue;\n }\n\n if (specifier.type === 'ImportSpecifier') {\n importsByVariable.set(variable, {\n kind: 'named',\n importedName: getModuleExportName(specifier.imported),\n resolvedId,\n });\n continue;\n }\n\n importsByVariable.set(variable, {\n kind: specifier.type === 'ImportDefaultSpecifier' ? 'default' : 'namespace',\n resolvedId,\n });\n }\n }\n\n return importsByVariable;\n}\n\nfunction collectExportBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n): Map<string, ExportBinding> {\n const exportsByName = new Map<string, ExportBinding>();\n\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n collectNamedExportBindings(node, scopeAnalysis, staticDependencies, exportsByName);\n continue;\n }\n\n if (node.type === 'ExportDefaultDeclaration') {\n exportsByName.set('default', { kind: 'unsupported', reason: 'default export' });\n continue;\n }\n\n if (node.type === 'ExportAllDeclaration') {\n collectNamespaceExportBinding(node, staticDependencies, exportsByName);\n }\n }\n\n return exportsByName;\n}\n\nfunction collectNamedExportBindings(\n node: ExportNamedDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n exportsByName: Map<string, ExportBinding>,\n): void {\n if (node.declaration) {\n collectDeclarationExportBindings(node.declaration, scopeAnalysis, exportsByName);\n return;\n }\n\n if (node.source && isStringLiteral(node.source)) {\n const resolvedId = getResolvedSource(staticDependencies, node.source.value);\n for (const specifier of node.specifiers) {\n if (specifier.type !== 'ExportSpecifier') {\n continue;\n }\n const exportedName = getModuleExportName(specifier.exported);\n if (exportedName === 'default') {\n exportsByName.set(exportedName, {\n kind: 'unsupported',\n reason: 'default re-export',\n resolvedId,\n });\n continue;\n }\n exportsByName.set(exportedName, {\n kind: 're-export',\n importedName: getModuleExportName(specifier.local),\n resolvedId,\n });\n }\n return;\n }\n\n for (const specifier of node.specifiers) {\n if (specifier.type !== 'ExportSpecifier') {\n continue;\n }\n const exportedName = getModuleExportName(specifier.exported);\n if (exportedName === 'default') {\n exportsByName.set(exportedName, {\n kind: 'unsupported',\n reason: 'default export',\n });\n continue;\n }\n const variable = getModuleVariable(getModuleExportName(specifier.local), scopeAnalysis);\n exportsByName.set(\n exportedName,\n variable\n ? { kind: 'local', variable }\n : { kind: 'unsupported', reason: 'unresolved local export' },\n );\n }\n}\n\nfunction collectDeclarationExportBindings(\n declaration: ExportNamedDeclaration['declaration'],\n scopeAnalysis: ModuleScopeAnalysis,\n exportsByName: Map<string, ExportBinding>,\n): void {\n if (!declaration) {\n return;\n }\n\n if (declaration.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n const variables = scopeAnalysis.scopeManager.getDeclaredVariables(declarator);\n if (declarator.id.type !== 'Identifier') {\n for (const variable of variables) {\n exportsByName.set(variable.name, {\n kind: 'unsupported',\n reason: 'binding pattern export',\n });\n }\n continue;\n }\n\n const [variable] = variables;\n if (variable) {\n exportsByName.set(declarator.id.name, { kind: 'local', variable });\n }\n }\n return;\n }\n\n if (\n (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&\n declaration.id\n ) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(declaration);\n if (variable) {\n exportsByName.set(declaration.id.name, { kind: 'local', variable });\n }\n }\n}\n\nfunction collectNamespaceExportBinding(\n node: ExportAllDeclaration,\n staticDependencies: StaticModuleDependency[],\n exportsByName: Map<string, ExportBinding>,\n): void {\n const exported = getExportAllExportedName(node);\n if (!exported || !isStringLiteral(node.source)) {\n return;\n }\n\n exportsByName.set(exported, {\n kind: 'unsupported',\n reason: 'namespace re-export',\n resolvedId: getResolvedSource(staticDependencies, node.source.value),\n });\n}\n\nfunction collectStarExports(\n ast: Program,\n staticDependencies: StaticModuleDependency[],\n): StarExport[] {\n return ast.body.flatMap((node) => {\n if (\n node.type !== 'ExportAllDeclaration' ||\n getExportAllExportedName(node) ||\n !isStringLiteral(node.source)\n ) {\n return [];\n }\n\n return [{ resolvedId: getResolvedSource(staticDependencies, node.source.value) }];\n });\n}\n\nfunction collectTopLevelBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n): Map<eslintScope.Variable, StaticBinding> {\n const bindings = new Map<eslintScope.Variable, StaticBinding>();\n\n for (const node of ast.body) {\n collectTopLevelNodeBindings(node, scopeAnalysis, bindings);\n }\n\n markReassignedTopLevelBindings(ast, scopeAnalysis, bindings);\n return bindings;\n}\n\nfunction collectTopLevelNodeBindings(\n node: ModuleDeclaration | Program['body'][number],\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (node.type === 'VariableDeclaration') {\n collectVariableDeclarationBindings(node, scopeAnalysis, bindings);\n return;\n }\n\n if (\n node.type === 'ExportNamedDeclaration' &&\n node.declaration?.type === 'VariableDeclaration'\n ) {\n collectVariableDeclarationBindings(node.declaration, scopeAnalysis, bindings);\n return;\n }\n\n const declaration =\n node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration'\n ? node.declaration\n : node;\n if (\n declaration &&\n (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&\n declaration.id\n ) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(declaration);\n if (variable) {\n bindings.set(variable, {\n kind: 'unsupported',\n reason: `${declaration.type} binding`,\n });\n }\n }\n}\n\nfunction collectVariableDeclarationBindings(\n declaration: VariableDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n for (const declarator of declaration.declarations) {\n const variables = scopeAnalysis.scopeManager.getDeclaredVariables(declarator);\n if (declarator.id.type !== 'Identifier') {\n for (const variable of variables) {\n bindings.set(variable, { kind: 'unsupported', reason: 'binding pattern' });\n }\n continue;\n }\n\n const [variable] = variables;\n if (!variable) {\n continue;\n }\n if (declaration.kind === 'const') {\n bindings.set(variable, { kind: 'const', expression: declarator.init ?? null });\n } else {\n bindings.set(variable, {\n kind: 'mutable',\n declarationKind: declaration.kind,\n });\n }\n }\n}\n\nfunction markReassignedTopLevelBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n walkAst(\n ast,\n { scopeAnalysis, bindings },\n {\n AssignmentExpression(node, { state }) {\n markAssignedPattern(node.left, state.scopeAnalysis, state.bindings);\n },\n UpdateExpression(node, { state }) {\n markAssignedPattern(node.argument, state.scopeAnalysis, state.bindings);\n },\n UnaryExpression(node, { state }) {\n if (node.operator === 'delete') {\n markAssignedPattern(node.argument, state.scopeAnalysis, state.bindings);\n }\n },\n ForInStatement(node, { state }) {\n markForIterationTarget(node.left, state.scopeAnalysis, state.bindings);\n },\n ForOfStatement(node, { state }) {\n markForIterationTarget(node.left, state.scopeAnalysis, state.bindings);\n },\n },\n );\n}\n\nfunction markForIterationTarget(\n left: Pattern | VariableDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (left.type !== 'VariableDeclaration') {\n markAssignedPattern(left, scopeAnalysis, bindings);\n }\n}\n\nfunction markAssignedPattern(\n pattern: Pattern | Expression,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (pattern.type === 'Identifier') {\n markAssignedVariable(pattern, scopeAnalysis, bindings, 'reassigned binding');\n return;\n }\n\n if (pattern.type === 'MemberExpression') {\n const root = getMemberExpressionRoot(pattern);\n if (root) {\n markAssignedVariable(root, scopeAnalysis, bindings, 'mutated object binding');\n }\n return;\n }\n\n if (pattern.type === 'ObjectPattern') {\n for (const property of pattern.properties) {\n markAssignedPattern(\n property.type === 'RestElement' ? property.argument : property.value,\n scopeAnalysis,\n bindings,\n );\n }\n return;\n }\n\n if (pattern.type === 'ArrayPattern') {\n for (const element of pattern.elements) {\n if (element) {\n markAssignedPattern(element, scopeAnalysis, bindings);\n }\n }\n return;\n }\n\n if (pattern.type === 'RestElement') {\n markAssignedPattern(pattern.argument, scopeAnalysis, bindings);\n return;\n }\n\n if (pattern.type === 'AssignmentPattern') {\n markAssignedPattern(pattern.left, scopeAnalysis, bindings);\n }\n}\n\nfunction markAssignedVariable(\n identifier: Identifier,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n reason: string,\n): void {\n const variable = resolveIdentifier(identifier, scopeAnalysis);\n if (!variable || isImportVariable(variable) || !bindings.has(variable)) {\n return;\n }\n\n const binding = bindings.get(variable);\n if (binding?.kind === 'mutable') {\n return;\n }\n bindings.set(variable, { kind: 'unsupported', reason });\n}\n\nfunction getMemberExpressionRoot(node: Expression | Super): Identifier | undefined {\n if (node.type === 'Identifier') {\n return node;\n }\n if (node.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\nfunction getModuleExportName(node: ModuleExportName): string {\n if (node.type === 'Identifier') {\n return node.name;\n }\n return String(node.value);\n}\n\nfunction getExportAllExportedName(node: ExportAllDeclaration): string | undefined {\n const exported = (node as ExportAllDeclaration & { exported?: ModuleExportName | null })\n .exported;\n return exported ? getModuleExportName(exported) : undefined;\n}\n\nfunction getResolvedSource(staticDependencies: StaticModuleDependency[], source: string): string {\n return (\n staticDependencies.find((dependency) => dependency.source === source)?.resolvedId ?? source\n );\n}\n\n/**\n * Finds dependency forms that cannot be represented by the static dependency\n * IDs supplied by the backend build collector.\n */\nfunction collectUnsupportedModuleDependencies(ast: Program): ModuleDependency[] {\n const dependencies: ModuleDependency[] = [];\n\n walkAst(ast, dependencies, {\n ImportExpression(node, { state }) {\n const specifier = getImportExpressionSpecifier(node);\n if (shouldFailDynamicImport(specifier)) {\n state.push({ specifier, kind: 'dynamic-import' });\n }\n },\n CallExpression(node, { state }) {\n if (isImportCallExpression(node)) {\n const specifier = getImportCallSpecifier(node);\n if (shouldFailDynamicImport(specifier)) {\n state.push({ specifier, kind: 'dynamic-import' });\n }\n return;\n }\n\n if (isLocalRequireCall(node)) {\n state.push({\n specifier: getRequireSpecifier(node),\n kind: 'require',\n });\n }\n },\n });\n\n return dependencies;\n}\n\n/**\n * Dynamic package imports are skipped, but local or non-literal dynamic imports\n * could hide app-local action-catalog calls and must fail closed.\n */\nfunction shouldFailDynamicImport(specifier: string): boolean {\n return specifier === 'non-literal dynamic import' || isLocalSpecifier(specifier);\n}\n\n/**\n * Keeps reachability traversal scoped to app-local JavaScript/TypeScript source\n * modules that the backend build collector can safely analyze.\n */\nexport function shouldTraverseCollectedModule(moduleId: string, buildRoot: string): boolean {\n if (!BACKEND_CODE_EXTENSIONS.some((extension) => moduleId.endsWith(extension))) {\n return false;\n }\n\n const relativePath = path.relative(path.resolve(buildRoot), moduleId);\n if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n return false;\n }\n\n return !relativePath.split(path.sep).some((segment) => PACKAGE_MANAGER_DIRS.has(segment));\n}\n\n/**\n * Reads the static string specifier from an ESTree dynamic import expression.\n */\nfunction getImportExpressionSpecifier(node: ImportExpression): string {\n return getLiteralSpecifier(node.source, 'non-literal dynamic import');\n}\n\n/**\n * Reads the static string specifier from Rollup's call-expression form for\n * dynamic import.\n */\nfunction getImportCallSpecifier(node: ImportCallExpression): string {\n return getLiteralSpecifier(node.arguments[0], 'non-literal dynamic import');\n}\n\n/**\n * Reads the static string specifier from a CommonJS require call.\n */\nfunction getRequireSpecifier(node: SimpleCallExpression): string {\n return getLiteralSpecifier(node.arguments[0], 'local require');\n}\n\n/**\n * Returns a literal string value when available, otherwise a diagnostic label\n * used in fail-closed error messages.\n */\nfunction getLiteralSpecifier(node: unknown, fallback: string): string {\n if (isStringLiteral(node)) {\n return node.value;\n }\n return fallback;\n}\n\n/**\n * Narrows Rollup's dynamic import call-expression representation.\n */\nfunction isImportCallExpression(node: SimpleCallExpression): node is ImportCallExpression {\n return (node.callee as { type: string }).type === 'Import';\n}\n\n/**\n * Detects local CommonJS require calls. Package require calls are ignored\n * because package modules are outside the app-local backend graph.\n */\nfunction isLocalRequireCall(node: SimpleCallExpression): boolean {\n if (node.callee.type !== 'Identifier' || node.callee.name !== 'require') {\n return false;\n }\n const [source] = node.arguments;\n return !source || !isStringLiteral(source) || isLocalSpecifier(source.value);\n}\n\n/**\n * Returns whether an import specifier points at an app-local path.\n */\nfunction isLocalSpecifier(specifier: string): boolean {\n return specifier.startsWith('.') || specifier.startsWith('/');\n}\n\n/**\n * Builds the common fail-closed error for graph shapes that could hide an\n * action-catalog connection ID.\n */\nexport function unsupportedModuleGraphDependency(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported local module graph for ${filePath}: ${unsupported} could hide an action-catalog connectionId.`,\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 { Expression, ObjectExpression, Property, SimpleCallExpression } from 'estree';\n\nimport {\n analyzeActionCatalogScopes,\n findActionCatalogCallSites,\n} from './action-catalog-call-sites';\nimport { collectActionCatalogImports } from './action-catalog-imports';\nimport type { ParsedModuleRecord } from './module-graph';\nimport { resolveStaticStringValue } from './static-string-resolution';\nimport { walkModuleGraph } from './walk-module-graph';\n\nconst CONNECTION_ID_PROPERTY = 'connectionId';\n\ntype ConnectionIdProperty = Property & { value: Expression };\n\n/**\n * Extracts the conservative backend-file connection ID union from module records\n * collected while the backend bundler walked the real execution graph.\n */\nexport function extractConnectionIdsFromModuleGraph(\n entryId: string,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n buildRoot: string,\n): string[] {\n const connectionIds = new Set<string>();\n\n // Walk the already-parsed records from this backend entry's build. The\n // extraction cost is linear in reachable app-local modules, without\n // reparsing source files here.\n walkModuleGraph(entryId, modules, buildRoot, ({ record }) => {\n const imports = collectActionCatalogImports(record.ast);\n const scopeAnalysis = analyzeActionCatalogScopes(record.scopeAnalysis, imports);\n\n for (const callSite of findActionCatalogCallSites(record.ast, scopeAnalysis, record.id)) {\n const connectionId = extractConnectionIdFromActionCall(callSite, modules, record);\n if (connectionId) {\n connectionIds.add(connectionId);\n }\n }\n });\n\n return [...connectionIds].sort();\n}\n\nfunction extractConnectionIdFromActionCall(\n node: SimpleCallExpression,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n record: ParsedModuleRecord,\n): string | undefined {\n const [firstArg] = node.arguments;\n if (!firstArg || firstArg.type !== 'ObjectExpression') {\n throw unsupportedActionCatalogCall(record.id, 'non-object action-catalog call arguments');\n }\n\n const connectionIdProperty = findConnectionIdProperty(firstArg, record.id);\n if (!connectionIdProperty) {\n return undefined;\n }\n\n const result = resolveStaticStringValue(modules, record.id, connectionIdProperty.value);\n if (result.kind === 'resolved') {\n return result.value;\n }\n\n throw unsupportedConnectionId(\n record.id,\n `static string resolution ${getStaticStringUnsupportedReason(result)}: ${result.message}`,\n );\n}\n\nfunction getStaticStringUnsupportedReason(\n result: Exclude<ReturnType<typeof resolveStaticStringValue>, { kind: 'resolved' }>,\n): string {\n if (result.reason === 'static-definition-unsupported') {\n return `${result.reason}/${result.definition.reason}`;\n }\n\n return result.reason;\n}\n\n/**\n * Finds the `connectionId` property in an action-catalog call's options object.\n *\n * This rejects spreads, computed keys, duplicate `connectionId` keys, and\n * accessor properties because those shapes can hide or change the actual value.\n */\nfunction findConnectionIdProperty(\n objectExpression: ObjectExpression,\n filePath: string,\n): ConnectionIdProperty | undefined {\n let connectionIdProperty: ConnectionIdProperty | undefined;\n for (const property of objectExpression.properties) {\n if (property.type === 'SpreadElement') {\n throw unsupportedActionCatalogCall(filePath, 'spread object arguments');\n }\n if (property.computed) {\n throw unsupportedActionCatalogCall(filePath, 'computed object property keys');\n }\n if (isConnectionIdKey(property)) {\n if (connectionIdProperty) {\n throw unsupportedActionCatalogCall(filePath, 'multiple connectionId properties');\n }\n if (property.kind !== 'init') {\n throw unsupportedActionCatalogCall(filePath, 'accessor connectionId properties');\n }\n if (!hasExpressionValue(property)) {\n throw unsupportedActionCatalogCall(\n filePath,\n 'destructuring pattern in connectionId value',\n );\n }\n connectionIdProperty = property;\n }\n }\n return connectionIdProperty;\n}\n\nfunction hasExpressionValue(property: Property): property is ConnectionIdProperty {\n const { value } = property;\n return (\n value.type !== 'ObjectPattern' &&\n value.type !== 'ArrayPattern' &&\n value.type !== 'RestElement' &&\n value.type !== 'AssignmentPattern'\n );\n}\n\nfunction isConnectionIdKey(property: Property): boolean {\n return getStaticPropertyKey(property) === CONNECTION_ID_PROPERTY;\n}\n\nfunction getStaticPropertyKey(property: Property): string | undefined {\n if (property.key.type === 'Identifier') {\n return property.key.name;\n }\n if (property.key.type === 'Literal' && typeof property.key.value === 'string') {\n return property.key.value;\n }\n return undefined;\n}\n\nfunction unsupportedActionCatalogCall(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported action-catalog call in ${filePath}: ${unsupported} could hide a connectionId.`,\n );\n}\n\nfunction unsupportedConnectionId(filePath: string, unsupported: string): Error {\n return new Error(`Unsupported action-catalog connectionId in ${filePath}: ${unsupported}.`);\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 type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n unsupportedModuleGraphDependency,\n} from './module-graph';\n\nexport interface ModuleGraphWalkContext {\n entryId: string;\n moduleId: string;\n record: ParsedModuleRecord;\n}\n\n/**\n * Walks every collected app-local module statically reachable from a backend\n * entry and applies fail-closed graph validation before following dependency\n * edges.\n */\nexport function walkModuleGraph(\n entryId: string,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n buildRoot: string,\n visit: (context: ModuleGraphWalkContext) => void,\n): void {\n // Traverse from the real backend entry, not the virtual wrapper used by\n // the backend build. Every backend export in this file receives this same\n // conservative file-level allowlist.\n const pending = [entryId];\n const visited = new Set<string>();\n\n while (pending.length > 0) {\n // Process each collected module at most once so local cycles cannot\n // loop forever.\n const moduleId = pending.shift()!;\n if (visited.has(moduleId)) {\n continue;\n }\n visited.add(moduleId);\n\n // A reachable local module that Rollup did not parse means the\n // collected graph is incomplete, so fail closed instead of silently\n // omitting a possible connection ID.\n const record = modules.get(moduleId);\n if (!record) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `missing module record for ${moduleId}`,\n );\n }\n\n visit({ entryId, moduleId, record });\n\n // Dynamic local imports and local require calls can hide reachable\n // action-catalog calls from static traversal. Treat them as unsupported\n // graph shapes for this PR.\n for (const dependency of record.unsupportedDependencies) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `${dependency.kind} ${dependency.specifier}`,\n );\n }\n\n // Follow only collected local source modules. Package imports, virtual\n // entries, generated files, and files outside buildRoot are ignored by\n // design because they are outside the app-local backend graph.\n for (const dependency of record.staticDependencies) {\n const dependencyId = dependency.resolvedId;\n if (!shouldTraverseCollectedModule(dependencyId, buildRoot)) {\n continue;\n }\n\n // A local dependency can be statically reachable but absent from\n // the collector if Rollup did not parse it. Fail closed rather than\n // trusting an incomplete allowlist.\n if (!modules.has(dependencyId)) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `uncollected local import ${dependencyId} from ${record.id}`,\n );\n }\n\n pending.push(dependencyId);\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 { ModuleInfo } from 'rollup';\nimport type { Plugin } from 'vite';\n\nimport {\n createParsedModuleRecord,\n type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n unsupportedModuleGraphDependency,\n} from '../backend/ast-parsing/module-graph';\n\nconst VIRTUAL_MODULE_ID_RE = /^(?:\\0|virtual:)/;\n\nexport interface BackendModuleGraphCollector {\n plugin: Plugin;\n getModuleRecords: () => ReadonlyMap<string, ParsedModuleRecord>;\n}\n\nexport function createBackendModuleGraphCollector(buildRoot: string): BackendModuleGraphCollector {\n const records = new Map<string, ParsedModuleRecord>();\n\n return {\n plugin: {\n name: 'dd-backend-module-graph-collector',\n moduleParsed(moduleInfo: ModuleInfo) {\n const moduleId = normalizeViteModuleId(moduleInfo.id);\n if (isViteVirtualModuleId(moduleId)) {\n return;\n }\n\n // `createParsedModuleRecord` applies this same predicate, but\n // only after the AST exists. Checking it here keeps us from\n // parsing every `node_modules` module just to discard it.\n if (!shouldTraverseCollectedModule(moduleId, buildRoot)) {\n return;\n }\n\n // External and synthetic modules have no source to parse.\n if (typeof moduleInfo.code !== 'string') {\n return;\n }\n\n // Parse the source instead of reading `moduleInfo.ast`: Rolldown,\n // the bundler Vite 8 uses by default, stubs that getter to throw\n // `UNSUPPORTED: ModuleInfo#ast`.\n //\n // No TypeScript-capable parser is needed because `moduleParsed`\n // runs after `transform`, so types and JSX are already compiled\n // away. Note that `this.parse` is the bundler's parser but not\n // its parser *configuration* — Rollup binds no options to it,\n // while its own module parse passes `{ jsx }`. Our nested build\n // never enables `jsx`, so the two agree today; fail closed rather\n // than silently if they ever diverge, since a module we cannot\n // parse may hide a connection ID.\n let parsed;\n try {\n parsed = this.parse(moduleInfo.code);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw unsupportedModuleGraphDependency(\n moduleId,\n `unparseable module source (${reason})`,\n );\n }\n\n const record = createParsedModuleRecord(\n moduleId,\n buildRoot,\n parsed,\n getStaticDependencyIds(moduleInfo).map(normalizeViteModuleId),\n );\n // Only null when the traversal predicate rejects, which the guard\n // above already covered; kept to narrow the nullable return type.\n if (!record) {\n return;\n }\n\n records.set(record.id, record);\n },\n },\n getModuleRecords() {\n return records;\n },\n };\n}\n\nfunction normalizeViteModuleId(id: string): string {\n return id.split('?')[0];\n}\n\nfunction getStaticDependencyIds(moduleInfo: ModuleInfo): string[] {\n return moduleInfo.importedIdResolutions?.map(({ id }) => id) ?? [...moduleInfo.importedIds];\n}\n\nfunction isViteVirtualModuleId(id: string): boolean {\n return VIRTUAL_MODULE_ID_RE.test(id);\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 { Plugin } from 'vite';\n\nimport { extractConnectionIdsFromModuleGraph } from '../backend/ast-parsing/extract-connection-ids-from-module-graph';\n\nimport { createBackendModuleGraphCollector } from './backend-module-graph-collector';\n\nexport interface BackendConnectionIdCollector {\n plugin: Plugin;\n getAllowedConnectionIds: () => string[];\n}\n\nexport function createBackendConnectionIdCollector(\n entryId: string,\n buildRoot: string,\n): BackendConnectionIdCollector {\n const moduleGraphCollector = createBackendModuleGraphCollector(buildRoot);\n\n return {\n plugin: moduleGraphCollector.plugin,\n getAllowedConnectionIds() {\n return extractConnectionIdsFromModuleGraph(\n entryId,\n moduleGraphCollector.getModuleRecords(),\n buildRoot,\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 { BuildOptions, InlineConfig, Plugin } from 'vite';\n\nimport { BACKEND_CODE_EXTENSIONS } from '../constants';\n\n/**\n * Create the virtual module resolver plugin used by both production and dev builds.\n * Maps virtual IDs to their generated source content.\n */\nexport function createVirtualPlugin(name: string, virtualEntries: Record<string, string>): Plugin {\n return {\n name,\n enforce: 'pre',\n resolveId(id: string) {\n if (virtualEntries[id]) {\n return { id, moduleSideEffects: true };\n }\n return null;\n },\n load(id: string) {\n if (virtualEntries[id]) {\n return virtualEntries[id];\n }\n return null;\n },\n };\n}\n\n/**\n * Shared Vite/Rollup config for building backend functions.\n * Both the production build (write to disk) and dev build (in-memory)\n * use this as a base, overriding only what differs.\n */\nexport function getBaseBackendBuildConfig(\n root: string,\n virtualEntries: Record<string, string>,\n plugins: Plugin[] = [],\n): InlineConfig & {\n build: BuildOptions & { rollupOptions: NonNullable<BuildOptions['rollupOptions']> };\n} {\n return {\n configFile: false,\n root,\n logLevel: 'silent',\n build: {\n minify: false,\n target: 'esnext',\n rollupOptions: {\n output: { format: 'es', exports: 'named', inlineDynamicImports: true },\n preserveEntrySignatures: 'exports-only',\n treeshake: false,\n onwarn(warning, defaultHandler) {\n if (warning.code === 'MODULE_LEVEL_DIRECTIVE') {\n return;\n }\n defaultHandler(warning);\n },\n },\n },\n resolve: {\n extensions: [...BACKEND_CODE_EXTENSIONS, '.json'],\n },\n plugins: [createVirtualPlugin('dd-backend-resolve', virtualEntries), ...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/* eslint-disable no-await-in-loop */\n\nimport type { AuthOptionsWithDefaults, Logger } from '@dd/core/types';\nimport { randomUUID } from 'crypto';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { build } from 'vite';\n\nimport { AUTH_GUIDANCE } from '../auth';\nimport type { DoAuthenticatedRequest } from '../auth';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { ExecuteActionRequest, ExecuteActionResponse } from '../backend/protocol';\nimport type { BackendFunction } from '../backend/types';\nimport { generateDevVirtualEntryContent } from '../backend/virtual-entry';\n\nimport { createBackendConnectionIdCollector } from './backend-connection-id-collector';\nimport { getBaseBackendBuildConfig } from './build-config';\n\ninterface BundleResult {\n func: BackendFunction;\n code: string;\n}\n\ntype BundleFn = (func: BackendFunction) => Promise<BundleResult>;\n\nconst DEV_VIRTUAL_PREFIX = 'virtual:dd-backend-dev:';\n\ntype AuthConfig = AuthOptionsWithDefaults;\n\n/** Shape of the `outputs` field in a Datadog app-builder query response —\n * the API wraps a JS action's return value as `{ data: <value> }`.\n */\ntype BackendOutputs = { data: unknown };\n\n/**\n * Format a BackendFunction for display in log/error messages.\n */\nfunction formatRef(func: BackendFunction): string {\n return `${func.relativePath}/${func.name}`;\n}\n\n/**\n * Parse JSON body from an incoming request stream.\n */\nfunction parseRequestBody(req: IncomingMessage): Promise<ExecuteActionRequest> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n try {\n resolve(JSON.parse(body));\n } catch {\n reject(new Error('Invalid JSON body'));\n }\n });\n req.on('error', reject);\n });\n}\n\n/**\n * Bundle a backend function using Vite's build API (Rollup under the hood).\n * Uses write: false to produce an in-memory bundle with no temp files.\n */\nasync function bundleBackendFunction(\n viteBuild: typeof build,\n func: BackendFunction,\n projectRoot: string,\n log: Logger,\n): Promise<BundleResult> {\n const displayName = formatRef(func);\n const virtualId = `${DEV_VIRTUAL_PREFIX}${displayName}`;\n const virtualContent = generateDevVirtualEntryContent(\n func.name,\n func.absolutePath,\n projectRoot,\n );\n const connectionIdCollector = createBackendConnectionIdCollector(\n func.absolutePath,\n projectRoot,\n );\n\n log.debug(`Bundling backend function \"${displayName}\" from ${func.absolutePath}`);\n\n const baseConfig = getBaseBackendBuildConfig(projectRoot, { [virtualId]: virtualContent }, [\n connectionIdCollector.plugin,\n ]);\n\n // Dev: build a single function in-memory per request so we can send the\n // bundled script to the Datadog API without writing temp files.\n // Uses a plain \"virtual:\" prefix instead of \\0 because Rollup generates\n // empty chunks when \\0-prefixed IDs are used as input entries.\n const result = await viteBuild({\n ...baseConfig,\n build: {\n ...baseConfig.build,\n write: false,\n rollupOptions: {\n ...baseConfig.build.rollupOptions,\n input: virtualId,\n output: baseConfig.build.rollupOptions.output,\n },\n },\n });\n\n const output = Array.isArray(result) ? result[0] : result;\n\n if (!('output' in output)) {\n throw new Error(`Unexpected vite.build result for \"${displayName}\"`);\n }\n\n const code = output.output[0].type === 'chunk' ? output.output[0].code : '';\n const enrichedFunc = {\n ...func,\n allowedConnectionIds: connectionIdCollector.getAllowedConnectionIds(),\n };\n\n log.debug(`Bundled \"${displayName}\" (${code.length} bytes)`);\n\n return { func: enrichedFunc, code };\n}\n\n/**\n * Execute a script via Datadog's app-builder queries API.\n */\nasync function executeScriptViaDatadog(\n scriptBody: string,\n func: BackendFunction,\n args: unknown[],\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n log: Logger,\n): Promise<BackendOutputs> {\n const endpoint = `https://api.${auth.site}/api/v2/app-builder/queries/preview-async`;\n const displayName = formatRef(func);\n\n log.debug(`Calling Datadog API: ${endpoint}`);\n\n const body = JSON.stringify({\n data: {\n type: 'queries',\n attributes: {\n query: {\n id: randomUUID(),\n name: displayName,\n type: 'action',\n properties: {\n spec: {\n fqn: 'com.datadoghq.datatransformation.jsFunctionWithActions',\n inputs: {\n script: scriptBody,\n allowedConnectionIds: func.allowedConnectionIds,\n context: { backendFunctionArgs: args },\n },\n },\n onlyTriggerManually: true,\n },\n },\n template_params: {},\n },\n },\n });\n\n const initialResult = await doAuthenticatedRequest<{ data?: { id?: string } }>({\n url: endpoint,\n method: 'POST',\n type: 'json',\n getData: () => ({\n data: body,\n headers: { 'Content-Type': 'application/json' },\n }),\n });\n\n const receiptId = initialResult.data?.id;\n\n if (!receiptId) {\n throw new Error('No receipt ID returned from Datadog API');\n }\n\n log.debug(`Query execution started with receipt: ${receiptId}`);\n\n return pollQueryExecution(receiptId, auth, doAuthenticatedRequest, log);\n}\n\ninterface PollResult {\n data?: { attributes?: { done?: boolean; outputs?: BackendOutputs } };\n errors?: Array<{ detail?: string; title?: string }>;\n}\n\nasync function pollQueryExecution(\n receiptId: string,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n log: Logger,\n): Promise<BackendOutputs> {\n const endpoint = `https://api.${auth.site}/api/v2/app-builder/queries/execution-long-polling/${receiptId}`;\n const maxRetries = 10;\n\n /*\n * Long-poll Datadog API until the query execution completes or times out.\n *\n * Executing an action works in two phases:\n * 1. executeScriptViaDatadog sends a POST to preview-async, which starts the\n * query and returns a receipt ID immediately.\n * 2. This function polls the execution-long-polling endpoint with that receipt ID.\n * The server holds the connection open (~30s) and responds with done: true when\n * the result is ready, or done: false when its long-poll window expires.\n *\n * This loop handles application-level re-polling (done: false), not HTTP retries.\n * doRequest already retries transient HTTP failures (5xx, network errors) internally.\n */\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n log.debug(`Long-poll attempt ${attempt + 1}/${maxRetries}...`);\n\n const result = await doAuthenticatedRequest<PollResult>({\n url: endpoint,\n type: 'json',\n });\n\n // Check for error responses.\n if (result.errors?.length) {\n const details = result.errors.map((e) => e.detail || e.title).join('; ');\n throw new Error(`Query execution failed: ${details}`);\n }\n\n const attrs = result.data?.attributes;\n log.debug(`Long-poll response, done: ${attrs?.done}`);\n\n if (attrs?.done) {\n if (!attrs.outputs) {\n throw new Error('Query execution completed without outputs');\n }\n return attrs.outputs;\n }\n\n // done === false means server-side long-poll timed out; retry immediately.\n }\n\n throw new Error('Query execution timed out');\n}\n\n/**\n * Send a JSON error response.\n */\nfunction sendError(res: ServerResponse, statusCode: number, message: string): void {\n res.statusCode = statusCode;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ success: false, error: message } satisfies ExecuteActionResponse));\n}\n\nclass HttpError extends Error {\n constructor(\n public statusCode: number,\n message: string,\n ) {\n super(message);\n }\n}\n\n/**\n * Shared request pipeline: parse body, validate functionName, look up\n * the backend function by encoded query name, and bundle it.\n */\nasync function validateAndBundle(\n req: IncomingMessage,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n): Promise<{ func: BackendFunction; code: string; args: unknown[] }> {\n const { functionName, args = [] } = await parseRequestBody(req);\n\n if (!functionName || typeof functionName !== 'string') {\n throw new HttpError(400, 'Missing or invalid functionName');\n }\n\n const func = functionsByName.get(functionName);\n if (!func) {\n throw new HttpError(404, `Backend function \"${functionName}\" not found`);\n }\n\n const bundled = await bundle(func);\n return { ...bundled, args };\n}\n\n/**\n * Handle POST /__dd/debugBundle — returns the bundled script for inspection.\n */\nasync function handleDebugBundle(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n): Promise<void> {\n try {\n const { code } = await validateAndBundle(req, functionsByName, bundle);\n\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/plain');\n res.end(code);\n } catch (error: unknown) {\n const statusCode = error instanceof HttpError ? error.statusCode : 500;\n const message = error instanceof Error ? error.message : 'Internal server error';\n sendError(res, statusCode, message);\n }\n}\n\n/**\n * Handle POST /__dd/executeAction — bundles a backend function and executes it via Datadog API.\n */\nasync function handleExecuteAction(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n log: Logger,\n): Promise<void> {\n try {\n const { func, code, args } = await validateAndBundle(req, functionsByName, bundle);\n const displayName = formatRef(func);\n\n log.debug(`Executing action: ${displayName} with args`);\n\n const result = await executeScriptViaDatadog(\n code,\n func,\n args,\n auth,\n doAuthenticatedRequest,\n log,\n );\n\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ success: true, result } satisfies ExecuteActionResponse));\n } catch (error: unknown) {\n const statusCode = error instanceof HttpError ? error.statusCode : 500;\n const message = error instanceof Error ? error.message : 'Internal server error';\n log.debug(`Error handling executeAction: ${message}`);\n sendError(res, statusCode, message);\n }\n}\n\n/**\n * Build a lookup map from encoded query names to BackendFunction objects.\n */\nfunction buildFunctionMap(backendFunctions: BackendFunction[]): Map<string, BackendFunction> {\n return new Map(backendFunctions.map((f) => [encodeQueryName(f), f]));\n}\n\n/**\n * Create a Connect-compatible middleware for the Vite dev server.\n * Intercepts backend function requests and handles them via Datadog API.\n *\n * The lookup map is rebuilt on each request via `getBackendFunctions()`\n * so that newly discovered (or renamed/removed) functions are reflected\n * without restarting the dev server.\n */\nexport function createDevServerMiddleware(\n viteBuild: typeof build,\n getBackendFunctions: () => BackendFunction[],\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest | undefined,\n projectRoot: string,\n log: Logger,\n): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {\n const bundle = (func: BackendFunction) =>\n bundleBackendFunction(viteBuild, func, projectRoot, log);\n\n const initialFunctions = getBackendFunctions();\n if (initialFunctions.length > 0) {\n log.info(\n `Dev server middleware active for ${initialFunctions.length} backend function(s): ${initialFunctions.map((f) => f.name).join(', ')}`,\n );\n }\n\n if (!doAuthenticatedRequest) {\n log.warn(\n `Auth credentials not configured. The /__dd/executeAction endpoint will be unavailable. ${AUTH_GUIDANCE}`,\n );\n }\n\n return (req: IncomingMessage, res: ServerResponse, next: () => void) => {\n if (req.method !== 'POST') {\n next();\n return;\n }\n\n const functionsByName = buildFunctionMap(getBackendFunctions());\n\n if (req.url === '/__dd/debugBundle') {\n handleDebugBundle(req, res, functionsByName, bundle).catch(() => {\n sendError(res, 500, 'Unexpected error');\n });\n } else if (req.url === '/__dd/executeAction') {\n if (!doAuthenticatedRequest) {\n sendError(res, 400, `Auth credentials not configured. ${AUTH_GUIDANCE}`);\n return;\n }\n handleExecuteAction(\n req,\n res,\n functionsByName,\n bundle,\n auth,\n doAuthenticatedRequest,\n log,\n ).catch(() => {\n sendError(res, 500, 'Unexpected error');\n });\n } else {\n next();\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 fsp from 'fs/promises';\nimport fs from 'fs';\nimport JSZip from 'jszip';\nimport os from 'os';\nimport path from 'path';\n\nimport type { Asset } from './assets';\nimport { ARCHIVE_FILENAME } from './constants';\n\nexport type Archive = {\n archivePath: string;\n size: number;\n assets: Asset[];\n};\n\nexport const createArchive = async (assets: Asset[]): Promise<Archive> => {\n const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'dd-apps-'));\n const archivePath = path.join(tempDir, ARCHIVE_FILENAME);\n\n const zip = new JSZip();\n for (const asset of assets) {\n zip.file(asset.relativePath, fs.createReadStream(asset.absolutePath), {\n binary: true,\n compression: 'DEFLATE',\n compressionOptions: { level: 9 },\n });\n }\n\n await new Promise<void>((resolve, reject) => {\n const output = fs.createWriteStream(archivePath);\n const stream = zip.generateNodeStream({\n type: 'nodebuffer',\n streamFiles: true,\n compression: 'DEFLATE',\n compressionOptions: { level: 9 },\n });\n stream.on('error', reject);\n output.on('error', reject);\n output.on('close', resolve);\n stream.pipe(output);\n });\n\n // Compute the size for logging purpose.\n const { size } = await fsp.stat(archivePath);\n\n return {\n archivePath,\n size,\n assets,\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 { glob } from 'glob';\nimport path from 'path';\n\nexport type Asset = {\n absolutePath: string;\n relativePath: string;\n};\n\n/**\n * Finds the common directory prefix across all paths.\n * Returns the longest common directory path that all paths share.\n * @param paths - Array of relative paths\n * @returns Common directory prefix (without trailing separator), or empty string if no common prefix\n */\nexport const findCommonPrefix = (paths: string[]): string => {\n if (paths.length === 0) {\n return '';\n }\n\n const segments = paths[0].split(path.sep);\n let commonPrefix = '';\n\n for (let i = 0; i < segments.length - 1; i++) {\n const prefix = segments.slice(0, i + 1).join(path.sep);\n const allMatch = paths.every((p) => p.startsWith(`${prefix}${path.sep}`));\n if (allMatch) {\n commonPrefix = prefix;\n } else {\n break;\n }\n }\n\n return commonPrefix;\n};\n\nexport const collectAssets = async (patterns: string[], cwd: string): Promise<Asset[]> => {\n const matches = (\n await Promise.all(\n patterns.map((pattern) => {\n return glob(pattern, { absolute: true, cwd, nodir: true });\n }),\n )\n ).flat();\n\n // Compute relative paths from cwd\n const relativePaths = Array.from(new Set(matches)).map((match) => path.relative(cwd, match));\n\n // Find common directory prefix across all paths\n const commonPrefix = findCommonPrefix(relativePaths);\n\n const assets: Asset[] = relativePaths.map((relativePath, index) => {\n // Strip common prefix to get paths relative to the common directory\n const strippedPath = commonPrefix\n ? relativePath.slice(commonPrefix.length + 1)\n : relativePath;\n\n return {\n absolutePath: matches[index],\n // Normalize to forward slashes so archive entries are valid\n // on all platforms (ZIP spec requires POSIX separators).\n relativePath: strippedPath.split(path.sep).join('/'),\n };\n });\n\n return assets;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\nimport { existsSync } from './fs';\n\n// Will only prepend the cwd if not already there.\nexport const getAbsolutePath = (cwd: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath.startsWith(cwd) || path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.resolve(cwd, filepath);\n};\n\n// Find the highest package.json from the current directory.\nexport const getHighestPackageJsonDir = (currentDir: string): string | undefined => {\n let highestPackage;\n let current = getAbsolutePath(process.cwd(), currentDir);\n let currentDepth = current.split(path.sep).length;\n while (currentDepth > 0) {\n const packagePath = path.resolve(current, `package.json`);\n // Check if package.json exists in the current directory.\n if (existsSync(packagePath)) {\n highestPackage = current;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n currentDepth--;\n }\n return highestPackage;\n};\n\nexport const getClosest = (currentDir: string, filename: string) => {\n let closest;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closest) {\n const filepath = path.resolve(current, filename);\n // Check if it exists in the current directory.\n if (existsSync(filepath)) {\n closest = filepath;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n\n // Exit if we reach the root directory.\n if ([path.sep, ''].includes(current)) {\n break;\n }\n }\n return closest;\n};\n\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n return getClosest(currentDir, 'package.json');\n};\n\n// From a list of path, return the nearest common directory.\nexport const getNearestCommonDirectory = (dirs: string[], cwd?: string) => {\n const dirsToCompare = [...dirs];\n\n const splitPaths = dirsToCompare.map((dir) => {\n const absolutePath = getAbsolutePath(cwd || process.cwd(), dir);\n return absolutePath.split(path.sep);\n });\n\n // Use the shortest length for faster results.\n const minLength = splitPaths.length ? Math.min(...splitPaths.map((parts) => parts.length)) : 0;\n const commonParts = [];\n\n for (let i = 0; i < minLength; i++) {\n // We use the first path as our basis.\n const component = splitPaths[0][i];\n if (splitPaths.every((parts) => parts[i] === component)) {\n commonParts.push(component);\n } else {\n break;\n }\n }\n\n return commonParts.length > 0\n ? // Use \"|| path.sep\" to cover for the [''] case.\n commonParts.join(path.sep) || path.sep\n : path.sep;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFileSync } from '@dd/core/helpers/fs';\nimport { getClosestPackageJson } from '@dd/core/helpers/paths';\nimport { filterSensitiveInfoFromRepositoryUrl } from '@dd/core/helpers/strings';\nimport type { Logger } from '@dd/core/types';\nimport chalk from 'chalk';\nimport { createHash } from 'crypto';\n\nconst red = chalk.bold.red;\nconst yellow = chalk.bold.yellow;\n\ntype PkgJson = {\n name?: string;\n repository?:\n | string\n | {\n type: string;\n url: string;\n };\n};\n\nexport const getPackageJson = (buildRoot: string): PkgJson | undefined => {\n const packageJsonPath = getClosestPackageJson(buildRoot);\n if (!packageJsonPath) {\n return undefined;\n }\n try {\n const packageJson = readFileSync(packageJsonPath);\n return JSON.parse(packageJson);\n } catch (e) {\n // Let the caller handle the warnings.\n return undefined;\n }\n};\n\nexport const getRepositoryUrlFromPkg = (pkg?: PkgJson): string | undefined => {\n if (!pkg || !pkg.repository) {\n return undefined;\n }\n\n if (typeof pkg.repository === 'string') {\n return pkg.repository;\n }\n\n if ('url' in pkg.repository) {\n return pkg.repository.url;\n }\n\n return undefined;\n};\n\nexport const resolveRepositoryUrl = (\n inputRepositoryUrl?: string,\n pkg?: PkgJson,\n): string | undefined => {\n const repositoryUrl = inputRepositoryUrl || getRepositoryUrlFromPkg(pkg);\n if (!repositoryUrl) {\n return undefined;\n }\n\n const sanitizedUrl = filterSensitiveInfoFromRepositoryUrl(repositoryUrl.trim());\n if (!sanitizedUrl) {\n return undefined;\n }\n\n return sanitizedUrl.replace(/\\.git$/, '');\n};\n\nexport const buildIdentifier = (repository?: string, name?: string): string | undefined => {\n // Both repository and name are mandatory for building the identifier\n if (!repository || !name) {\n return undefined;\n }\n\n const plainIdentifier = `${repository}:${name}`;\n // SHA-256 truncated to 128 bits (32 hex characters) for a compact identifier.\n return createHash('sha256').update(plainIdentifier).digest('hex').slice(0, 32);\n};\n\nexport const resolveIdentifier = (\n buildRoot: string,\n log: Logger,\n input?: {\n url?: string;\n name?: string;\n identifier?: string;\n },\n): { identifier?: string; name?: string } => {\n if (input?.name && input?.identifier) {\n return { identifier: input?.identifier, name: input.name };\n }\n\n const pkg = getPackageJson(buildRoot);\n if (!pkg) {\n log.warn(yellow('No package.json found to infer the app name.'));\n }\n\n const name = input?.name || pkg?.name?.trim();\n if (!name) {\n log.error(red('Unable to determine the app name to compute the app identifier.'));\n }\n\n const repository = resolveRepositoryUrl(input?.url, pkg);\n if (!repository) {\n log.error(red('Unable to determine the git remote to compute the app identifier.'));\n }\n\n const identifier = input?.identifier || buildIdentifier(repository, name);\n if (!identifier || !name) {\n log.error(red('Unable to compute the app identifier.'));\n }\n\n return { identifier, name };\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 { getDDEnvValue, parseBoolEnv } from '@dd/core/helpers/env';\nimport { getFile } from '@dd/core/helpers/fs';\nimport { createRequestData, getOriginHeaders, NB_RETRIES } from '@dd/core/helpers/request';\nimport { prettyObject } from '@dd/core/helpers/strings';\nimport type { Logger } from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\nimport { Readable } from 'stream';\n\nimport type { Archive } from './archive';\nimport type { DoAuthenticatedRequest } from './auth';\nimport { APPS_API_PATH, ARCHIVE_FILENAME } from './constants';\n\ntype DataResponse = Awaited<ReturnType<typeof createRequestData>>;\n\n// Only the fields this file actually reads. app_builder_url is deliberately optional on both:\n// see resolveAppBuilderUrl for what happens when the backend can't resolve it.\ntype UploadApiResponse = {\n app_builder_id?: string;\n app_builder_url?: string;\n version_id?: string;\n};\n\ntype ReleaseApiResponse = {\n app_builder_id?: string;\n app_builder_url?: string;\n};\n\nexport type UploadContext = {\n bundlerName: string;\n doAuthenticatedRequest: DoAuthenticatedRequest;\n dryRun: boolean;\n identifier: string;\n name: string;\n site: string;\n siteSubdomain?: string;\n version: string;\n};\n\nconst green = chalk.green.bold;\nconst yellow = chalk.yellow.bold;\nconst cyan = chalk.cyan.bold;\nconst bold = chalk.bold;\n\nexport const getIntakeUrl = (site: string, appId: string) => {\n const envIntake = getDDEnvValue('APPS_INTAKE_URL');\n return envIntake || `https://api.${site}/${APPS_API_PATH}/${appId}/upload`;\n};\n\nexport const getReleaseUrl = (site: string, appId: string) => {\n return `https://api.${site}/${APPS_API_PATH}/${appId}/release/live`;\n};\n\n// The backend-provided app_builder_url is authoritative and always wins, even over our own\n// subdomain config, since it reflects whatever the backend actually resolved for this org.\n// Only when the backend can't resolve one do we build our own from site + subdomain (falling\n// back to the generic \"app\" host) and the app_builder_id — this can only ever be a guess at\n// the backend's URL scheme, so it's a fallback, not a replacement for the backend's own value.\nconst resolveAppBuilderUrl = (\n action: 'upload' | 'release',\n site: string,\n subdomain: string | undefined,\n appBuilderUrl: string | undefined,\n appBuilderId: string | undefined,\n): string | undefined => {\n if (appBuilderUrl) {\n return appBuilderUrl;\n }\n\n if (!appBuilderId) {\n return undefined;\n }\n\n const path =\n action === 'upload'\n ? `/app-builder/apps/edit/${appBuilderId}?viewMode=preview`\n : `/app-builder/apps/${appBuilderId}`;\n return `https://${subdomain ?? 'app'}.${site}${path}`;\n};\n\n// Builds the warning shown when the backend couldn't resolve an org's App Builder URL and we\n// don't even have an app_builder_id to construct a fallback link from. Names the app\n// (context.name — always human-readable, unlike context.identifier's opaque hash) so users can\n// find it in their App Builder apps list.\nconst buildMissingAppUrlWarning = (action: 'upload' | 'release', name: string) => {\n return `Could not resolve the App Builder URL for this ${action} — find \"${name}\" in your App Builder apps list to view it.`;\n};\n\nexport const getData =\n (archivePath: string, defaultHeaders: Record<string, string> = {}, name: string) =>\n async (): Promise<DataResponse> => {\n const archiveFile = await getFile(archivePath, {\n contentType: 'application/zip',\n filename: ARCHIVE_FILENAME,\n });\n\n return createRequestData({\n getForm: () => {\n const form = new FormData();\n form.append('name', name);\n form.append('bundle', archiveFile, ARCHIVE_FILENAME);\n const versionName = getDDEnvValue('APPS_VERSION_NAME')?.trim();\n if (versionName) {\n form.append('version', versionName);\n }\n return form;\n },\n defaultHeaders,\n zip: false,\n });\n };\n\nexport const uploadArchive = async (archive: Archive, context: UploadContext, log: Logger) => {\n const errors: Error[] = [];\n const warnings: string[] = [];\n const doAuthenticatedRequest = context.doAuthenticatedRequest;\n\n if (!context.identifier) {\n errors.push(new Error('No app identifier provided'));\n return { errors, warnings };\n }\n\n const intakeUrl = getIntakeUrl(context.site, context.identifier);\n const defaultHeaders = getOriginHeaders({\n bundler: context.bundlerName,\n plugin: 'apps',\n version: context.version,\n });\n\n const configurationString = prettyObject({\n identifier: context.identifier,\n intakeUrl,\n defaultHeaders: `\\n${JSON.stringify(defaultHeaders, null, 2)}`,\n });\n\n const summary = `an archive of:\n - ${green(archive.assets.length.toString())} files\n - ${green(prettyBytes(archive.size))}\n\nWith the configuration:\\n${configurationString}`;\n\n if (context.dryRun) {\n // Using log.error to ensure it's printed with high priority.\n log.error(\n `\\n${cyan('Dry run enabled')}\\n\nSkipping assets upload.\nWould have uploaded ${summary}`,\n );\n return { errors, warnings };\n }\n\n try {\n const response = await doAuthenticatedRequest<UploadApiResponse>({\n url: intakeUrl,\n method: 'POST',\n type: 'json',\n getData: getData(archive.archivePath, defaultHeaders, context.name),\n onRetry: (error: Error, attempt: number) => {\n const message = `Failed to upload archive (attempt ${yellow(\n `${attempt}/${NB_RETRIES}`,\n )}): ${error.message}`;\n warnings.push(message);\n log.warn(message);\n },\n });\n\n log.debug(`Uploaded ${summary}\\n`);\n\n const appBuilderUrl = resolveAppBuilderUrl(\n 'upload',\n context.site,\n context.siteSubdomain,\n response.app_builder_url,\n response.app_builder_id,\n );\n if (appBuilderUrl) {\n log.info(`Your application is available at:\\n ${cyan(appBuilderUrl)}`);\n } else {\n // The backend couldn't resolve this org's App Builder URL and didn't even return\n // an app_builder_id to build a fallback link from (e.g. a transient lookup\n // failure) — the upload itself still succeeded, so this doesn't fail the build.\n const message = buildMissingAppUrlWarning('upload', context.name);\n warnings.push(message);\n log.warn(message);\n }\n\n const shouldPublish = parseBoolEnv(getDDEnvValue('APPS_PUBLISH'), true);\n\n if (response.version_id && shouldPublish) {\n const releaseUrl = getReleaseUrl(context.site, context.identifier);\n const releaseResponse = await doAuthenticatedRequest<ReleaseApiResponse>({\n url: releaseUrl,\n method: 'PUT',\n type: 'json',\n getData: async () => ({\n data: Readable.from(JSON.stringify({ version_id: response.version_id })),\n headers: {\n 'Content-Type': 'application/json',\n ...defaultHeaders,\n },\n }),\n onRetry: (error: Error, attempt: number) => {\n const message = `Failed to release version (attempt ${yellow(\n `${attempt}/${NB_RETRIES}`,\n )}): ${error.message}`;\n warnings.push(message);\n log.warn(message);\n },\n });\n\n const releaseAppBuilderUrl = resolveAppBuilderUrl(\n 'release',\n context.site,\n context.siteSubdomain,\n releaseResponse.app_builder_url,\n // The release response can omit app_builder_id even though it identifies the\n // same app the upload response already resolved one for.\n releaseResponse.app_builder_id ?? response.app_builder_id,\n );\n if (releaseAppBuilderUrl) {\n log.info(\n `Published uploaded version ${bold(response.version_id)} to live.\\n ${cyan(releaseAppBuilderUrl)}`,\n );\n } else {\n log.info(`Published uploaded version ${bold(response.version_id)} to live.`);\n const message = buildMissingAppUrlWarning('release', context.name);\n warnings.push(message);\n log.warn(message);\n }\n } else if (response.version_id && !shouldPublish) {\n log.info(`Uploaded version ${bold(response.version_id)} as a draft (publish skipped).`);\n }\n } catch (error: unknown) {\n const err = error instanceof Error ? error : new Error(String(error));\n errors.push(err);\n }\n\n return { 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 { rm } from '@dd/core/helpers/fs';\nimport type { GlobalContext } from '@dd/core/types';\nimport chalk from 'chalk';\nimport fsp from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport { createArchive } from '../archive';\nimport type { Asset } from '../assets';\nimport { collectAssets } from '../assets';\nimport type { DoAuthenticatedRequest } from '../auth';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { BackendFunction } from '../backend/types';\nimport { PLUGIN_NAME } from '../constants';\nimport { resolveIdentifier } from '../identifier';\nimport type { AppsManifest, AppsOptionsWithDefaults } from '../types';\nimport { uploadArchive } from '../upload';\n\nconst yellow = chalk.yellow.bold;\nconst red = chalk.red.bold;\nconst MANIFEST_FILE_NAME = 'manifest.json';\n\nexport interface HandleUploadOptions {\n backendOutputs: Map<string, string>;\n backendFunctions: BackendFunction[];\n context: GlobalContext;\n doAuthenticatedRequest: DoAuthenticatedRequest;\n options: AppsOptionsWithDefaults;\n}\n\nfunction buildManifest(\n backendFunctions: BackendFunction[],\n options: AppsOptionsWithDefaults,\n): AppsManifest {\n const functions: AppsManifest['backend']['functions'] = {};\n for (const func of backendFunctions) {\n functions[encodeQueryName(func)] = {\n allowedConnectionIds: [...func.allowedConnectionIds],\n };\n }\n\n const manifest: AppsManifest = { backend: { functions } };\n\n // Include optional app properties when specified — the server ignores absent fields\n // and leaves the existing values unchanged, so omitting them is always safe.\n // Use != null throughout to treat both undefined and null as \"not configured\".\n if (options.description != null) {\n manifest.description = options.description;\n }\n if (options.selfService != null) {\n manifest.selfService = options.selfService;\n }\n // Only include permissions if at least one subfield is non-null — an empty object {}\n // or an object with only null subfields must not appear in the manifest, as the server\n // treats any present key as an explicit update and null subfields are not valid values.\n const protectionLevel = options.permissions?.protectionLevel ?? null;\n const runAs = options.permissions?.runAs ?? null;\n if (protectionLevel != null || runAs != null) {\n manifest.permissions = {\n ...(protectionLevel != null && { protectionLevel }),\n ...(runAs != null && { runAs }),\n };\n }\n\n return manifest;\n}\n\nasync function writeManifestFile(\n backendFunctions: BackendFunction[],\n options: AppsOptionsWithDefaults,\n): Promise<{\n manifestAsset: Asset;\n cleanup: () => Promise<void>;\n}> {\n const manifestDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'dd-apps-manifest-'));\n const manifestPath = path.join(manifestDir, MANIFEST_FILE_NAME);\n try {\n await fsp.writeFile(\n manifestPath,\n JSON.stringify(buildManifest(backendFunctions, options), null, 2),\n );\n } catch (error) {\n await rm(manifestDir);\n throw error;\n }\n return {\n manifestAsset: {\n absolutePath: manifestPath,\n relativePath: MANIFEST_FILE_NAME,\n },\n cleanup: () => rm(manifestDir),\n };\n}\n\nexport const handleUpload = async ({\n backendOutputs,\n backendFunctions,\n context,\n doAuthenticatedRequest,\n options,\n}: HandleUploadOptions) => {\n const log = context.getLogger(PLUGIN_NAME);\n const {\n auth,\n buildRoot,\n bundler: { name: bundlerName, outDir },\n git,\n version,\n } = context;\n const handleTimer = log.time('handle assets');\n let archiveDir: string | undefined;\n let cleanupManifest: (() => Promise<void>) | undefined;\n let toThrow: Error | undefined;\n try {\n const identifierTimer = log.time('resolve identifier');\n\n const { name, identifier } = resolveIdentifier(buildRoot, log, {\n url: git?.remote,\n name: options.name,\n identifier: options.identifier,\n });\n\n if (!identifier || !name) {\n throw new Error(`Missing apps identification.\nEither:\n - pass an 'options.apps.identifier' and 'options.apps.name' to your plugin's configuration.\n - have a 'name' and a 'repository' in your 'package.json'.\n - have a valid remote url on your git project.\n`);\n }\n identifierTimer.end();\n\n const relativeOutdir = path.relative(buildRoot, outDir);\n const assetGlobs = [...options.include, `${relativeOutdir}/**/*`];\n\n const assets = await collectAssets(assetGlobs, buildRoot);\n\n if (!assets.length) {\n log.debug(`No assets to upload.`);\n return;\n }\n\n // Exclude backend output files from frontend assets.\n const backendPaths = new Set(backendOutputs.values());\n const frontendOnly = assets.filter((a) => !backendPaths.has(a.absolutePath));\n\n // Prefix all frontend assets with frontend/.\n // Use POSIX joins — archive entries must use forward slashes.\n const allAssets: Asset[] = frontendOnly.map((asset) => ({\n ...asset,\n relativePath: `frontend/${asset.relativePath}`,\n }));\n\n // Append backend assets from the outputs map populated during the build.\n // Keys are encoded query names ({hash(path)}.{name}).\n for (const [bundleName, absolutePath] of backendOutputs) {\n allAssets.push({\n absolutePath,\n relativePath: `backend/${bundleName}.js`,\n });\n }\n\n const { manifestAsset, cleanup } = await writeManifestFile(backendFunctions, options);\n cleanupManifest = cleanup;\n allAssets.push(manifestAsset);\n\n const archiveTimer = log.time('archive assets');\n const archive = await createArchive(allAssets);\n archiveTimer.end();\n // Store variable for later disposal of directory.\n archiveDir = path.dirname(archive.archivePath);\n\n const uploadTimer = log.time('upload assets');\n const { errors: uploadErrors, warnings: uploadWarnings } = await uploadArchive(\n archive,\n {\n bundlerName,\n doAuthenticatedRequest,\n dryRun: options.dryRun,\n identifier,\n name,\n site: auth.site,\n siteSubdomain: auth.siteSubdomain,\n version,\n },\n log,\n );\n uploadTimer.end();\n\n if (uploadWarnings.length > 0) {\n log.warn(\n `${yellow('Warnings while uploading assets:')}\\n - ${uploadWarnings.join('\\n - ')}`,\n );\n }\n\n if (uploadErrors.length > 0) {\n const listOfErrors = uploadErrors\n .map((error) => {\n // error.cause carries the actionable detail (e.g. ENOTFOUND, ECONNREFUSED)\n // for network-level failures, where fetch's own message is just \"fetch failed\".\n const cause = error.cause instanceof Error ? error.cause.message : error.cause;\n const message = error.message || error.stack || String(error);\n return cause ? `${cause}\\n${message}` : message;\n })\n .join('\\n - ');\n throw new Error(` - ${listOfErrors}`);\n }\n } catch (error: any) {\n toThrow = error;\n log.error(`${red('Failed to upload assets:')}\\n${error?.message || error}`);\n }\n\n // Clean temporary directory\n if (archiveDir) {\n await rm(archiveDir);\n }\n if (cleanupManifest) {\n await cleanupManifest();\n }\n handleTimer.end();\n\n if (toThrow) {\n // Break the build.\n throw toThrow;\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 { rm } from '@dd/core/helpers/fs';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\nimport type { build } from 'vite';\n\nimport {\n getAuthenticatedRequest,\n MissingAuthenticationError,\n type DoAuthenticatedRequest,\n} from '../auth';\nimport { extractExportedFunctions } from '../backend/ast-parsing/extract-backend-functions';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport { generateProxyModule } from '../backend/proxy-codegen';\nimport type { BackendFunction } from '../backend/types';\nimport { BACKEND_FILE_RE, PLUGIN_NAME } from '../constants';\nimport type { AppsOptionsWithDefaults } from '../types';\n\nimport { buildBackendFunctions } from './build-backend-functions';\nimport { createDevServerMiddleware } from './dev-server';\nimport { handleUpload } from './handle-upload';\n\nexport type ViteBundler = {\n build: typeof build;\n};\n\nexport interface VitePluginOptions {\n bundler: ViteBundler;\n context: GlobalContext;\n options: AppsOptionsWithDefaults;\n}\n\n/**\n * Build BackendFunction entries from discovered export names and generate\n * the frontend proxy module that replaces the original backend code.\n */\nfunction buildProxyModule(\n exportNames: string[],\n id: string,\n buildRoot: string,\n): { functions: BackendFunction[]; proxyCode: string } {\n const relativePath = path.relative(buildRoot, id);\n const refPath = relativePath.replace(BACKEND_FILE_RE, '');\n\n const functions: BackendFunction[] = [];\n const proxyExports: Array<{ exportName: string; queryName: string }> = [];\n\n for (const exportName of exportNames) {\n const func = {\n relativePath: refPath,\n name: exportName,\n absolutePath: id,\n allowedConnectionIds: [],\n };\n functions.push(func);\n proxyExports.push({ exportName, queryName: encodeQueryName(func) });\n }\n\n return { functions, proxyCode: generateProxyModule(proxyExports) };\n}\n\n/**\n * Create a registry for tracking discovered backend functions.\n * Uses a Map keyed by entryPath so that re-transforms (e.g. during HMR)\n * replace stale entries for a file instead of appending duplicates.\n */\nfunction createBackendFunctionRegistry() {\n const functionsByEntryPath = new Map<string, BackendFunction[]>();\n\n return {\n /** Replace all entries for a given file. Handles HMR re-transforms. */\n setBackendFunctions(entryPath: string, functions: BackendFunction[]) {\n functionsByEntryPath.set(entryPath, functions);\n },\n /** Get a flat array of all currently registered backend functions. */\n getBackendFunctions(): BackendFunction[] {\n return Array.from(functionsByEntryPath.values()).flat();\n },\n };\n}\n\nconst APPS_RUNTIME_PATH = path.join(__dirname, './apps-runtime.mjs');\n\nconst doDryRunAuthenticatedRequest: DoAuthenticatedRequest = async () => {\n throw new Error('Dry run should not perform authenticated requests.');\n};\n\n/**\n * Returns the Vite-specific plugin hooks for the apps plugin.\n *\n * Transform: discovers backend exports and connection allowlists, registers\n * backend functions, and replaces each backend module with its frontend proxy.\n *\n * Production (closeBundle): builds backend functions (if any) then uploads\n * all assets sequentially.\n *\n * Dev (configureServer): registers middleware for local backend function\n * testing when auth credentials are available.\n */\nexport const getVitePlugin = ({\n bundler,\n context,\n options,\n}: VitePluginOptions): PluginOptions['vite'] => {\n const log = context.getLogger(PLUGIN_NAME);\n const { auth } = context;\n\n context.inject({\n type: 'file',\n position: InjectPosition.MIDDLE,\n value: APPS_RUNTIME_PATH,\n });\n\n const { setBackendFunctions, getBackendFunctions } = createBackendFunctionRegistry();\n\n return {\n transform: {\n filter: {\n id: {\n include: [BACKEND_FILE_RE],\n exclude: [/node_modules/, /[/\\\\]dist[/\\\\]/],\n },\n },\n // For each .backend.* file, parse its named exports, register\n // them as backend functions, and replace the module with a\n // frontend proxy that calls executeBackendFunction at runtime.\n handler(code, id) {\n const ast = this.parse(code);\n const exportNames = extractExportedFunctions(ast, id);\n if (exportNames.length === 0) {\n log.warn(\n `Backend file ${id} has no exported functions. ` +\n `Did you forget to add a named export?`,\n );\n // Clear any previously registered functions for this file\n // so stale entries don't persist across HMR re-transforms.\n setBackendFunctions(id, []);\n return { code: '', map: null };\n }\n\n const { functions, proxyCode } = buildProxyModule(\n exportNames,\n id,\n context.buildRoot,\n );\n setBackendFunctions(id, functions);\n log.debug(`Generated proxy for ${id} with ${functions.length} export(s)`);\n\n return { code: proxyCode, map: null };\n },\n },\n async closeBundle() {\n let backendOutDir: string | undefined;\n let backendOutputs = new Map<string, string>();\n let backendFunctions = getBackendFunctions();\n if (backendFunctions.length > 0) {\n const result = await buildBackendFunctions(\n bundler.build,\n backendFunctions,\n context.buildRoot,\n log,\n );\n backendOutDir = result.outDir;\n backendOutputs = result.outputs;\n backendFunctions = result.functions;\n }\n try {\n const doAuthenticatedRequest = options.dryRun\n ? doDryRunAuthenticatedRequest\n : getAuthenticatedRequest(options.authOverrides.method, auth, log);\n\n await handleUpload({\n backendOutputs,\n backendFunctions,\n context,\n doAuthenticatedRequest,\n options,\n });\n } finally {\n if (backendOutDir) {\n await rm(backendOutDir);\n }\n }\n },\n configureServer(server) {\n let doAuthenticatedRequest: DoAuthenticatedRequest | undefined;\n try {\n doAuthenticatedRequest = getAuthenticatedRequest(\n options.authOverrides.method,\n auth,\n log,\n );\n } catch (error) {\n if (!(error instanceof MissingAuthenticationError)) {\n throw error;\n }\n }\n\n server.middlewares.use(\n createDevServerMiddleware(\n bundler.build,\n getBackendFunctions,\n auth,\n doAuthenticatedRequest,\n context.buildRoot,\n log,\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 { Logger } from '@dd/core/types';\nimport { mkdtemp } from 'fs/promises';\nimport { tmpdir } from 'os';\nimport path from 'path';\nimport type { build } from 'vite';\n\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { BackendFunction } from '../backend/types';\nimport { generateVirtualEntryContent } from '../backend/virtual-entry';\n\nimport { createBackendConnectionIdCollector } from './backend-connection-id-collector';\nimport { getBaseBackendBuildConfig } from './build-config';\n\nconst VIRTUAL_PREFIX = '\\0dd-backend:';\n\n/**\n * Build all backend functions using a separate vite.build() call.\n * Produces one standalone JS file per function in a temp directory.\n *\n * Each bundle filename is the encoded query name (`{hash(path)}.{name}.js`)\n * for the flat backend/ directory in the ZIP.\n */\nexport async function buildBackendFunctions(\n viteBuild: typeof build,\n functions: BackendFunction[],\n buildRoot: string,\n log: Logger,\n): Promise<{ outDir: string; outputs: Map<string, string>; functions: BackendFunction[] }> {\n const outDir = await mkdtemp(path.join(tmpdir(), 'dd-apps-backend-'));\n const outputs = new Map<string, string>();\n const allowedConnectionIdsByEntryPath = new Map<string, string[]>();\n\n log.debug(`Building ${functions.length} backend function(s) via vite.build()`);\n\n // Build each function individually so that each output is a single\n // self-contained JS file\n for (const func of functions) {\n const bundleName = encodeQueryName(func);\n const virtualId = `${VIRTUAL_PREFIX}${bundleName}`;\n const virtualContent = generateVirtualEntryContent(func.name, func.absolutePath, buildRoot);\n const connectionIdCollector = createBackendConnectionIdCollector(\n func.absolutePath,\n buildRoot,\n );\n\n const baseConfig = getBaseBackendBuildConfig(buildRoot, { [virtualId]: virtualContent }, [\n connectionIdCollector.plugin,\n ]);\n\n // eslint-disable-next-line no-await-in-loop\n const result = await viteBuild({\n ...baseConfig,\n build: {\n ...baseConfig.build,\n write: true,\n outDir,\n emptyOutDir: false,\n rollupOptions: {\n ...baseConfig.build.rollupOptions,\n input: { [bundleName]: virtualId },\n output: {\n ...baseConfig.build.rollupOptions.output,\n entryFileNames: '[name].js',\n },\n },\n },\n });\n\n const output = Array.isArray(result) ? result[0] : result;\n\n if ('output' in output) {\n for (const chunk of output.output) {\n if (chunk.type !== 'chunk' || !chunk.isEntry) {\n continue;\n }\n const absolutePath = path.resolve(outDir, chunk.fileName);\n outputs.set(bundleName, absolutePath);\n log.debug(`Backend function \"${bundleName}\" output: ${absolutePath}`);\n }\n }\n\n allowedConnectionIdsByEntryPath.set(\n func.absolutePath,\n connectionIdCollector.getAllowedConnectionIds(),\n );\n }\n\n return {\n outDir,\n outputs,\n functions: functions.map((func) => ({\n ...func,\n allowedConnectionIds: allowedConnectionIdsByEntryPath.get(func.absolutePath)!,\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 } from '@dd/core/types';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { AppsOptions } from './types';\nimport { validateOptions } from './validate';\nimport { getVitePlugin } from './vite/index';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport type types = {\n // Add the types you'd like to expose here.\n AppsOptions: AppsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context, bundler }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options);\n\n if (context.bundler.name !== 'vite') {\n log.warn(`The apps plugin only supports Vite; skipping under '${context.bundler.name}'.`);\n return [];\n }\n\n // All build + upload logic is handled inside the Vite sub-plugin's closeBundle.\n // When backend functions exist, it builds them first, then uploads everything.\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n vite: getVitePlugin({\n bundler,\n context,\n options: validatedOptions,\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 = 'errorTracking' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-error-tracking-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport path from 'path';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap, MinifiedPathPrefix } from '../types';\n\ntype PartialSourcemap = Pick<Sourcemap, 'minifiedFilePath' | 'minifiedUrl' | 'relativePath'>;\n\n// Helper function to safely join URLs or paths\nexport const joinUrlOrPath = (prefix: MinifiedPathPrefix, relativePath: string): string => {\n // Prefix is a path.\n if (prefix.startsWith('/')) {\n // Simply join the prefix with the relative path.\n return path.join(prefix, relativePath);\n }\n\n // Prefix is a URL.\n try {\n // Ensure it ends with a slash for deterministic URL path joining.\n const normalizedPrefix = prefix.replace(/\\/*$/, '/');\n const url = new URL(normalizedPrefix);\n // Ensure the relative path does not start with a slash\n // otherwise it will act as a \"root\" path when joined with the url.\n const normalizedRelativePath = relativePath.replace(/^[\\\\/]*/, '');\n return new URL(normalizedRelativePath, url).href;\n } catch {\n // Fallback to simple concatenation if URL constructor fails\n return `${prefix}${relativePath}`;\n }\n};\n\nexport const decomposePath = (\n prefix: MinifiedPathPrefix,\n // This is coming from context.bundler.outDir, which is absolute.\n absoluteOutDir: string,\n sourcemapFilePath: string,\n): PartialSourcemap => {\n if (path.extname(sourcemapFilePath) !== '.map') {\n throw new Error(`The file ${chalk.green.bold(sourcemapFilePath)} is not a sourcemap.`);\n }\n\n const minifiedFilePath = sourcemapFilePath.replace(/\\.map$/, '');\n const relativePath = path.relative(absoluteOutDir, minifiedFilePath);\n const minifiedUrl = joinUrlOrPath(prefix, relativePath);\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport type SourcemapsFilesContext = {\n outputs?: Output[];\n outDir: string;\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsFilesContext,\n): Sourcemap[] => {\n if (!context.outputs || context.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.outputs\n .filter((file) => file.filepath.endsWith('.map'))\n .map((file) => file.filepath);\n\n const sourcemapFiles = sourcemapFilesList.map((sourcemapFilePath) => {\n return {\n ...decomposePath(options.minifiedPathPrefix, context.outDir, sourcemapFilePath),\n sourcemapFilePath,\n minifiedPathPrefix: options.minifiedPathPrefix,\n };\n });\n\n return sourcemapFiles;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport fsp from 'fs/promises';\n\n// Matches the `ddDebugId:\"<uuid>\"` literal the RUM plugin injects into each chunk's own content\n// (see packages/plugins/rum/src/getSourceCodeContextSnippet.ts). The key is quoted in source\n// (`JSON.stringify(context)`) but minifiers like terser strip quotes from object keys that are\n// valid identifiers, so the built output can have either `\"ddDebugId\":\"...\"` or `ddDebugId:\"...\"`.\n// Reading it back out of the file we're about to upload means we never have to trust a filename\n// as a coordination key between the RUM plugin and this one, so it stays correct across any\n// bundler renaming step.\nconst DEBUG_ID_RX = /\"?ddDebugId\"?:\"([0-9a-fA-F-]{36})\"/;\n\n// The RUM plugin injects its snippet as a BEFORE-position banner (packages/plugins/rum/src/index.ts),\n// so the ddDebugId literal always lands within the file's first couple hundred bytes, regardless\n// of the file's total size — no need to read the whole (potentially large) minified bundle to\n// find it. Measured against ~2.8k real built chunks (mixed bundlers/minifiers), the match always\n// ended by byte 242; this leaves ~4x headroom for longer service/version strings.\nexport const DEBUG_ID_SEARCH_PREFIX_BYTES = 1024;\n\nconst matchDebugId = (fileContent: string): string | undefined => {\n return DEBUG_ID_RX.exec(fileContent)?.[1];\n};\n\n// Read only the first DEBUG_ID_SEARCH_PREFIX_BYTES bytes of the file, since that's all\n// we need to find the ddDebugId literal and reading the whole (potentially large)\n// minified bundle into memory would be wasteful.\nconst readFilePrefix = async (filePath: string): Promise<string> => {\n const fd = await fsp.open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(DEBUG_ID_SEARCH_PREFIX_BYTES);\n const { bytesRead } = await fd.read(buffer, 0, DEBUG_ID_SEARCH_PREFIX_BYTES, 0);\n return buffer.toString('utf-8', 0, bytesRead);\n } finally {\n await fd.close();\n }\n};\n\n// Reads the minified file's own content and extracts the debug_id from it, instead of\n// trusting a filename as a coordination key with the RUM plugin — the bundler may still\n// rename the file after injection (e.g. webpack/rspack's realContentHash), but the content,\n// and the debug_id embedded in it, is unaffected.\nexport const extractDebugId = async (filePath: string): Promise<string | undefined> => {\n const fileContent = await readFilePrefix(filePath).catch(() => undefined);\n return fileContent ? matchDebugId(fileContent) : undefined;\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 debug_id?: 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 debugId?: string,\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 debug_id: debugId,\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 { normalizeTagValue } from '@dd/core/helpers/strings';\nimport type { Metric } from '@dd/core/types';\n\nimport type { SourcemapsOptionsWithDefaults } from '../types';\n\nimport type { UploadContext } from './sender';\n\nexport const SOURCEMAP_UPLOAD_METRIC_PREFIX = 'sourcemaps.upload';\n\ntype UploadMetricName = 'retry' | 'failure';\n\ntype UploadMetric = {\n name: UploadMetricName;\n value: number;\n tags: string[];\n};\n\nexport type SourcemapUploadMetrics = {\n metrics: Map<string, UploadMetric>;\n baseTags: string[];\n};\n\nconst getMetricKey = (name: UploadMetricName, tags: string[]) => `${name}|${tags.join('|')}`;\n\nconst getStatusCodeTag = (error: Error): string => {\n const match = error.message.match(/HTTP (\\d{3})/);\n return match ? `status_code:${match[1]}` : 'status_code:unknown';\n};\n\nconst getErrorTypeTag = (error: Error): string => {\n const statusCodeTag = getStatusCodeTag(error);\n if (statusCodeTag !== 'status_code:unknown') {\n return `error_type:http_${statusCodeTag.replace('status_code:', '')}`;\n }\n\n return `error_type:${normalizeTagValue(error.name || 'unknown')}`;\n};\n\nexport const createSourcemapUploadMetrics = (\n options: SourcemapsOptionsWithDefaults,\n): SourcemapUploadMetrics => ({\n metrics: new Map(),\n baseTags: [`service:${options.service}`],\n});\n\nconst incrementUploadMetric = (\n uploadMetrics: SourcemapUploadMetrics,\n name: UploadMetricName,\n tags: string[],\n) => {\n const metricKey = getMetricKey(name, tags);\n const currentMetric = uploadMetrics.metrics.get(metricKey);\n if (currentMetric) {\n currentMetric.value++;\n return;\n }\n\n uploadMetrics.metrics.set(metricKey, { name, value: 1, tags });\n};\n\nexport const recordSourcemapUploadRetry = (\n uploadMetrics: SourcemapUploadMetrics,\n error: Error,\n attempt: number,\n) => {\n incrementUploadMetric(uploadMetrics, 'retry', [\n ...uploadMetrics.baseTags,\n `attempt:${attempt}`,\n getStatusCodeTag(error),\n getErrorTypeTag(error),\n ]);\n};\n\nexport const recordSourcemapUploadFailure = (\n uploadMetrics: SourcemapUploadMetrics,\n error: Error,\n) => {\n incrementUploadMetric(uploadMetrics, 'failure', [\n ...uploadMetrics.baseTags,\n getStatusCodeTag(error),\n getErrorTypeTag(error),\n ]);\n};\n\nexport const getSourcemapUploadMetrics = (uploadMetrics: SourcemapUploadMetrics): Metric[] => {\n const timestamp = Math.floor(Date.now() / 1000);\n return Array.from(uploadMetrics.metrics.values()).map((metric) => ({\n metric: `${SOURCEMAP_UPLOAD_METRIC_PREFIX}.${metric.name}`,\n type: 'count',\n points: [[timestamp, metric.value]],\n tags: metric.tags,\n }));\n};\n\nexport const addSourcemapUploadMetrics = (\n uploadMetrics: SourcemapUploadMetrics,\n context: UploadContext,\n) => {\n if (!context.sendMetrics) {\n return;\n }\n\n if (!uploadMetrics.metrics.size) {\n return;\n }\n\n const metrics = getSourcemapUploadMetrics(uploadMetrics);\n for (const metric of metrics) {\n context.addMetric(metric);\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 { getDDEnvValue } from '@dd/core/helpers/env';\nimport { getFile } from '@dd/core/helpers/fs';\nimport {\n createRequestData,\n doRequest,\n getOriginHeaders,\n NB_RETRIES,\n type RequestData,\n} from '@dd/core/helpers/request';\nimport { formatDuration, prettyObject } from '@dd/core/helpers/strings';\nimport type { Logger, Metric, RepositoryData } from '@dd/core/types';\nimport chalk from 'chalk';\nimport PQueue from 'p-queue';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap } from '../types';\n\nimport { extractDebugId } from './debugId';\nimport type { Metadata, MultipartFileValue, Payload } from './payload';\nimport { getPayload } from './payload';\nimport {\n addSourcemapUploadMetrics,\n createSourcemapUploadMetrics,\n recordSourcemapUploadFailure,\n recordSourcemapUploadRetry,\n} from './upload-metrics';\n\nconst green = chalk.green.bold;\nconst yellow = chalk.yellow.bold;\nconst red = chalk.red.bold;\n\ntype FileMetadata = {\n sourcemap: string;\n file: string;\n};\n\nexport const SOURCEMAPS_API_SUBDOMAIN = 'sourcemap-intake';\nexport const SOURCEMAPS_API_PATH = 'api/v2/srcmap';\n\nexport const getIntakeUrl = (site: string) => {\n const envIntake = getDDEnvValue('SOURCEMAP_INTAKE_URL');\n return envIntake || `https://${SOURCEMAPS_API_SUBDOMAIN}.${site}/${SOURCEMAPS_API_PATH}`;\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<RequestData> => {\n return createRequestData({\n getForm: async () => {\n const form = new FormData();\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 return form;\n },\n defaultHeaders,\n zip: true,\n });\n };\n\nexport type UploadContext = {\n addMetric: (metric: Metric) => void;\n apiKey?: string;\n bundlerName: string;\n sendMetrics?: boolean;\n site: string;\n version: string;\n outDir: string;\n};\n\nexport const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: UploadContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.apiKey) {\n errors.push({ error: new Error('No authentication token provided') });\n return { errors, warnings };\n }\n\n if (payloads.length === 0) {\n warnings.push('No sourcemaps to upload');\n return { errors, warnings };\n }\n\n const queueTimer = log.time('Queue uploads');\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const queue = new Queue({ concurrency: options.maxConcurrency });\n const intakeUrl = getIntakeUrl(context.site);\n const defaultHeaders = getOriginHeaders({\n bundler: context.bundlerName,\n plugin: 'sourcemaps',\n version: context.version,\n });\n const uploadMetrics = createSourcemapUploadMetrics(options);\n\n // Show a pretty summary of the configuration.\n const configurationString = prettyObject({\n ...options,\n intakeUrl,\n outDir: context.outDir,\n defaultHeaders: `\\n${JSON.stringify(defaultHeaders, null, 2)}`,\n });\n\n const summary = `\\nUploading ${green(payloads.length.toString())} sourcemaps with configuration:\\n${configurationString}`;\n\n log.debug(summary);\n\n const addPromises = [];\n\n for (const payload of payloads) {\n const metadata = {\n sourcemap: (payload.content.get('source_map') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n };\n\n addPromises.push(\n queue.add(async () => {\n try {\n await doRequest({\n auth: { apiKey: context.apiKey },\n url: intakeUrl,\n method: 'POST',\n getData: getData(payload, defaultHeaders),\n // On retry we store the error as a warning.\n onRetry: (error: Error, attempt: number) => {\n recordSourcemapUploadRetry(uploadMetrics, error, attempt);\n const warningMessage = `Failed to upload ${yellow(metadata.sourcemap)} | ${yellow(metadata.file)}:\\n ${error.message}\\nRetrying ${attempt}/${NB_RETRIES}`;\n // This will be logged at the end of the process.\n warnings.push(warningMessage);\n log.debug(warningMessage);\n },\n });\n } catch (e: any) {\n recordSourcemapUploadFailure(uploadMetrics, e);\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 queueTimer.end();\n log.debug(`Queued ${green(payloads.length.toString())} uploads.`);\n\n try {\n await Promise.all(addPromises);\n await queue.onIdle();\n } finally {\n addSourcemapUploadMetrics(uploadMetrics, context);\n }\n\n return { warnings, errors };\n};\n\nexport type SourcemapsSenderContext = UploadContext & {\n git?: RepositoryData;\n};\n\nexport const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsSenderContext,\n log: Logger,\n) => {\n const start = Date.now();\n const prefix = options.minifiedPathPrefix;\n\n const metadata: Metadata = {\n git_repository_url: context.git?.remote,\n git_commit_sha: context.git?.hash,\n plugin_version: context.version,\n project_path: context.outDir,\n service: options.service,\n type: 'js_sourcemap',\n version: options.releaseVersion,\n };\n\n const payloadsTimer = log.time('Compute payloads');\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const payloadsQueue = new Queue({ concurrency: options.maxConcurrency });\n let debugIdCount = 0;\n const payloads: Payload[] = await payloadsQueue.addAll(\n sourcemaps.map((sourcemap) => async () => {\n const debugId = await extractDebugId(sourcemap.minifiedFilePath);\n if (debugId) {\n debugIdCount += 1;\n }\n return getPayload(sourcemap, metadata, prefix, context.git, debugId);\n }),\n );\n payloadsTimer.end();\n log.debug(\n `Extracted debug_id for ${green(`${debugIdCount}/${sourcemaps.length}`)} sourcemaps.`,\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 uploadTimer = log.time('Upload sourcemaps');\n const { errors: uploadErrors, warnings: uploadWarnings } = await upload(\n payloads,\n options,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n version: context.version,\n outDir: context.outDir,\n site: context.site,\n sendMetrics: context.sendMetrics,\n addMetric: context.addMetric,\n },\n log,\n );\n uploadTimer.end();\n log.debug(\n `Done uploading ${green(`${sourcemaps.length - uploadErrors.length}/${sourcemaps.length}`)} sourcemaps in ${green(formatDuration(Date.now() - start))}.`,\n );\n\n if (uploadErrors.length > 0) {\n const listOfErrors = ` - ${uploadErrors\n .map(({ metadata: fileMetadata, error }) => {\n const errorToPrint = error.cause || error.stack || error.message;\n if (fileMetadata) {\n return `${red(fileMetadata.file)} | ${red(fileMetadata.sourcemap)} :\\n${errorToPrint}`;\n }\n return errorToPrint;\n })\n .join('\\n - ')}`;\n\n const errorMsg = `Failed to upload some sourcemaps:\\n${listOfErrors}`;\n log.error(errorMsg);\n\n // Depending on the configuration we throw or not.\n // This should not be reached as we'd have thrown earlier.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n }\n\n if (uploadWarnings.length > 0) {\n log.warn(`Warnings while uploading sourcemaps:\\n - ${uploadWarnings.join('\\n - ')}`);\n }\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n addMetric: context.addMetric,\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n sendMetrics: context.sendMetrics,\n site: context.site,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type {\n ErrorTrackingOptions,\n ErrorTrackingOptionsWithDefaults,\n SourcemapsOptionsWithDefaults,\n} from './types';\n\n// Deal with validation and defaults here.\nexport const validateOptions = (config: Options, log: Logger): ErrorTrackingOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sourcemapsResults = validateSourcemapsOptions(config);\n errors.push(...sourcemapsResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n return {\n ...config[CONFIG_KEY],\n sourcemaps: sourcemapsResults.config,\n };\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 const sourcemapsCfg = validatedOptions.sourcemaps;\n\n // Resolve `releaseVersion`: prefer the plugin-specific option, then\n // fall back to the shared top-level `metadata.version`. Letting users\n // configure one canonical build version at the top level keeps every\n // consumer (live-debugger, sourcemaps, …) reading from the same place.\n const releaseVersion = sourcemapsCfg.releaseVersion || config.metadata?.version;\n\n // Validate the configuration.\n if (!releaseVersion) {\n toReturn.errors.push(\n `${red('sourcemaps.releaseVersion')} is required (set it directly or via ${red('metadata.version')}).`,\n );\n }\n if (\n sourcemapsCfg.releaseVersion &&\n config.metadata?.version &&\n sourcemapsCfg.releaseVersion !== config.metadata.version\n ) {\n toReturn.errors.push(\n `${red('sourcemaps.releaseVersion')} must match ${red('metadata.version')} when both are configured.`,\n );\n }\n if (!sourcemapsCfg.service) {\n toReturn.errors.push(`${red('sourcemaps.service')} is required.`);\n }\n if (!sourcemapsCfg.minifiedPathPrefix) {\n toReturn.errors.push(`${red('sourcemaps.minifiedPathPrefix')} is required.`);\n }\n\n // Validate the minifiedPathPrefix.\n if (\n sourcemapsCfg.minifiedPathPrefix &&\n !validateMinifiedPathPrefix(sourcemapsCfg.minifiedPathPrefix)\n ) {\n toReturn.errors.push(\n `${red('sourcemaps.minifiedPathPrefix')} must be a valid URL or start with '/'.`,\n );\n }\n\n // Build the resolved config only when `releaseVersion` actually\n // resolves; otherwise an error has been recorded and the caller will\n // throw before the config is read.\n if (releaseVersion) {\n toReturn.config = {\n bailOnError: false,\n dryRun: false,\n maxConcurrency: 20,\n ...sourcemapsCfg,\n releaseVersion,\n };\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 { resolveEnable } from '@dd/core/helpers/options';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { BuildReport, GetPlugins, RepositoryData } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { uploadSourcemaps } from './sourcemaps';\nimport type { ErrorTrackingOptions, ErrorTrackingOptionsWithSourcemaps } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME } from './constants';\n\nexport type types = {\n // Add the types you'd like to expose here.\n ErrorTrackingOptions: ErrorTrackingOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const timeOptions = log.time('validate options');\n const validatedOptions = validateOptions(options, log);\n timeOptions.end();\n const sendSourcemapUploadMetrics = resolveEnable(options, 'metrics', log);\n\n let gitInfo: RepositoryData | undefined;\n let buildReport: BuildReport | undefined;\n let sourcemapsHandled: boolean = false;\n\n const handleSourcemaps = async () => {\n if (!validatedOptions.sourcemaps || sourcemapsHandled) {\n return;\n }\n sourcemapsHandled = true;\n const totalTime = log.time('sourcemaps process');\n await uploadSourcemaps(\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n {\n apiKey: context.auth.apiKey,\n bundlerName: context.bundler.name,\n git: gitInfo,\n addMetric: context.addMetric,\n outDir: context.bundler.outDir,\n outputs: buildReport?.outputs || [],\n sendMetrics: sendSourcemapUploadMetrics,\n site: context.auth.site,\n version: context.version,\n },\n log,\n );\n totalTime.end();\n };\n\n const plugins: ReturnType<GetPlugins> = [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async git(repoData) {\n gitInfo = repoData;\n\n if (buildReport) {\n await handleSourcemaps();\n }\n },\n async buildReport(report) {\n buildReport = report;\n\n if (gitInfo || !shouldGetGitInfo(options)) {\n await handleSourcemaps();\n }\n },\n async asyncTrueEnd() {\n // If we're at the end and sourcemaps have not been handled yet,\n // just do it. It can happen when git data isn't accessible for some reason.\n // For insteance, when working from an unpushed repository.\n if (!sourcemapsHandled) {\n await handleSourcemaps();\n }\n },\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 { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'liveDebugger' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-live-debugger-plugin' as const;\n\n// Skip instrumentation comment\nexport const SKIP_INSTRUMENTATION_COMMENT = '@dd-no-instrumentation';\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// Minimal runtime stub injected into all chunks.\n// `$dd_probes` is called unconditionally by instrumented functions, so it must\n// exist before the Browser Debugger SDK initializes. The SDK's `init()` later\n// replaces the stubbed globals with the real implementations.\nconst runtimeStubs = `if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}`;\nconst buildMetadataGlobal = '__DD_LIVE_DEBUGGER_BUILD__' as const;\n\n// Build the runtime bootstrap injected into all chunks. When\n// `metadata.version` is configured, also expose build metadata so the\n// Browser Debugger SDK can default its runtime version from the injected value.\nexport const getRuntimeBootstrap = (version?: string): string => {\n if (version === undefined) {\n return runtimeStubs;\n }\n\n return `${runtimeStubs};if(typeof globalThis.${buildMetadataGlobal}==='undefined'){globalThis.${buildMetadataGlobal}={version:${JSON.stringify(version)}}}`;\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/**\n * Resolve a CJS default export that may be double-wrapped by bundler interop.\n *\n * When a CJS module uses `module.exports = function ...`, ESM `import foo from`\n * should yield the function directly. However, some bundlers (rspack, webpack)\n * wrap the namespace so `foo` is `{ default: fn }` instead of `fn`.\n * This helper normalizes both shapes to the underlying function.\n */\nexport function resolveCjsDefaultExport<T extends Function>(imported: T | { default: T }): T {\n if (typeof imported === 'function') {\n return imported;\n }\n return imported.default;\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 * as t from '@babel/types';\nimport path from 'path';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\n\n/**\n * Generate a stable, unique function ID\n * Format (POC): <relative-file-path>;<function-name>\n * Example: src/utils.js;add\n *\n * NOTE: This POC format only supports uniquely named functions.\n * Anonymous functions will use the format <file-path>;<anonymous>:<index>\n */\nexport function generateFunctionId(\n filePath: string,\n buildRoot: string,\n functionPath: BabelPath<t.Function>,\n anonymousSiblingIndex: number,\n typesModule: BabelTypesModule,\n): string {\n const relativePath = path.relative(buildRoot, filePath).replace(/\\\\/g, '/');\n const functionName = getFunctionName(functionPath, typesModule);\n\n if (functionName) {\n return `${relativePath};${functionName}`;\n }\n\n const locationSuffix = getFunctionLocation(functionPath);\n\n return `${relativePath};<anonymous>@${locationSuffix}:${anonymousSiblingIndex}`;\n}\n\n/**\n * Get the name of a function if available\n */\nexport function getFunctionName(\n functionPath: BabelPath<t.Function>,\n typesModule: BabelTypesModule,\n): string | null {\n const node = functionPath.node;\n const parent = functionPath.parent;\n\n // Named function declaration: function foo() {}\n if ('id' in node && typesModule.isIdentifier(node.id)) {\n return node.id.name;\n }\n\n // Object/Class method: { foo() {} } or class { foo() {} }\n if (\n typesModule.isObjectMethod(node) ||\n typesModule.isClassMethod(node) ||\n typesModule.isClassPrivateMethod(node)\n ) {\n return getPropertyLikeName(node.key, typesModule);\n }\n\n // Variable declaration: const foo = () => {}\n if (typesModule.isVariableDeclarator(parent) && typesModule.isIdentifier(parent.id)) {\n return parent.id.name;\n }\n\n // Assignment: foo = () => {} or obj.foo = () => {}\n if (typesModule.isAssignmentExpression(parent)) {\n return getAssignmentTargetName(parent.left, typesModule);\n }\n\n // Object property: { foo: () => {} }\n if (\n typesModule.isObjectProperty(parent) ||\n typesModule.isClassProperty(parent) ||\n typesModule.isClassPrivateProperty(parent)\n ) {\n return getPropertyLikeName(parent.key, typesModule);\n }\n\n return null;\n}\n\nfunction getAssignmentTargetName(\n target: t.LVal | t.OptionalMemberExpression,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(target)) {\n return target.name;\n }\n\n if (typesModule.isMemberExpression(target) || typesModule.isOptionalMemberExpression(target)) {\n const objectName = getMemberObjectName(target.object, typesModule);\n const propertyName = getMemberPropertyName(target.property, target.computed, typesModule);\n\n if (objectName && propertyName) {\n return `${objectName}.${propertyName}`;\n }\n }\n\n return null;\n}\n\nfunction getMemberObjectName(\n target: t.Expression | t.Super,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(target)) {\n return target.name;\n }\n\n if (typesModule.isThisExpression(target)) {\n return 'this';\n }\n\n if (typesModule.isMemberExpression(target) || typesModule.isOptionalMemberExpression(target)) {\n const parentObjectName = getMemberObjectName(target.object, typesModule);\n const propertyName = getMemberPropertyName(target.property, target.computed, typesModule);\n\n if (parentObjectName && propertyName) {\n return `${parentObjectName}.${propertyName}`;\n }\n }\n\n return null;\n}\n\nfunction getMemberPropertyName(\n property: t.Expression | t.PrivateName,\n isComputed: boolean,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isPrivateName(property) && typesModule.isIdentifier(property.id)) {\n return `#${property.id.name}`;\n }\n\n if (isComputed) {\n return null;\n }\n\n if (typesModule.isIdentifier(property)) {\n return property.name;\n }\n\n return null;\n}\n\nfunction getPropertyLikeName(\n key: t.Expression | t.PrivateName | t.Identifier,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(key)) {\n return key.name;\n }\n\n if (\n typesModule.isStringLiteral(key) ||\n typesModule.isNumericLiteral(key) ||\n typesModule.isBigIntLiteral(key)\n ) {\n return String(key.value);\n }\n\n if (typesModule.isPrivateName(key) && typesModule.isIdentifier(key.id)) {\n return `#${key.id.name}`;\n }\n\n return null;\n}\n\nfunction getFunctionLocation(functionPath: BabelPath<t.Function>): string {\n const line = functionPath.node.loc?.start.line ?? 0;\n const column = functionPath.node.loc?.start.column ?? 0;\n\n return `${line}:${column}`;\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 * as t from '@babel/types';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\n\nfunction hasSkipComment(path: BabelPath, skipComment: string): boolean {\n if (path.node.leadingComments) {\n for (const comment of path.node.leadingComments) {\n if (comment.value.includes(skipComment)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Check if a function should be skipped based on comments.\n *\n * Walks up the AST from the function node through wrapping expression/declaration\n * nodes (VariableDeclarator, VariableDeclaration, ExportNamedDeclaration, etc.)\n * and checks leadingComments at each level. Stops at statement-level boundaries\n * so that comments on unrelated statements are never matched.\n *\n * After reaching a statement boundary (e.g. VariableDeclaration), also checks the\n * parent if it is an export declaration, because `export const fn = ...` attaches\n * the comment to the ExportNamedDeclaration, one level above the statement.\n */\nexport function shouldSkipFunction(\n functionPath: BabelPath<t.Function>,\n skipComment: string,\n typesModule: BabelTypesModule,\n): boolean {\n let current: BabelPath | null = functionPath;\n\n while (current) {\n if (hasSkipComment(current, skipComment)) {\n return true;\n }\n\n // Stop once we reach a statement or export declaration — that is the\n // outermost node where Babel would attach a line-level leading comment.\n if (\n typesModule.isStatement(current.node) ||\n typesModule.isExportDeclaration(current.node)\n ) {\n // For `export const fn = ...`, the comment is on the ExportDeclaration\n // which wraps the VariableDeclaration statement.\n if (current.parentPath && typesModule.isExportDeclaration(current.parentPath.node)) {\n return hasSkipComment(current.parentPath, skipComment);\n }\n break;\n }\n\n current = current.parentPath;\n }\n\n return false;\n}\n\n/**\n * Check if function should be instrumented\n * Skips: generators and constructors\n */\nexport function canInstrumentFunction(\n functionPath: BabelPath<t.Function>,\n typesModule: BabelTypesModule,\n): boolean {\n const node = functionPath.node;\n\n // Skip generators\n if (node.generator) {\n return false;\n }\n\n // Skip constructors\n if (typesModule.isClassMethod(node) && node.kind === 'constructor') {\n return false;\n }\n\n return true;\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 * as t from '@babel/types';\n\nimport type { BabelTypesModule } from './babel-path.types';\n\nexport const MAX_CAPTURE_VARIABLES = 25;\n\nexport interface LocalVariableTemporalDeadZone {\n start: number;\n end: number;\n}\n\nexport interface LocalVariableDeclaration {\n name: string;\n declarationEnd: number;\n temporalDeadZones: LocalVariableTemporalDeadZone[];\n}\n\nexport function getParameterNames(\n functionNode: t.Function,\n typesModule: BabelTypesModule,\n): string[] {\n const variables: string[] = [];\n\n for (const param of functionNode.params) {\n for (const name of getPatternIdentifiers(param, typesModule)) {\n // TypeScript's `this` parameter (e.g. `fn(this: Type)`) is not\n // a real parameter and `this` can't be used as a shorthand\n // property name in object literals.\n if (name !== 'this') {\n variables.push(name);\n }\n }\n }\n\n if (variables.length > MAX_CAPTURE_VARIABLES) {\n return variables.slice(0, MAX_CAPTURE_VARIABLES);\n }\n\n return variables;\n}\n\nexport function getLocalVariableDeclarations(\n functionNode: t.Function,\n typesModule: BabelTypesModule,\n): LocalVariableDeclaration[] {\n const variables: LocalVariableDeclaration[] = [];\n\n if (typesModule.isBlockStatement(functionNode.body)) {\n const paramNames = functionNode.params.flatMap((param) =>\n getPatternIdentifiers(param, typesModule),\n );\n const paramSet = new Set(paramNames);\n const functionName =\n 'id' in functionNode && typesModule.isIdentifier(functionNode.id)\n ? functionNode.id.name\n : '';\n\n for (const stmt of functionNode.body.body) {\n if (typesModule.isVariableDeclaration(stmt)) {\n const declarationEnd = stmt.end;\n if (declarationEnd == null) {\n continue;\n }\n\n for (const decl of stmt.declarations) {\n for (const name of getPatternIdentifiers(decl.id, typesModule)) {\n if (!paramSet.has(name) && name !== functionName) {\n variables.push({\n name,\n declarationEnd,\n temporalDeadZones: [],\n });\n }\n }\n }\n }\n }\n }\n\n const cappedVariables =\n variables.length > MAX_CAPTURE_VARIABLES\n ? variables.slice(0, MAX_CAPTURE_VARIABLES)\n : variables;\n\n if (typesModule.isBlockStatement(functionNode.body)) {\n const localNames = cappedVariables.map(({ name }) => name);\n const localNameSet = new Set(localNames);\n const temporalDeadZonesByName = getNestedTemporalDeadZonesByName(\n functionNode.body,\n localNameSet,\n typesModule,\n );\n\n for (const variable of cappedVariables) {\n variable.temporalDeadZones = temporalDeadZonesByName.get(variable.name) ?? [];\n }\n }\n\n return cappedVariables;\n}\n\nfunction getNestedTemporalDeadZonesByName(\n functionBody: t.BlockStatement,\n localNames: Set<string>,\n typesModule: BabelTypesModule,\n): Map<string, LocalVariableTemporalDeadZone[]> {\n const temporalDeadZonesByName = new Map<string, LocalVariableTemporalDeadZone[]>();\n\n for (const stmt of functionBody.body) {\n collectTemporalDeadZonesFromStatement(\n stmt,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n\n return temporalDeadZonesByName;\n}\n\nfunction collectTemporalDeadZonesFromStatement(\n stmt: t.Statement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n if (typesModule.isFunctionDeclaration(stmt) || typesModule.isClassDeclaration(stmt)) {\n return;\n }\n\n if (typesModule.isBlockStatement(stmt)) {\n collectTemporalDeadZonesFromBlock(stmt, localNames, temporalDeadZonesByName, typesModule);\n } else if (typesModule.isIfStatement(stmt)) {\n collectTemporalDeadZonesFromStatement(\n stmt.consequent,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n if (stmt.alternate) {\n collectTemporalDeadZonesFromStatement(\n stmt.alternate,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n } else if (\n typesModule.isForStatement(stmt) ||\n typesModule.isForInStatement(stmt) ||\n typesModule.isForOfStatement(stmt) ||\n typesModule.isWhileStatement(stmt) ||\n typesModule.isDoWhileStatement(stmt)\n ) {\n collectTemporalDeadZonesFromStatement(\n stmt.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n } else if (typesModule.isSwitchStatement(stmt)) {\n collectTemporalDeadZonesFromSwitch(stmt, localNames, temporalDeadZonesByName, typesModule);\n } else if (typesModule.isTryStatement(stmt)) {\n collectTemporalDeadZonesFromBlock(\n stmt.block,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n if (stmt.handler) {\n collectTemporalDeadZonesFromBlock(\n stmt.handler.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n if (stmt.finalizer) {\n collectTemporalDeadZonesFromBlock(\n stmt.finalizer,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n } else if (typesModule.isLabeledStatement(stmt) || typesModule.isWithStatement(stmt)) {\n collectTemporalDeadZonesFromStatement(\n stmt.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n}\n\nfunction collectTemporalDeadZonesFromBlock(\n block: t.BlockStatement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n addTemporalDeadZonesFromStatements(\n block.body,\n block.start,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n\n for (const stmt of block.body) {\n collectTemporalDeadZonesFromStatement(\n stmt,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n}\n\nfunction collectTemporalDeadZonesFromSwitch(\n stmt: t.SwitchStatement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n for (const caseClause of stmt.cases) {\n addTemporalDeadZonesFromStatements(\n caseClause.consequent,\n stmt.start,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n\n for (const consequent of caseClause.consequent) {\n collectTemporalDeadZonesFromStatement(\n consequent,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n }\n}\n\nfunction addTemporalDeadZonesFromStatements(\n statements: t.Statement[],\n scopeStart: number | null | undefined,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n if (scopeStart == null) {\n return;\n }\n\n for (const stmt of statements) {\n if (typesModule.isVariableDeclaration(stmt) && stmt.kind !== 'var') {\n addVariableDeclarationTemporalDeadZones(\n stmt,\n scopeStart,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n } else if (typesModule.isClassDeclaration(stmt) && stmt.id) {\n addTemporalDeadZone(\n stmt.id.name,\n scopeStart,\n stmt.end,\n localNames,\n temporalDeadZonesByName,\n );\n }\n }\n}\n\nfunction addVariableDeclarationTemporalDeadZones(\n stmt: t.VariableDeclaration,\n scopeStart: number,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n for (const decl of stmt.declarations) {\n for (const name of getPatternIdentifiers(decl.id, typesModule)) {\n addTemporalDeadZone(name, scopeStart, stmt.end, localNames, temporalDeadZonesByName);\n }\n }\n}\n\nfunction addTemporalDeadZone(\n name: string,\n start: number,\n end: number | null | undefined,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n): void {\n if (end == null || !localNames.has(name)) {\n return;\n }\n\n const existingZones = temporalDeadZonesByName.get(name) ?? [];\n existingZones.push({ start, end });\n temporalDeadZonesByName.set(name, existingZones);\n}\n\nfunction getPatternIdentifiers(pattern: t.Node, typesModule: BabelTypesModule): string[] {\n if (typesModule.isIdentifier(pattern)) {\n return [pattern.name];\n }\n\n if (typesModule.isRestElement(pattern)) {\n return typesModule.isIdentifier(pattern.argument)\n ? [pattern.argument.name]\n : getPatternIdentifiers(pattern.argument, typesModule);\n }\n\n if (typesModule.isAssignmentPattern(pattern)) {\n return getPatternIdentifiers(pattern.left, typesModule);\n }\n\n if (typesModule.isObjectPattern(pattern)) {\n return pattern.properties.flatMap((property) => {\n if (typesModule.isRestElement(property)) {\n return getPatternIdentifiers(property.argument, typesModule);\n }\n\n return getPatternIdentifiers(property.value, typesModule);\n });\n }\n\n if (typesModule.isArrayPattern(pattern)) {\n return pattern.elements.flatMap((element) => {\n if (!element) {\n return [];\n }\n\n return getPatternIdentifiers(element, typesModule);\n });\n }\n\n if (typesModule.isTSParameterProperty(pattern)) {\n return typesModule.isIdentifier(pattern.parameter) ? [pattern.parameter.name] : [];\n }\n\n return [];\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 _traverse from '@babel/traverse';\nimport type * as BabelTypes from '@babel/types';\nimport type MagicStringType from 'magic-string';\nimport type { SourceMap } from 'magic-string';\n\nimport { SKIP_INSTRUMENTATION_COMMENT } from '../constants';\nimport type { FunctionKind } from '../types';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\nimport { resolveCjsDefaultExport } from './cjs-interop';\nimport { generateFunctionId, getFunctionName } from './functionId';\nimport { canInstrumentFunction, shouldSkipFunction } from './instrumentation';\nimport { getLocalVariableDeclarations, getParameterNames } from './scopeTracker';\nimport type { LocalVariableDeclaration } from './scopeTracker';\n\ntype TraverseFn = typeof _traverse;\ntype ParseFn = (\n code: string,\n options: {\n sourceType: 'unambiguous';\n plugins: string[];\n sourceFilename: string;\n },\n) => BabelTypes.File;\ntype MagicStringConstructor = typeof import('magic-string').default;\n\n/**\n * Optional peer dependencies that must be present at runtime for the\n * Live Debugger transform to work. They are declared as optional peer\n * dependencies on the published packages so users who don't enable the\n * plugin don't have to install them.\n */\nconst REQUIRED_PEER_DEPS = [\n '@babel/parser',\n '@babel/traverse',\n '@babel/types',\n 'magic-string',\n] as const;\ntype RequiredPeerDep = (typeof REQUIRED_PEER_DEPS)[number];\n\n// Node attaches a string `code` to filesystem/module resolution errors.\ntype NodeModuleError = Error & { code?: string };\n\nlet hasLoadedTransformRuntime = false;\nlet parse: ParseFn;\nlet traverse: TraverseFn;\nlet babelTypes: BabelTypesModule;\nlet MagicString: MagicStringConstructor;\n\nconst getTransformRuntime = (): void => {\n if (!hasLoadedTransformRuntime) {\n // Lazy-load heavy peer deps only when we actually instrument a file.\n // `require()` (not `import()`) because the transform hook is synchronous.\n // `requireOptionalPeerDep` rewrites `MODULE_NOT_FOUND` into a message\n // pointing users at the install step.\n parse = requireOptionalPeerDep<{ parse: ParseFn }>('@babel/parser').parse;\n traverse = resolveCjsDefaultExport(\n requireOptionalPeerDep<TraverseFn | { default: TraverseFn }>('@babel/traverse'),\n );\n babelTypes = requireOptionalPeerDep<BabelTypesModule>('@babel/types');\n MagicString = resolveCjsDefaultExport(\n requireOptionalPeerDep<MagicStringConstructor | { default: MagicStringConstructor }>(\n 'magic-string',\n ),\n );\n\n hasLoadedTransformRuntime = true;\n }\n};\n\n/**\n * Wrapper around `require()` that turns `MODULE_NOT_FOUND` into a clear,\n * actionable error pointing at our optional peer dependencies.\n *\n * The name is restricted to the list of known optional peer deps so each\n * require uses a literal string (survives bundling and satisfies lint rules).\n */\nfunction requireOptionalPeerDep<T>(name: RequiredPeerDep): T {\n try {\n return loadKnownPeerDep(name) as T;\n } catch (error) {\n throw rewrapMissingPeerDepError(error);\n }\n}\n\nfunction loadKnownPeerDep(name: RequiredPeerDep): unknown {\n switch (name) {\n case '@babel/parser':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/parser');\n case '@babel/traverse':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/traverse');\n case '@babel/types':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/types');\n case 'magic-string':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('magic-string');\n default: {\n const exhaustive: never = name;\n throw new Error(`Unknown peer dependency: ${exhaustive as string}`);\n }\n }\n}\n\nfunction rewrapMissingPeerDepError(error: unknown): Error {\n if (!isMissingPeerDepError(error)) {\n return error instanceof Error ? error : new Error(String(error));\n }\n const missingDep = REQUIRED_PEER_DEPS.find((dep) => error.message.includes(dep));\n const target = missingDep ?? REQUIRED_PEER_DEPS.join(', ');\n return new Error(\n `Datadog Live Debugger could not load \"${target}\". ` +\n `It is an optional peer dependency that must be installed in your project ` +\n `when the \\`liveDebugger\\` plugin is enabled. Install the peer dependencies with: ` +\n `\\`npm install --save-dev ${REQUIRED_PEER_DEPS.join(' ')}\\` ` +\n `(or the yarn/pnpm/bun equivalent). ` +\n `Underlying error: ${error.message}`,\n );\n}\n\nfunction isMissingPeerDepError(error: unknown): error is NodeModuleError {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as NodeModuleError).code;\n if (code !== 'MODULE_NOT_FOUND' && code !== 'ERR_MODULE_NOT_FOUND') {\n return false;\n }\n return REQUIRED_PEER_DEPS.some((dep) => error.message.includes(dep));\n}\n\nfunction escapeSingleQuotedJavaScriptString(value: string): string {\n return value.replace(/['\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case \"'\":\n return \"\\\\'\";\n case '\\\\':\n return '\\\\\\\\';\n case '\\n':\n return '\\\\n';\n case '\\r':\n return '\\\\r';\n case '\\u2028':\n return '\\\\u2028';\n case '\\u2029':\n return '\\\\u2029';\n default:\n return character;\n }\n });\n}\n\nconst HAS_FUNCTION_SYNTAX = /\\bfunction\\b|=>|\\bclass\\b|\\)\\s*\\{/;\n\ninterface ReturnInfo {\n start: number;\n end: number;\n argStart: number | undefined;\n argEnd: number | undefined;\n hasSequenceExpressionArgument: boolean;\n}\n\ninterface FunctionTarget {\n bodyStart: number;\n bodyEnd: number;\n functionEnd: number;\n isExpressionBody: boolean;\n hasSequenceExpressionBody: boolean;\n aliasesExpressionBodySuperCall: boolean;\n needsTrailingReturn: boolean;\n useThisAlias: boolean;\n bodyParenStart: number | undefined;\n directivesEnd: number | undefined;\n functionId: string;\n probeVarName: string;\n probeIdx: string;\n entryVars: string[];\n localVars: LocalVariableDeclaration[];\n returns: ReturnInfo[];\n}\n\ninterface SuperCallTarget {\n start: number;\n end: number;\n}\n\ninterface ConstructorThisAliasTarget {\n bodyStart: number;\n superCalls: SuperCallTarget[];\n}\n\nexport interface TransformOptions {\n code: string;\n filePath: string;\n buildRoot: string;\n honorSkipComments: boolean;\n functionTypes: FunctionKind[] | undefined;\n namedOnly: boolean;\n}\n\nexport interface TransformResult {\n code: string;\n map?: SourceMap;\n failedCount: number;\n instrumentedCount: number;\n skippedByCommentCount: number;\n skippedFileCount: number;\n skippedUnsupportedCount: number;\n totalFunctions: number;\n}\n\n/**\n * Transform JavaScript code to add Live Debugger instrumentation.\n * Uses Babel to parse and read the AST, then MagicString for injection.\n */\nexport function transformCode(options: TransformOptions): TransformResult {\n const { code, filePath, buildRoot, honorSkipComments, functionTypes, namedOnly } = options;\n\n let failedCount = 0;\n let instrumentedCount = 0;\n let skippedByCommentCount = 0;\n let skippedUnsupportedCount = 0;\n let totalFunctions = 0;\n\n if (containsUnsupportedImports(code)) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 1,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n if (!HAS_FUNCTION_SYNTAX.test(code)) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n getTransformRuntime();\n const ast = parse(code, {\n sourceType: 'unambiguous',\n plugins: ['jsx', 'typescript'],\n sourceFilename: filePath,\n });\n\n // Read-only traverse: collect instrumentation targets without mutating the AST\n const targets: FunctionTarget[] = [];\n const constructorBodyStartsByNode = new Map<BabelTypes.Node, number>();\n const constructorsUsingThisAlias = new Set<BabelTypes.Node>();\n const superCallsByConstructorNode = new Map<BabelTypes.Node, SuperCallTarget[]>();\n const anonymousCountByParent = new Map<BabelTypes.Node, number>();\n let probeVarCounter = 0;\n\n // @babel/parser and @babel/traverse bundle separate copies of @babel/types,\n // causing a structural type mismatch. The cast is safe: parse() returns a\n // valid AST that traverse() accepts at runtime.\n traverse(ast as unknown as BabelTypes.Node, {\n Function(path: BabelPath<BabelTypes.Function>) {\n totalFunctions++;\n\n const derivedConstructor = getDerivedConstructor(path, babelTypes);\n if (derivedConstructor) {\n constructorBodyStartsByNode.set(derivedConstructor, derivedConstructor.body.start!);\n superCallsByConstructorNode.set(\n derivedConstructor,\n getSuperCallTargets(derivedConstructor.body.body, babelTypes),\n );\n }\n\n if (!canInstrumentFunction(path, babelTypes)) {\n skippedUnsupportedCount++;\n return;\n }\n\n if (\n honorSkipComments &&\n shouldSkipFunction(path, SKIP_INSTRUMENTATION_COMMENT, babelTypes)\n ) {\n skippedByCommentCount++;\n return;\n }\n\n if (functionTypes && !functionTypes.includes(getFunctionKind(path.node, babelTypes))) {\n skippedUnsupportedCount++;\n return;\n }\n\n if (namedOnly && !getFunctionName(path, babelTypes)) {\n skippedUnsupportedCount++;\n return;\n }\n\n // O(1) anonymous sibling index via pre-indexed Map\n let anonymousSiblingIndex = 0;\n if (!getFunctionName(path, babelTypes)) {\n const parentNode = path.parentPath?.node;\n if (parentNode) {\n anonymousSiblingIndex = anonymousCountByParent.get(parentNode) || 0;\n anonymousCountByParent.set(parentNode, anonymousSiblingIndex + 1);\n }\n }\n\n const functionId = generateFunctionId(\n filePath,\n buildRoot,\n path,\n anonymousSiblingIndex,\n babelTypes,\n );\n\n try {\n const node = path.node;\n const idx = probeVarCounter++;\n const probeVarName = `$dd_p${idx}`;\n const entryVars = getParameterNames(node, babelTypes);\n const localVars = getLocalVariableDeclarations(node, babelTypes);\n\n const isExpressionBody =\n babelTypes.isArrowFunctionExpression(node) &&\n !babelTypes.isBlockStatement(node.body);\n const hasSequenceExpressionBody =\n isExpressionBody && babelTypes.isSequenceExpression(node.body);\n const constructorPath = getDerivedConstructorForLexicalThis(path, babelTypes);\n const useThisAlias = constructorPath != null;\n if (constructorPath) {\n constructorsUsingThisAlias.add(constructorPath.node);\n constructorBodyStartsByNode.set(\n constructorPath.node,\n constructorPath.node.body.start!,\n );\n }\n\n const returns: ReturnInfo[] = [];\n const needsTrailingReturn =\n isExpressionBody ||\n !babelTypes.isBlockStatement(node.body) ||\n !alwaysReturns(node.body.body, babelTypes);\n if (!isExpressionBody && babelTypes.isBlockStatement(node.body)) {\n collectReturnStatements(node.body.body, returns, babelTypes);\n }\n\n let directivesEnd: number | undefined;\n if (\n !isExpressionBody &&\n babelTypes.isBlockStatement(node.body) &&\n node.body.directives.length > 0\n ) {\n const lastDirective = node.body.directives[node.body.directives.length - 1];\n directivesEnd = lastDirective.end!;\n }\n\n targets.push({\n bodyStart: node.body.start!,\n bodyEnd: node.body.end!,\n functionEnd: node.end!,\n isExpressionBody,\n hasSequenceExpressionBody,\n aliasesExpressionBodySuperCall:\n useThisAlias &&\n isExpressionBody &&\n isSuperCallExpression(node.body, babelTypes),\n needsTrailingReturn,\n useThisAlias,\n bodyParenStart:\n isExpressionBody && typeof node.body.extra?.parenStart === 'number'\n ? node.body.extra.parenStart\n : undefined,\n directivesEnd,\n functionId,\n probeVarName,\n probeIdx: String(idx),\n entryVars,\n localVars,\n returns,\n });\n\n instrumentedCount++;\n } catch (error) {\n failedCount++;\n }\n },\n });\n\n if (instrumentedCount === 0) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n const s = new MagicString(code);\n const superCallRangesHandledByExpressionBodies =\n getSuperCallRangesHandledByExpressionBodies(targets);\n const constructorThisAliasTargets = getConstructorThisAliasTargets(\n constructorsUsingThisAlias,\n constructorBodyStartsByNode,\n superCallsByConstructorNode,\n superCallRangesHandledByExpressionBodies,\n );\n\n // Process inner (deeper) functions before outer ones so that MagicString\n // appendLeft calls at shared positions (e.g. where an outer return wraps\n // an inner arrow function) stack in the correct order.\n for (let i = targets.length - 1; i >= 0; i--) {\n injectInstrumentation(s, code, targets[i]);\n }\n for (const target of constructorThisAliasTargets) {\n injectConstructorThisAlias(s, code, target);\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({ source: filePath, hires: true }),\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n}\n\n/**\n * Inject instrumentation for a single function.\n */\nfunction injectInstrumentation(s: MagicStringType, code: string, target: FunctionTarget): void {\n const {\n probeVarName,\n probeIdx,\n functionId,\n entryVars,\n localVars,\n returns,\n bodyStart,\n bodyEnd,\n functionEnd,\n isExpressionBody,\n hasSequenceExpressionBody,\n aliasesExpressionBodySuperCall,\n useThisAlias,\n bodyParenStart,\n directivesEnd,\n } = target;\n\n const entryHelper = `$dd_e${probeIdx}`;\n const rvVarName = `$dd_rv${probeIdx}`;\n const receiverArg = useThisAlias ? '$dd_t' : 'this';\n\n const entryVarsList = entryVars.join(', ');\n\n const hasParams = entryVarsList !== '';\n\n const argsArg = hasParams ? `, ${entryHelper}()` : '';\n\n const escapedFunctionId = escapeSingleQuotedJavaScriptString(functionId);\n const probeDecl = `const ${probeVarName} = $dd_probes('${escapedFunctionId}');`;\n const entryHelperDecl = hasParams ? `const ${entryHelper} = () => ({${entryVarsList}});` : '';\n const entryCall = `if (${probeVarName}) $dd_entry(${probeVarName}, ${receiverArg}${argsArg});`;\n const catchBlock = `catch(e) { if (${probeVarName}) $dd_throw(${probeVarName}, e, ${receiverArg}${argsArg}); throw e; }`;\n\n if (isExpressionBody) {\n // Arrow expression body: (a) => expr\n // Wrap in block body with temp variable to avoid duplicating nested expressions\n\n // Handle parenthesized expression bodies: () => ({key: value})\n // The parentheses must be removed when converting to a block body,\n // otherwise the output would be => ({block_code}) which is a syntax error.\n // Babel stores nested bodies like `((1))` as body `1`, so every wrapper\n // paren around the body range must be removed before injecting a block.\n if (bodyParenStart != null) {\n const openingParens = getLeadingArrowBodyParens(code, bodyParenStart, bodyStart);\n const closingParens = getTrailingArrowBodyParens(code, bodyEnd, functionEnd);\n const parenCount = Math.min(openingParens.length, closingParens.length);\n\n for (let i = 0; i < parenCount; i++) {\n const openingParen = openingParens[i];\n const closingParen = closingParens[i];\n s.remove(openingParen, openingParen + 1);\n s.remove(closingParen, closingParen + 1);\n }\n }\n\n const prefix = [\n '{',\n probeDecl,\n entryHelperDecl,\n 'try {',\n entryCall,\n aliasesExpressionBodySuperCall\n ? `const ${rvVarName} = ($dd_t = `\n : `const ${rvVarName} = `,\n ]\n .filter(Boolean)\n .join('\\n');\n\n const returnCaptureArgs = getReturnCaptureArgs(entryHelper, hasParams, localVars, bodyEnd);\n let expressionSuffix = hasSequenceExpressionBody ? ');' : ';';\n if (aliasesExpressionBodySuperCall) {\n expressionSuffix = hasSequenceExpressionBody ? '));' : ');';\n }\n const suffix = [\n expressionSuffix,\n `if (${probeVarName}) $dd_return(${probeVarName}, ${rvVarName}, ${receiverArg}${returnCaptureArgs});`,\n `return ${rvVarName};`,\n `} ${catchBlock}`,\n '}',\n ].join('\\n');\n\n // Anchor each injected line to the original expression's location by\n // editing the boundary chars of the body. Two updates avoid losing\n // per-character mappings of the original expression in between.\n // For a single-char body (e.g. `() => 1`) the two ranges would\n // collide, so we fall back to one update covering the whole body.\n if (bodyEnd - bodyStart >= 2) {\n const bodyPrefix = hasSequenceExpressionBody\n ? `${prefix}(${code[bodyStart]}`\n : prefix + code[bodyStart];\n s.update(bodyStart, bodyStart + 1, bodyPrefix);\n s.update(bodyEnd - 1, bodyEnd, code[bodyEnd - 1] + suffix);\n } else {\n s.update(bodyStart, bodyEnd, prefix + code.slice(bodyStart, bodyEnd) + suffix);\n }\n } else {\n // Block body function\n const preamble = [probeDecl, entryHelperDecl, 'try {', `let ${rvVarName};`, entryCall]\n .filter(Boolean)\n .join('\\n');\n\n // Wrap return statements BEFORE the boundary updates so that when\n // a semicolon-free final return shares its argEnd position with\n // bodyEnd - 1, the return suffix is appended to the preceding chunk\n // (its outro) and ends up before the postamble in the generated code.\n for (const ret of returns) {\n const returnCaptureArgs = getReturnCaptureArgs(\n entryHelper,\n hasParams,\n localVars,\n ret.start,\n );\n\n if (ret.argStart != null && ret.argEnd != null) {\n // return EXPR; → return ($dd_rvN = EXPR, probe ? $dd_return(...) : $dd_rvN);\n const assignmentPrefix = ret.hasSequenceExpressionArgument\n ? `(${rvVarName} = (`\n : `(${rvVarName} = `;\n const assignmentSuffix = ret.hasSequenceExpressionArgument ? ')' : '';\n\n s.appendLeft(ret.argStart, assignmentPrefix);\n s.appendLeft(\n ret.argEnd,\n `${assignmentSuffix}, ${probeVarName} ? $dd_return(${probeVarName}, ${rvVarName}, ${receiverArg}${returnCaptureArgs}) : ${rvVarName})`,\n );\n } else {\n // return; → if (probe) $dd_return(...); return;\n s.appendLeft(\n ret.start,\n `if (${probeVarName}) $dd_return(${probeVarName}, undefined, ${receiverArg}${returnCaptureArgs}); `,\n );\n }\n }\n\n // Wrap the boundary character (last directive char or the body's\n // opening `{`) with `<char><preamble>`. Editing through `update()`\n // makes magic-string emit a source-map segment for every line of\n // the new content, all anchored at that boundary char's location —\n // so injected preamble lines map to the function's own line instead\n // of to nothing.\n //\n // For directives, an additional leading newline keeps the preamble\n // on its own line (the directive's trailing `;` already ends a\n // statement, but its terminator stays on the directive's line).\n if (directivesEnd != null) {\n const anchor = directivesEnd - 1;\n s.update(anchor, directivesEnd, `${code[anchor]}\\n${preamble}`);\n } else {\n s.update(bodyStart, bodyStart + 1, `${code[bodyStart]}${preamble}`);\n }\n\n // Build the postamble. The optional trailing-return helper is\n // included here (rather than as a separate appendLeft) so that the\n // single boundary update for `}` covers it; this keeps the trailing\n // helper's source-map segment anchored to the closing brace too.\n const trailingReturnCaptureArgs = getReturnCaptureArgs(\n entryHelper,\n hasParams,\n localVars,\n bodyEnd,\n );\n const trailingReturn = target.needsTrailingReturn\n ? `if (${probeVarName}) $dd_return(${probeVarName}, undefined, ${receiverArg}${trailingReturnCaptureArgs});\\n`\n : '';\n const postamble = `\\n${trailingReturn}} ${catchBlock}\\n`;\n s.update(bodyEnd - 1, bodyEnd, `${postamble}${code[bodyEnd - 1]}`);\n }\n}\n\nfunction injectConstructorThisAlias(\n s: MagicStringType,\n code: string,\n target: ConstructorThisAliasTarget,\n): void {\n s.update(target.bodyStart, target.bodyStart + 1, `${code[target.bodyStart]}let $dd_t;`);\n\n for (const superCall of target.superCalls) {\n s.appendLeft(superCall.start, '($dd_t = ');\n s.appendLeft(superCall.end, ')');\n }\n}\n\nfunction getSuperCallTargets(\n statements: BabelTypes.Statement[],\n typesModule: BabelTypesModule,\n): SuperCallTarget[] {\n const targets: SuperCallTarget[] = [];\n for (const statement of statements) {\n collectSuperCallTargetsFromNode(statement, targets, typesModule);\n }\n\n return targets;\n}\n\nfunction collectSuperCallTargetsFromNode(\n node: BabelTypes.Node,\n targets: SuperCallTarget[],\n typesModule: BabelTypesModule,\n): void {\n if (isSuperCallExpression(node, typesModule)) {\n targets.push({\n start: node.start!,\n end: node.end!,\n });\n }\n\n const values = Object.values(node);\n for (const value of values) {\n if (Array.isArray(value)) {\n for (const item of value) {\n collectSuperCallTargetsFromUnknown(item, targets, typesModule);\n }\n } else {\n collectSuperCallTargetsFromUnknown(value, targets, typesModule);\n }\n }\n}\n\nfunction collectSuperCallTargetsFromUnknown(\n value: unknown,\n targets: SuperCallTarget[],\n typesModule: BabelTypesModule,\n): void {\n if (!typesModule.isNode(value)) {\n return;\n }\n\n if (typesModule.isFunction(value) && !typesModule.isArrowFunctionExpression(value)) {\n return;\n }\n\n collectSuperCallTargetsFromNode(value, targets, typesModule);\n}\n\nfunction getConstructorThisAliasTargets(\n constructorsUsingThisAlias: Set<BabelTypes.Node>,\n constructorBodyStartsByNode: Map<BabelTypes.Node, number>,\n superCallsByConstructorNode: Map<BabelTypes.Node, SuperCallTarget[]>,\n superCallRangesHandledByExpressionBodies: Set<string>,\n): ConstructorThisAliasTarget[] {\n const targets: ConstructorThisAliasTarget[] = [];\n\n for (const constructorNode of constructorsUsingThisAlias) {\n const bodyStart = constructorBodyStartsByNode.get(constructorNode);\n if (bodyStart == null) {\n continue;\n }\n\n targets.push({\n bodyStart,\n superCalls: (superCallsByConstructorNode.get(constructorNode) ?? []).filter(\n (superCall) =>\n !superCallRangesHandledByExpressionBodies.has(getRangeKey(superCall)),\n ),\n });\n }\n\n return targets;\n}\n\nfunction getSuperCallRangesHandledByExpressionBodies(targets: FunctionTarget[]): Set<string> {\n const ranges = new Set<string>();\n for (const target of targets) {\n if (target.aliasesExpressionBodySuperCall) {\n ranges.add(getRangeKey({ start: target.bodyStart, end: target.bodyEnd }));\n }\n }\n\n return ranges;\n}\n\nfunction getRangeKey(range: SuperCallTarget): string {\n return `${range.start}:${range.end}`;\n}\n\nfunction getDerivedConstructor(\n path: BabelPath<BabelTypes.Function>,\n typesModule: BabelTypesModule,\n): BabelTypes.ClassMethod | undefined {\n if (\n typesModule.isClassMethod(path.node) &&\n path.node.kind === 'constructor' &&\n isDerivedClassMethod(path, typesModule)\n ) {\n return path.node;\n }\n\n return undefined;\n}\n\nfunction getDerivedConstructorForLexicalThis(\n path: BabelPath,\n typesModule: BabelTypesModule,\n): BabelPath<BabelTypes.ClassMethod> | undefined {\n if (typesModule.isFunction(path.node) && !typesModule.isArrowFunctionExpression(path.node)) {\n return undefined;\n }\n\n let current = path.parentPath;\n while (current) {\n const node = current.node;\n if (typesModule.isClassMethod(node) && node.kind === 'constructor') {\n if (!isDerivedClassMethod(current, typesModule)) {\n return undefined;\n }\n\n return {\n node,\n parent: current.parent,\n parentPath: current.parentPath,\n };\n }\n\n if (typesModule.isFunction(node)) {\n if (typesModule.isArrowFunctionExpression(node)) {\n current = current.parentPath;\n continue;\n }\n\n return undefined;\n }\n\n current = current.parentPath;\n }\n\n return undefined;\n}\n\nfunction isSuperCallExpression(\n node: BabelTypes.Node,\n typesModule: BabelTypesModule,\n): node is BabelTypes.CallExpression {\n return typesModule.isCallExpression(node) && typesModule.isSuper(node.callee);\n}\n\nfunction isDerivedClassMethod(path: BabelPath, typesModule: BabelTypesModule): boolean {\n const classPath = path.parentPath?.parentPath;\n if (!classPath) {\n return false;\n }\n\n const classNode = classPath.node;\n return (\n (typesModule.isClassDeclaration(classNode) || typesModule.isClassExpression(classNode)) &&\n classNode.superClass != null\n );\n}\n\nfunction getReturnCaptureArgs(\n entryHelper: string,\n hasParams: boolean,\n localVars: LocalVariableDeclaration[],\n exitPosition: number,\n): string {\n const localsArg = getLocalCaptureArg(localVars, exitPosition);\n if (hasParams && localsArg) {\n return `, ${entryHelper}(), ${localsArg}`;\n }\n if (hasParams) {\n return `, ${entryHelper}()`;\n }\n if (localsArg) {\n return `, undefined, ${localsArg}`;\n }\n return '';\n}\n\nfunction getLeadingArrowBodyParens(code: string, start: number, end: number): number[] {\n const parens: number[] = [];\n for (let i = start; i < end; i++) {\n if (code[i] === '(') {\n parens.push(i);\n }\n }\n return parens;\n}\n\nfunction getTrailingArrowBodyParens(code: string, start: number, end: number): number[] {\n const parens: number[] = [];\n for (let i = end - 1; i >= start; i--) {\n if (code[i] === ')') {\n parens.push(i);\n }\n }\n return parens;\n}\n\nfunction getLocalCaptureArg(\n localVars: LocalVariableDeclaration[],\n exitPosition: number,\n): string | undefined {\n const availableLocals = localVars\n .filter(\n ({ declarationEnd, temporalDeadZones }) =>\n declarationEnd <= exitPosition &&\n !isInTemporalDeadZone(temporalDeadZones, exitPosition),\n )\n .map(({ name }) => name);\n\n if (availableLocals.length === 0) {\n return undefined;\n }\n\n return `{${availableLocals.join(', ')}}`;\n}\n\nfunction isInTemporalDeadZone(\n temporalDeadZones: LocalVariableDeclaration['temporalDeadZones'],\n position: number,\n): boolean {\n return temporalDeadZones.some(({ start, end }) => start <= position && position < end);\n}\n\n/**\n * Recursively collect return statements within a function body,\n * skipping nested function/class bodies.\n */\nfunction collectReturnStatements(\n statements: BabelTypes.Statement[],\n returns: ReturnInfo[],\n typesModule: BabelTypesModule,\n): void {\n for (const stmt of statements) {\n if (typesModule.isReturnStatement(stmt)) {\n returns.push({\n start: stmt.start!,\n end: stmt.end!,\n argStart: stmt.argument?.start ?? undefined,\n argEnd: stmt.argument?.end ?? undefined,\n hasSequenceExpressionArgument: typesModule.isSequenceExpression(stmt.argument),\n });\n continue;\n }\n\n if (typesModule.isFunctionDeclaration(stmt) || typesModule.isClassDeclaration(stmt)) {\n continue;\n }\n\n if (typesModule.isBlockStatement(stmt)) {\n collectReturnStatements(stmt.body, returns, typesModule);\n } else if (typesModule.isIfStatement(stmt)) {\n collectReturnStatements([stmt.consequent], returns, typesModule);\n if (stmt.alternate) {\n collectReturnStatements([stmt.alternate], returns, typesModule);\n }\n } else if (\n typesModule.isForStatement(stmt) ||\n typesModule.isForInStatement(stmt) ||\n typesModule.isForOfStatement(stmt) ||\n typesModule.isWhileStatement(stmt) ||\n typesModule.isDoWhileStatement(stmt)\n ) {\n collectReturnStatements([stmt.body], returns, typesModule);\n } else if (typesModule.isSwitchStatement(stmt)) {\n for (const caseClause of stmt.cases) {\n collectReturnStatements(caseClause.consequent, returns, typesModule);\n }\n } else if (typesModule.isTryStatement(stmt)) {\n collectReturnStatements(stmt.block.body, returns, typesModule);\n if (stmt.handler) {\n collectReturnStatements(stmt.handler.body.body, returns, typesModule);\n }\n if (stmt.finalizer) {\n collectReturnStatements(stmt.finalizer.body, returns, typesModule);\n }\n } else if (typesModule.isLabeledStatement(stmt)) {\n collectReturnStatements([stmt.body], returns, typesModule);\n } else if (typesModule.isWithStatement(stmt)) {\n collectReturnStatements([stmt.body], returns, typesModule);\n }\n }\n}\n\n/**\n * Lightweight control-flow check: does this statement list guarantee a return\n * on every path? Handles direct returns and exhaustive if/else branches.\n * Conservatively returns false for loops, switch, try/catch, etc.\n */\nfunction alwaysReturns(statements: BabelTypes.Statement[], typesModule: BabelTypesModule): boolean {\n if (statements.length === 0) {\n return false;\n }\n const last = statements[statements.length - 1];\n\n if (typesModule.isReturnStatement(last)) {\n return true;\n }\n\n if (typesModule.isIfStatement(last) && last.alternate) {\n const consequent = typesModule.isBlockStatement(last.consequent)\n ? last.consequent.body\n : [last.consequent];\n const alternate = typesModule.isBlockStatement(last.alternate)\n ? last.alternate.body\n : [last.alternate];\n return alwaysReturns(consequent, typesModule) && alwaysReturns(alternate, typesModule);\n }\n\n return false;\n}\n\nfunction getFunctionKind(node: BabelTypes.Function, typesModule: BabelTypesModule): FunctionKind {\n if (typesModule.isFunctionDeclaration(node)) {\n return 'functionDeclaration';\n }\n if (typesModule.isArrowFunctionExpression(node)) {\n return 'arrowFunction';\n }\n if (typesModule.isObjectMethod(node)) {\n return 'objectMethod';\n }\n if (typesModule.isClassPrivateMethod(node)) {\n return 'classPrivateMethod';\n }\n if (typesModule.isClassMethod(node)) {\n return 'classMethod';\n }\n return 'functionExpression';\n}\n\nfunction containsUnsupportedImports(code: string): boolean {\n return /['\"][^'\"]*(?:@css-module:|\\?worker\\b|\\?sprite\\b|dynamic!)[^'\"]*['\"]/.test(code);\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 VALID_FUNCTION_KINDS = [\n 'functionDeclaration',\n 'functionExpression',\n 'arrowFunction',\n 'objectMethod',\n 'classMethod',\n 'classPrivateMethod',\n] as const;\n\nexport type FunctionKind = (typeof VALID_FUNCTION_KINDS)[number];\n\nexport type LiveDebuggerOptions = {\n enable?: boolean;\n include?: (string | RegExp)[];\n exclude?: (string | RegExp)[];\n honorSkipComments?: boolean;\n functionTypes?: FunctionKind[];\n namedOnly?: boolean;\n};\n\nexport type LiveDebuggerOptionsWithDefaults = {\n version: string | undefined;\n include: (string | RegExp)[];\n exclude: (string | RegExp)[];\n honorSkipComments: boolean;\n functionTypes: FunctionKind[] | undefined;\n namedOnly: 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 { Logger, Options } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { LiveDebuggerOptions, LiveDebuggerOptionsWithDefaults } from './types';\nimport { VALID_FUNCTION_KINDS } from './types';\n\nconst red = chalk.bold.red;\n\nexport const validateOptions = (config: Options, log: Logger): LiveDebuggerOptionsWithDefaults => {\n const pluginConfig: LiveDebuggerOptions = config[CONFIG_KEY] || {};\n const metadataVersion = config.metadata?.version;\n const errors: string[] = [];\n\n // Validate include option\n if (pluginConfig.include !== undefined) {\n if (!Array.isArray(pluginConfig.include)) {\n errors.push(`${red('include')} must be an array of strings or RegExp`);\n } else {\n for (const pattern of pluginConfig.include) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n errors.push(`${red('include')} patterns must be strings or RegExp`);\n break;\n }\n }\n }\n }\n\n // Validate exclude option\n if (pluginConfig.exclude !== undefined) {\n if (!Array.isArray(pluginConfig.exclude)) {\n errors.push(`${red('exclude')} must be an array of strings or RegExp`);\n } else {\n for (const pattern of pluginConfig.exclude) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n errors.push(`${red('exclude')} patterns must be strings or RegExp`);\n break;\n }\n }\n }\n }\n\n // Validate honorSkipComments option\n if (\n pluginConfig.honorSkipComments !== undefined &&\n typeof pluginConfig.honorSkipComments !== 'boolean'\n ) {\n errors.push(`${red('honorSkipComments')} must be a boolean`);\n }\n\n // Validate functionTypes option\n if (pluginConfig.functionTypes !== undefined) {\n if (!Array.isArray(pluginConfig.functionTypes)) {\n errors.push(`${red('functionTypes')} must be an array of FunctionKind values`);\n } else {\n for (const kind of pluginConfig.functionTypes) {\n if (!VALID_FUNCTION_KINDS.includes(kind)) {\n errors.push(\n `${red('functionTypes')} contains invalid value \"${kind}\". Valid values: ${VALID_FUNCTION_KINDS.join(', ')}`,\n );\n break;\n }\n }\n }\n }\n\n // Validate namedOnly option\n if (pluginConfig.namedOnly !== undefined && typeof pluginConfig.namedOnly !== 'boolean') {\n errors.push(`${red('namedOnly')} must be a boolean`);\n }\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 with defaults\n return {\n version: metadataVersion,\n include: pluginConfig.include || [/\\.[jt]sx?$/], // .js, .jsx, .ts, .tsx\n exclude: pluginConfig.exclude || [\n /\\/node_modules\\//,\n /\\.min\\.js$/,\n /\\/pyodide-lib\\//, // Bundled third-party Pyodide library\n /^vite\\//, // Vite internal modules\n /\\0/, // Virtual modules (Rollup/Vite convention)\n /commonjsHelpers\\.js$/, // Rollup commonjs helpers\n /__vite-browser-external/, // Vite browser externals\n /@datadog\\/browser-/, // Datadog browser SDK packages (when npm linked)\n /browser-sdk\\/packages\\//, // Datadog browser SDK source files\n ],\n honorSkipComments: pluginConfig.honorSkipComments ?? true,\n functionTypes: pluginConfig.functionTypes,\n namedOnly: pluginConfig.namedOnly ?? false,\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, GlobalContext, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport remapping from '@jridgewell/remapping';\nimport type { SourceMapInput } from '@jridgewell/remapping';\nimport type { SourceMap } from 'magic-string';\nimport type { SourceMapCompact, UnpluginBuildContext } from 'unplugin';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { getRuntimeBootstrap } from './runtime-bootstrap';\nimport { transformCode } from './transform';\nimport type { LiveDebuggerOptions, LiveDebuggerOptionsWithDefaults } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nconst DD_LD_LIMIT = Number(process.env.DD_LD_LIMIT) || Infinity;\n\n// Export types for factory integration\nexport type types = {\n LiveDebuggerOptions: LiveDebuggerOptions;\n};\n\nexport const getLiveDebuggerPlugin = (\n pluginOptions: LiveDebuggerOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n\n let instrumentedCount = 0;\n let failedCount = 0;\n let skippedByCommentCount = 0;\n let skippedFileCount = 0;\n let skippedUnsupportedCount = 0;\n let transformedFileCount = 0;\n let totalFunctions = 0;\n let totalFilesWithFunctions = 0;\n\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: pluginOptions.include,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n // Enforce include/exclude patterns at runtime because unplugin's\n // native filter is not applied in bundler child compilations\n // (e.g., web worker bundles in rspack/webpack).\n if (pluginOptions.include.length > 0) {\n const included = pluginOptions.include.some((pattern) =>\n typeof pattern === 'string' ? id.includes(pattern) : pattern.test(id),\n );\n if (!included) {\n return { code };\n }\n }\n\n for (const pattern of pluginOptions.exclude) {\n const excluded =\n typeof pattern === 'string' ? id.includes(pattern) : pattern.test(id);\n if (excluded) {\n return { code };\n }\n }\n\n if (totalFilesWithFunctions >= DD_LD_LIMIT) {\n return { code };\n }\n\n try {\n const result = transformCode({\n code,\n filePath: id,\n buildRoot: context.buildRoot,\n honorSkipComments: pluginOptions.honorSkipComments,\n functionTypes: pluginOptions.functionTypes,\n namedOnly: pluginOptions.namedOnly,\n });\n\n instrumentedCount += result.instrumentedCount;\n totalFunctions += result.totalFunctions;\n failedCount += result.failedCount;\n skippedByCommentCount += result.skippedByCommentCount;\n skippedFileCount += result.skippedFileCount;\n skippedUnsupportedCount += result.skippedUnsupportedCount;\n\n if (result.totalFunctions > 0) {\n totalFilesWithFunctions++;\n }\n\n if (result.instrumentedCount === 0) {\n return {\n // No changes, return original code\n code,\n };\n }\n\n transformedFileCount++;\n\n const inputMap = getInputSourceMap(this);\n const composedMap =\n result.map && inputMap\n ? composeWithInputMap(result.map, inputMap, id, log)\n : result.map;\n\n return {\n code: result.code,\n map: composedMap,\n };\n } catch (e) {\n log.error(`Instrumentation Error in ${id}: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n buildEnd: () => {\n if (totalFunctions > 0) {\n log.info(\n `Live Debugger: ${instrumentedCount}/${totalFunctions} functions instrumented across ${transformedFileCount}/${totalFilesWithFunctions} files`,\n {\n forward: true,\n context: {\n failedCount,\n skippedByCommentCount,\n skippedFileCount,\n skippedUnsupportedCount,\n totalFilesWithFunctions,\n instrumentedCount,\n totalFunctions,\n transformedFileCount,\n },\n },\n );\n }\n },\n };\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options, log);\n\n // Inject no-op stubs for the runtime globals so instrumented code\n // doesn't crash when the Datadog Browser Debugger SDK is absent.\n // The SDK's init() overwrites these with the real implementations.\n context.inject({\n type: 'code',\n position: InjectPosition.BEFORE,\n injectIntoAllChunks: true,\n value: getRuntimeBootstrap(validatedOptions.version),\n });\n\n return [getLiveDebuggerPlugin(validatedOptions, context)];\n};\n\n/**\n * Return the source map produced by the previous loader, if any.\n */\nfunction getInputSourceMap(ctx: UnpluginBuildContext): SourceMapInput | undefined {\n const native = ctx.getNativeBuildContext?.();\n return (native as { inputSourceMap?: SourceMapInput })?.inputSourceMap;\n}\n\n/**\n * Compose a local source map with the previous loader's source map. The result maps instrumented\n * output directly back to original source coordinates.\n */\nfunction composeWithInputMap(\n instrumentMap: SourceMap,\n inputMap: SourceMapInput,\n id: string,\n log: ReturnType<GlobalContext['getLogger']>,\n): SourceMapCompact | SourceMap {\n try {\n return remapping(instrumentMap as unknown as SourceMapInput, (_file, ctx) =>\n ctx.depth === 1 ? inputMap : null,\n ) as unknown as SourceMapCompact;\n } catch (e) {\n log.error(`Failed to compose source map for ${id}: ${e}`, { forward: true });\n return instrumentMap;\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, GlobalStores } from '@dd/core/types';\n\nexport const initializeMetricsCollector = (context: GlobalContext, stores: GlobalStores) => {\n context.addMetric = (metric) => {\n stores.metrics.add(metric);\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Metric } from '@dd/core/types';\n\nconst filterTreeMetrics = (metric: Metric): Metric | null =>\n // Remove tree metrics because way too verbose\n !/modules\\.tree\\.(count|size)$/.test(metric.metric) ? metric : null;\n\nconst filterSourcemapsAndNodeModules = (metric: Metric): Metric | null =>\n metric.tags.some(\n (tag: string) =>\n // Remove sourcemaps.\n /^assetName:.*\\.map$/.test(tag) ||\n // Remove third parties.\n /^moduleName:\\/node_modules/.test(tag),\n )\n ? null\n : metric;\n\nconst filterMetricsOnThreshold = (metric: Metric): Metric | null => {\n const thresholds = {\n size: 100000,\n count: 10,\n duration: 1000,\n };\n if (/^sourcemaps\\.upload\\.(failure|retry)$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Allow count for smaller results.\n if (/(entries|loaders|warnings|errors)\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Dependencies are huges, lets submit a bit less.\n if (/(modules\\.(dependencies|dependents)$)/.test(metric.metric)) {\n thresholds.count = 30;\n }\n // Dependency tree calculation can output a lot of metrics.\n if (/modules\\.tree\\.count$/.test(metric.metric)) {\n thresholds.count = 150;\n }\n if (/modules\\.tree\\.size$/.test(metric.metric)) {\n thresholds.size = 1500000;\n }\n // We want to track entry size whatever their size.\n if (/entries\\.size$/.test(metric.metric)) {\n thresholds.size = 0;\n }\n // We want to track entry module count whatever their number\n if (/entries\\.modules\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n const avg = metric.points.length\n ? metric.points.reduce((accumulator, currentPoint) => accumulator + currentPoint[1], 0) /\n metric.points.length\n : 0;\n return avg > thresholds[metric.type] ? metric : null;\n};\n\nexport const defaultFilters: ((metric: Metric) => Metric | null)[] = [\n filterTreeMetrics,\n filterSourcemapsAndNodeModules,\n filterMetricsOnThreshold,\n];\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'metrics' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-metrics-plugin` as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { normalizeTagValue } from '@dd/core/helpers/strings';\nimport type {\n GlobalContext,\n OptionsWithDefaults,\n Metric,\n ValueContext,\n MetricToSend,\n} from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/metrics-plugin/constants';\nimport type {\n Module,\n Compilation,\n MetricsOptionsWithDefaults,\n Filter,\n} from '@dd/metrics-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const getTimestamp = (timestamp?: number): number => {\n return Math.floor((timestamp || Date.now()) / 1000);\n};\n\nexport const validateOptions = (\n opts: OptionsWithDefaults,\n bundlerName: string,\n): MetricsOptionsWithDefaults => {\n const options = opts[CONFIG_KEY];\n\n const timestamp = getTimestamp(options?.timestamp);\n\n let prefix = options?.enableDefaultPrefix === false ? '' : `build.${bundlerName}`;\n if (options?.prefix) {\n prefix += prefix ? `.${options.prefix}` : options.prefix;\n }\n\n return {\n enableDefaultPrefix: true,\n enableTracing: false,\n filters: defaultFilters,\n tags: [],\n ...opts[CONFIG_KEY],\n timestamp,\n // Make it lowercase and remove any leading/closing dots.\n prefix: prefix.toLowerCase().replace(/(^\\.*|\\.*$)/g, ''),\n };\n};\n\nexport const getDefaultTags = (context: GlobalContext, configuredTags: string[]): string[] => {\n const defaultTags = [\n `bundler:${normalizeTagValue(context.bundler.name)}`,\n `plugin_version:${normalizeTagValue(context.version)}`,\n `site:${normalizeTagValue(context.auth.site)}`,\n ];\n\n if (context.build.metadata.name) {\n defaultTags.push(`build_name:${normalizeTagValue(context.build.metadata.name)}`);\n }\n\n if (context.build.metadata.version) {\n defaultTags.push(`build_version:${normalizeTagValue(context.build.metadata.version)}`);\n }\n\n return [...defaultTags, ...configuredTags];\n};\n\nconst getMetric = (metric: MetricToSend, defaultTags: string[], prefix: string): MetricToSend => {\n return {\n ...metric,\n tags: [...metric.tags, ...defaultTags],\n metric: prefix ? `${prefix}.${metric.metric}` : metric.metric,\n };\n};\n\nexport const getMetricsToSend = (\n metrics: Set<Metric>,\n timestamp: number,\n filters: Filter[],\n defaultTags: string[],\n prefix: string,\n): Set<MetricToSend> => {\n const metricsToSend: Set<MetricToSend> = new Set();\n\n // Apply filters\n for (const metric of metrics) {\n let processedMetrics: MetricToSend = { ...metric, toSend: true };\n if (filters?.length) {\n for (const filter of filters) {\n const result = filter({\n metric: processedMetrics.metric,\n type: processedMetrics.type,\n points: processedMetrics.points,\n tags: processedMetrics.tags,\n });\n\n if (result) {\n // Keep the toSend value from the original metric.\n processedMetrics = { ...result, toSend: processedMetrics.toSend };\n } else {\n // Do not modify the metric but mark it as not to send.\n processedMetrics.toSend = false;\n }\n }\n }\n\n // We wrap the metric after the filters\n // to ensure we apply the right prefix and default tags\n // without being impacted by the filters.\n metricsToSend.add(getMetric(processedMetrics, defaultTags, prefix));\n }\n\n // Count only the metrics that pass the filters\n const count = Array.from(metricsToSend).filter((m) => m.toSend).length;\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n points: [[timestamp, count + 1]],\n tags: [],\n toSend: true,\n },\n defaultTags,\n prefix,\n ),\n );\n\n return metricsToSend;\n};\n\nexport const getPluginName = (opts: string | { name: string }) =>\n typeof opts === 'string' ? opts : opts.name;\n\n// We want to ensure cwd ends with a slash.\nconst formatCwd = (cwd: string = ''): string => {\n return cwd.endsWith('/') ? cwd : `${cwd}/`;\n};\n\n// Format a module name by trimming the user's specific part out.\nexport const getDisplayName = (name: string, cwd?: string) => {\n let toReturn: string = name;\n const nameSplit: string[] = name.split(formatCwd(cwd));\n if (cwd && nameSplit.length) {\n toReturn = nameSplit.pop()!;\n }\n\n return (\n toReturn\n // Remove loaders query\n .split('!')\n .pop()!\n // Remove everything in front of /node_modules\n .replace(/(.*)?\\/node_modules\\//, '/node_modules/')\n // Remove any prefixing ../\n .replace(/^((\\.)*\\/)+/, '')\n );\n};\n\nexport const formatModuleName = (name: string, context?: string) =>\n name\n // Remove loaders query\n .split('!')\n .pop()!\n // Webpack store its modules with a relative path\n // let's do the same so we can integrate better with it.\n .replace(formatCwd(context), './');\n\nexport const getModulePath = (module: Module, compilation: Compilation) => {\n let path: string | undefined = module.userRequest;\n if (!path) {\n let issuer;\n if (compilation.moduleGraph && typeof compilation.moduleGraph.getIssuer === 'function') {\n issuer = compilation.moduleGraph.getIssuer(module);\n } else {\n issuer = module.issuer;\n }\n\n path = issuer?.userRequest;\n\n if (!path) {\n // eslint-disable-next-line no-underscore-dangle\n path = module._identifier?.split('!').pop();\n }\n }\n return path || 'unknown';\n};\n\n// Find the module name and format it the same way as webpack.\nexport const getModuleName = (module: Module, compilation: Compilation, context?: string) => {\n let name: string = module.name || module.userRequest;\n if (!name) {\n name = getModulePath(module, compilation);\n }\n return formatModuleName(name || 'no-name', context);\n};\n\n// Format the loader's name by extracting it from the query.\n// \"[...]/node_modules/babel-loader/lib/index.js\" => babel-loader\nconst formatLoaderName = (loader: string) =>\n loader.replace(/^.*\\/node_modules\\/(@[a-z0-9][\\w-.]+\\/[a-z0-9][\\w-.]*|[^/]+).*$/, '$1');\n\n// Find a module's loaders names and format them.\nexport const getLoaderNames = (module: Module) =>\n (module.loaders || []).map((l: any) => l.loader || l).map(formatLoaderName);\n\nexport const getValueContext = (args: any[]): ValueContext[] => {\n return args.map((arg) => ({\n type: arg?.constructor?.name ?? typeof arg,\n name: arg?.name,\n value: typeof arg === 'string' ? arg : undefined,\n }));\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Output,\n TimingsMap,\n TimingsReport,\n} from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\n// How many items do we show in the top lists.\nconst TOP = 5;\n// How long a path can be before we truncate it.\nconst MAX_VALUE_LENGTH = 60;\n\nconst numColor = chalk.bold.red;\nconst nameColor = chalk.bold.cyan;\n\ntype ValuesToPrint = { name: string; top: boolean; values: { name: string; value: string }[] };\n\ntype FileReport = {\n name: string;\n aggregatedSize?: number;\n size: number;\n dependencies: Set<string>;\n dependents: Set<string>;\n};\n\n// Sort a collection by attribute\nconst sortDesc = (attr: ((arg: any) => any) | string) => (a: any, b: any) => {\n let aVal;\n let bVal;\n\n if (typeof attr === 'function') {\n aVal = attr(a);\n bVal = attr(b);\n } else {\n aVal = a[attr];\n bVal = b[attr];\n }\n\n if (aVal > bVal) {\n return -1;\n } else if (aVal < bVal) {\n return 1;\n } else {\n return 0;\n }\n};\n\nexport const getGeneralValues = (context: GlobalContext): ValuesToPrint[] => {\n const valuesToPrint: ValuesToPrint = {\n name: 'General Numbers',\n values: [],\n top: false,\n };\n\n const nbModules = context.build.inputs ? context.build.inputs.length : 0;\n const nbAssets = context.build.outputs ? context.build.outputs.length : 0;\n const nbWarnings = context.build.warnings.length;\n const nbErrors = context.build.errors.length;\n const nbEntries = context.build.entries ? context.build.entries.length : 0;\n\n if (context.build.start) {\n valuesToPrint.values.push({\n name: 'Overhead duration',\n value: formatDuration(context.build.start - context.start),\n });\n }\n\n if (context.build.duration) {\n valuesToPrint.values.push({\n name: 'Build duration',\n value: formatDuration(context.build.duration),\n });\n }\n\n if (context.build.writeDuration) {\n valuesToPrint.values.push({\n name: 'Write duration',\n value: formatDuration(context.build.writeDuration),\n });\n }\n\n valuesToPrint.values.push(\n {\n name: 'Number of modules',\n value: nbModules.toString(),\n },\n {\n name: 'Number of assets',\n value: nbAssets.toString(),\n },\n {\n name: 'Number of entries',\n value: nbEntries.toString(),\n },\n {\n name: 'Number of warnings',\n value: nbWarnings.toString(),\n },\n {\n name: 'Number of errors',\n value: nbErrors.toString(),\n },\n );\n\n return [valuesToPrint];\n};\n\nconst getAssetsValues = (context: GlobalContext): ValuesToPrint[] => {\n const assetSizesToPrint: ValuesToPrint = {\n name: 'Asset size',\n values: (context.build.outputs || [])\n // We don't want to report on sourcemaps here.\n .filter((output) => output.type !== 'map')\n .sort(sortDesc((output: Output) => output.size))\n .map((output) => ({\n name: output.name,\n value: prettyBytes(output.size),\n })),\n top: true,\n };\n\n const entrySizesToPrint: ValuesToPrint = {\n name: 'Entry aggregated size',\n values: (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: prettyBytes(entry.size),\n })),\n top: true,\n };\n\n const entryModulesToPrint: ValuesToPrint = {\n name: 'Entry number of modules',\n values:\n (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: entry.inputs.length.toString(),\n })) || [],\n top: true,\n };\n\n return [assetSizesToPrint, entrySizesToPrint, entryModulesToPrint];\n};\n\nconst getModulesValues = (context: GlobalContext): ValuesToPrint[] => {\n const dependentsToPrint: ValuesToPrint = {\n name: `Module total dependents`,\n values: [],\n top: true,\n };\n\n const dependenciesToPrint: ValuesToPrint = {\n name: `Module total dependencies`,\n values: [],\n top: true,\n };\n\n const sizesToPrint: ValuesToPrint = {\n name: `Module size`,\n values: [],\n top: true,\n };\n\n const aggregatedSizesToPrint: ValuesToPrint = {\n name: `Module aggregated size`,\n values: [],\n top: true,\n };\n\n const dependencies: Set<FileReport> = new Set();\n\n // Build our collections.\n const serializedReport = serializeBuildReport(context.build);\n const inputs: Map<string, FileReport> = new Map();\n const fileDependencies: Map<string, Set<string>> = new Map();\n const fileDependents: Map<string, Set<string>> = new Map();\n\n for (const input of serializedReport.inputs || []) {\n // We don't want to report on sourcemaps here.\n if (input.type === 'map') {\n continue;\n }\n\n const dependenciesSet = new Set(input.dependencies);\n const dependentsSet = new Set(input.dependents);\n\n // Create the sets for all the dependencies.\n for (const dep of dependenciesSet) {\n if (!fileDependents.has(dep)) {\n fileDependents.set(dep, new Set());\n }\n fileDependents.get(dep)!.add(input.filepath);\n }\n\n // Create the sets for all the dependents.\n for (const dep of dependentsSet) {\n if (!fileDependencies.has(dep)) {\n fileDependencies.set(dep, new Set());\n }\n fileDependencies.get(dep)!.add(input.filepath);\n }\n\n if (fileDependencies.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependencies = fileDependencies.get(input.filepath)!;\n for (const dep of existingDependencies) {\n dependenciesSet.add(dep);\n }\n }\n\n if (fileDependents.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependents = fileDependents.get(input.filepath)!;\n for (const dep of existingDependents) {\n dependentsSet.add(dep);\n }\n }\n\n fileDependencies.set(input.filepath, dependenciesSet);\n fileDependents.set(input.filepath, dependentsSet);\n\n inputs.set(input.filepath, {\n name: input.name,\n size: input.size,\n dependencies: dependenciesSet,\n dependents: dependentsSet,\n });\n }\n\n for (const [filepath, input] of inputs) {\n const inputDependencies = fileDependencies.get(filepath) || new Set();\n const inputDependents = fileDependents.get(filepath) || new Set();\n\n // Aggregate size.\n let aggregatedSize = input.size;\n for (const dep of inputDependencies) {\n aggregatedSize += inputs.get(dep)?.size || 0;\n }\n\n dependencies.add({\n name: input.name,\n size: input.size,\n aggregatedSize,\n dependents: inputDependents,\n dependencies: inputDependencies,\n });\n }\n\n if (!dependencies.size) {\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint];\n }\n\n const dependenciesArray = Array.from(dependencies);\n // Sort by dependents, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependents.size));\n dependentsToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependents.size.toString(),\n }));\n // Sort by dependencies, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependencies.size));\n dependenciesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependencies.size.toString(),\n }));\n // Sort by size, biggest first\n dependenciesArray.sort(sortDesc('size'));\n sizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.size),\n }));\n // Sort by aggregated size, biggest first\n dependenciesArray.sort(sortDesc('aggregatedSize'));\n aggregatedSizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.aggregatedSize || file.size),\n }));\n\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint, aggregatedSizesToPrint];\n};\n\nconst getTimingValues = (name: string, timings?: TimingsMap): ValuesToPrint[] => {\n if (!timings || !timings.size) {\n return [];\n }\n\n const times = Array.from(timings.values());\n // Sort by duration, longest first\n times.sort(sortDesc('duration'));\n const durationsToPrint: ValuesToPrint = {\n name: `${name} duration`,\n values: times.map((module) => ({\n name: module.name,\n value: formatDuration(module.duration),\n })),\n top: true,\n };\n\n // Sort by increment, biggest first\n times.sort(sortDesc('increment'));\n const hitsToPrint: ValuesToPrint = {\n name: `${name} hits`,\n values: times.map((module) => ({\n name: module.name,\n value: module.increment.toString(),\n })),\n top: true,\n };\n\n return [durationsToPrint, hitsToPrint];\n};\n\nconst renderValues = (values: ValuesToPrint[]): string => {\n let outputString = '';\n\n const titlePadding = 4;\n const valuePadding = 4;\n\n // Cleaning and preparing out the groups.\n for (const group of values) {\n // Only keep the top values if requested.\n if (group.top && group.values.length >= TOP) {\n group.values = group.values.slice(0, TOP);\n group.name = `Top ${TOP} ${group.name}`;\n }\n\n // Truncate values' names when they are way too long.\n for (const value of group.values) {\n value.name = truncateString(value.name, MAX_VALUE_LENGTH);\n }\n }\n\n // Calculating the width of the columns.\n const maxTitleWidth = Math.max(...values.map((val) => val.name.length));\n const maxNameWidth = Math.max(...values.flatMap((val) => val.values.map((v) => v.name.length)));\n const maxValueWidth = Math.max(\n ...values.flatMap((val) => val.values.map((v) => v.value.length)),\n );\n const totalWidth = Math.max(\n maxTitleWidth + titlePadding,\n maxNameWidth + maxValueWidth + valuePadding,\n );\n\n // Composing the output.\n for (const group of values) {\n if (group.values.length === 0) {\n continue;\n }\n\n const titlePad = totalWidth - (group.name.length + titlePadding);\n\n outputString += `\\n== ${group.name} ${'='.repeat(titlePad)}=\\n`;\n\n for (const value of group.values) {\n const valuePad = maxValueWidth - value.value.length;\n outputString += ` [${numColor(value.value)}] ${' '.repeat(valuePad)}${nameColor(value.name)}\\n`;\n }\n }\n\n return outputString;\n};\n\nexport const outputTexts = (globalContext: GlobalContext, log: Logger, timings?: TimingsReport) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (timings) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', timings.modules));\n }\n\n valuesToPrint.push(...getModulesValues(globalContext));\n valuesToPrint.push(...getAssetsValues(globalContext));\n valuesToPrint.push(...getGeneralValues(globalContext));\n\n const outputString = renderValues(valuesToPrint);\n\n log.info(outputString);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { Logger, Metric, MetricToSend } from '@dd/core/types';\nimport chalk from 'chalk';\n\nexport const METRICS_API_PATH = 'api/v1/series';\n\nconst green = chalk.bold.green;\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; site: string },\n log: Logger,\n) => {\n if (!auth.apiKey) {\n log.info(`Won't send metrics to Datadog: missing API Key.`);\n return;\n }\n if (!metrics.size) {\n log.debug(`No metrics to send.`);\n return;\n }\n\n // Only send metrics that are to be sent.\n const metricsToSend: Metric[] = Array.from(metrics)\n .filter((metric) => metric.toSend)\n .map((metric) => {\n return {\n ...metric,\n toSend: undefined,\n };\n });\n\n const metricIterations: Map<string, number> = new Map();\n for (const metric of metricsToSend) {\n if (!metricIterations.has(metric.metric)) {\n metricIterations.set(metric.metric, 0);\n }\n metricIterations.set(metric.metric, metricIterations.get(metric.metric)! + 1);\n }\n\n const metricsNames = Array.from(metricIterations.entries())\n // Sort by metric name.\n .sort(([nameA], [nameB]) => nameA.localeCompare(nameB))\n .map(([name, count]) => `${name} - ${count}`);\n\n log.debug(`\nSending ${metricsToSend.length} metrics with configuration:\n - intake: ${green(`https://api.${auth.site}/${METRICS_API_PATH}`)}\n\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `https://api.${auth.site}/${METRICS_API_PATH}?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: metricsToSend } satisfies {\n series: Metric[];\n }),\n }),\n }).catch((e) => {\n log.error(`Error sending metrics ${e}`);\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing, Value } from '@dd/core/types';\nimport { formatModuleName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\nconst loadersMap: Map<string, Timing> = new Map();\nconst pluginsMap: TimingsMap = new Map();\nconst modulesMap: TimingsMap = new Map();\n\nexport const wrapPlugins = (build: PluginBuild, context: string) => {\n const plugins = build.initialOptions.plugins;\n if (plugins) {\n // We clone plugins so we don't pass modified options to other plugins.\n const initialPlugins = plugins.map((plugin) => {\n return {\n ...plugin,\n };\n });\n for (const plugin of plugins) {\n const oldSetup = plugin.setup;\n plugin.setup = async (esbuild) => {\n const newBuildObject = getNewBuildObject(esbuild, plugin.name, context);\n await oldSetup({\n ...newBuildObject,\n // Use non-modified plugins for other plugins\n initialOptions: { ...newBuildObject.initialOptions, plugins: initialPlugins },\n });\n };\n }\n }\n};\n\nconst getNewBuildObject = (\n build: PluginBuild,\n pluginName: string,\n context: string,\n): PluginBuild => {\n const newBuildObject: any = Object.assign({}, build);\n for (const fn of FN_TO_WRAP) {\n newBuildObject[fn] = async (opts: any, cb: any) => {\n const pluginTiming: Timing = pluginsMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n pluginTiming.events[fn] = pluginTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const isLoader = fn === 'onLoad';\n const initialFunction: any = build[fn];\n return initialFunction(opts, async (...args: any[]) => {\n const modulePath = formatModuleName(args[0].path, context);\n const moduleTiming: Timing = modulesMap.get(modulePath) || {\n name: modulePath,\n increment: 0,\n duration: 0,\n events: {},\n };\n moduleTiming.events[fn] = moduleTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const start = performance.now();\n\n try {\n return await cb(...args);\n } finally {\n const end = performance.now();\n const duration = end - start;\n const statsObject: Value = {\n start,\n end,\n duration,\n context: getValueContext(args),\n };\n\n pluginTiming.events[fn].values.push(statsObject);\n pluginTiming.duration += duration;\n pluginTiming.increment += 1;\n pluginsMap.set(pluginName, pluginTiming);\n\n moduleTiming.events[fn].values.push(statsObject);\n moduleTiming.duration += duration;\n moduleTiming.increment += 1;\n modulesMap.set(modulePath, moduleTiming);\n\n // Only if we're in a loader function.\n if (isLoader) {\n const loaderTiming: Timing = loadersMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n loaderTiming.events[fn] = loaderTiming.events[fn] || {\n name: fn,\n values: [],\n };\n loaderTiming.events[fn].values.push(statsObject);\n loaderTiming.duration += duration;\n loaderTiming.increment += 1;\n loadersMap.set(pluginName, loaderTiming);\n }\n }\n });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap, loaders: loadersMap });\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.buildRoot);\n timeWrap.end();\n build.onEnd(async (result: BuildResult) => {\n if (!result.metafile) {\n logger.warn(\"Missing metafile, can't proceed with modules data.\");\n return;\n }\n\n const timeResult = logger.time('getting plugins results');\n const { plugins, loaders, modules } = getPluginsResults();\n timeResult.end();\n\n await globalContext.asyncHook('timings', {\n tapables: plugins,\n loaders,\n modules,\n });\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing } from '@dd/core/types';\nimport { getDisplayName, getModuleName, getLoaderNames } from '@dd/metrics-plugin/common/helpers';\nimport type { Module, Event, Compilation } from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Loaders {\n constructor(cwd: string) {\n this.cwd = cwd;\n }\n cwd: string;\n started: { [key: string]: Event } = {};\n finished: Event[] = [];\n\n startModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n const loaders = getLoaderNames(module);\n\n if (!loaders.length) {\n // Keep a track of modules without a loader.\n loaders.push('no-loader');\n }\n\n // Store the event until the module is complete.\n this.started[moduleName] = {\n module: getDisplayName(moduleName),\n timings: {\n start: performance.now(),\n duration: 0,\n end: 0,\n },\n loaders,\n };\n }\n\n doneModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n // Get the event for this module.\n const event = this.started[moduleName];\n\n if (!event) {\n return;\n }\n\n event.timings.end = performance.now();\n event.timings.duration = event.timings.end - event.timings.start;\n\n // Store the event.\n this.finished.push(event);\n\n // Delete the entry so another import\n // of the same module can be also reported.\n delete this.started[moduleName];\n }\n\n getResults(): {\n modules: TimingsMap;\n loaders: TimingsMap;\n } {\n const loaders: Map<string, Timing> = new Map();\n const modules: Map<string, Timing> = new Map();\n for (const event of this.finished) {\n const duration = event.timings.end! - event.timings.start;\n\n // Aggregate module timings\n const moduleTiming = modules.get(event.module) || {\n name: event.module,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n const eventName = event.loaders.join(',');\n moduleTiming.events[eventName] = moduleTiming.events[eventName] || {\n name: eventName,\n values: [],\n };\n\n moduleTiming.events[eventName].values.push(event.timings);\n moduleTiming.increment += 1;\n moduleTiming.duration += duration;\n modules.set(event.module, moduleTiming);\n\n // Aggregate loader timings\n for (const loader of event.loaders) {\n const loaderTiming = loaders.get(loader) || {\n name: loader,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n loaderTiming.increment += 1;\n loaderTiming.duration += duration;\n loaders.set(loader, loaderTiming);\n }\n }\n\n return { loaders, modules };\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, ValueContext, TAP_TYPES, Timing } from '@dd/core/types';\nimport { getPluginName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n} from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Tapables {\n constructor(cwd: Tapables['cwd']) {\n this.cwd = cwd;\n }\n cwd: string;\n monitoredTaps: MonitoredTaps = {};\n tapables: Tapable[] = [];\n hooks: Hooks = {};\n timings: TimingsMap = new Map();\n ignoredHooks = [\n // This one triggers a DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK warning.\n 'normalModuleLoader',\n ];\n\n saveResult(\n type: TAP_TYPES,\n pluginName: string,\n hookName: string,\n context: ValueContext[],\n start: number,\n end: number,\n ) {\n const timing: Timing = this.timings.get(pluginName) || {\n name: pluginName,\n duration: 0,\n increment: 0,\n events: {},\n };\n if (!timing.events[hookName]) {\n timing.events[hookName] = {\n name: hookName,\n values: [],\n };\n }\n\n timing.events[hookName].values.push({\n start,\n end,\n duration: end - start,\n context,\n type,\n });\n timing.duration += end - start;\n timing.increment += 1;\n this.timings.set(pluginName, timing);\n }\n\n getResults(): TapablesResult {\n const timings = this.timings;\n\n // Aggregate the durations for each plugin.\n for (const [tapableName, tapable] of this.timings) {\n const timing = tapable;\n timing.duration = Object.values(tapable.events)\n .map((hookArray) =>\n hookArray.values.reduce((previous, current) => {\n return previous + current.end - current.start;\n }, 0),\n )\n .reduce((previous, current) => previous + current, 0);\n timings.set(tapableName, timing);\n }\n\n return {\n monitoredTaps: this.monitoredTaps,\n tapables: this.tapables,\n hooks: this.hooks,\n timings,\n };\n }\n\n getPromiseTapPatch(type: TAP_TYPES, fn: TapPromise, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n const cb = () => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n };\n // Save the result whether it succeeds or not.\n returnValue.then(cb, cb);\n return returnValue;\n };\n }\n\n getAsyncTapPatch(type: TAP_TYPES, fn: TapAsync, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n // Callback is the last argument.\n const originalCB = args.pop();\n const newCB = (...a: [any]) => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return originalCB(...a);\n };\n return fn.apply(this, [...args, newCB]);\n };\n }\n\n getDefaultTapPatch(type: TAP_TYPES, fn: Tap, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return returnValue;\n };\n }\n\n // Patch the tap so we can report its execution duration.\n getTapPatch(type: TAP_TYPES, fn: (args: any) => any, pluginName: string, hookName: string) {\n switch (type) {\n case 'promise':\n return this.getPromiseTapPatch(type, fn, pluginName, hookName);\n case 'async':\n return this.getAsyncTapPatch(type, fn, pluginName, hookName);\n case 'default':\n default:\n return this.getDefaultTapPatch(type, fn, pluginName, hookName);\n }\n }\n\n newTap(\n type: TAP_TYPES,\n hookName: string,\n originalTap: Tap | TapAsync | TapPromise,\n scope: any,\n ) {\n return (options: any, fn: (args: any) => any) => {\n const pluginName = getPluginName(options);\n const key = `${hookName}-${pluginName}`;\n if (this.monitoredTaps[key]) {\n // Since it's monitored, fn is already patched.\n return originalTap.call(scope, options, fn);\n }\n this.monitoredTaps[key] = true;\n const newFn = this.getTapPatch(type, fn, pluginName, hookName);\n return originalTap.call(scope, options, newFn);\n };\n }\n\n replaceTaps(hookName: string, hook: Hook) {\n // Cover three types of tap.\n hook.tap = this.newTap('default', hookName, hook.tap!, hook);\n hook.tapAsync = this.newTap('async', hookName, hook.tapAsync!, hook);\n hook.tapPromise = this.newTap('promise', hookName, hook.tapPromise!, hook);\n }\n\n patchHook(tapableName: string, hookName: string, hook: Hook) {\n // Webpack specific, these _fakeHook are not writable.\n // eslint-disable-next-line no-underscore-dangle\n if (hook._fakeHook) {\n return;\n }\n\n // Skip the current plugin.\n if (tapableName.includes(PLUGIN_NAME)) {\n return;\n }\n\n if (!this.hooks[tapableName]) {\n this.hooks[tapableName] = [];\n }\n\n if (this.hooks[tapableName].includes(hookName)) {\n return;\n }\n\n this.hooks[tapableName].push(hookName);\n this.replaceTaps(hookName, hook);\n }\n\n patchHooks(tapable: Tapable) {\n const name = tapable.constructor.name;\n const hooksToPatch = Object.keys(tapable.hooks).filter((hookName) => {\n // Skip the ignored hooks.\n if (this.ignoredHooks.includes(hookName)) {\n return false;\n }\n\n // Skip the already patched hooks.\n if (this.hooks[name]?.includes(hookName)) {\n return false;\n }\n\n return true;\n });\n\n for (const hookName of hooksToPatch) {\n this.patchHook(name, hookName, tapable.hooks[hookName]);\n }\n }\n\n checkNewHooks() {\n // We reparse hooks in case new ones arrived.\n for (const tapable of this.tapables) {\n this.patchHooks(tapable);\n }\n }\n\n // Let's navigate through all the hooks we can find.\n throughHooks(tapable: Tapable) {\n if (!this.tapables.includes(tapable)) {\n this.tapables.push(tapable);\n }\n\n this.patchHooks(tapable);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type { Compilation } from '@dd/metrics-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.buildRoot);\n const loaders = new Loaders(globalContext.buildRoot);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack and rspack reconciliation.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack and rspack reconciliation.\n compiler.hooks.thisCompilation.tap(HOOK_OPTIONS, (compilation: Compilation) => {\n const compilationTime = log.time('parse compilation hooks');\n tapables.throughHooks(compilation);\n compilationTime.end();\n\n // TODO: Use log.time() to measure modules.\n compilation.hooks.buildModule.tap(HOOK_OPTIONS, (module) => {\n loaders.startModule(module, compilation);\n });\n\n compilation.hooks.succeedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n\n // NOTE: compilation.hooks.failedModule is not available in rspack as of 1.2.8\n // https://rspack.dev/api/plugin-api/compilation-hooks\n if (compilation.hooks.failedModule) {\n compilation.hooks.failedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n }\n });\n\n // We're losing some tracing from plugins by using `afterEmit` instead of `done` but\n // it allows us to centralize the common process better.\n // TODO: Use custom hooks to make this more reliable and not blocked by a race condition.\n compiler.hooks.afterEmit.tapPromise(HOOK_OPTIONS, async () => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n await globalContext.asyncHook('timings', {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\n });\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, GetPlugins, Metric, PluginOptions, TimingsReport } from '@dd/core/types';\n\nimport { initializeMetricsCollector } from './collector';\nimport { getUniversalMetrics, getPluginMetrics, getLoaderMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getDefaultTags, getMetricsToSend, getTimestamp, validateOptions } from './common/helpers';\nimport { outputTexts } from './common/output/text';\nimport { sendMetrics } from './common/sender';\nimport { PLUGIN_NAME, CONFIG_KEY } from './constants';\nimport { getEsbuildPlugin } from './esbuild-plugin';\nimport type { Filter, MetricsOptions } from './types';\nimport { getWebpackPlugin } from './webpack-plugin';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n filters: defaultFilters,\n};\n\nexport type types = {\n Filter: Filter;\n Metric: Metric;\n MetricsOptions: MetricsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context, stores }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n initializeMetricsCollector(context, stores);\n\n const validatedOptions = validateOptions(options, context.bundler.name);\n const plugins: PluginOptions[] = [];\n\n // Webpack and Esbuild specific plugins.\n // LEGACY\n const legacyPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: getEsbuildPlugin(context, log),\n webpack: getWebpackPlugin(context),\n rspack: getWebpackPlugin(context),\n };\n\n const timeBuild = log.time('build', { start: false });\n // Identify if we need the legacy plugin.\n const needLegacyPlugin =\n validatedOptions.enableTracing &&\n ['esbuild', 'webpack', 'rspack'].includes(context.bundler.name);\n let timingsReport: TimingsReport | undefined;\n let buildReport: BuildReport;\n\n const getMetricsToSendFromCollectedMetrics = () => {\n const metrics = new Set(stores.metrics);\n stores.metrics.clear();\n const defaultTags = getDefaultTags(context, validatedOptions.tags);\n\n return getMetricsToSend(\n metrics,\n validatedOptions.timestamp,\n validatedOptions.filters,\n defaultTags,\n validatedOptions.prefix,\n );\n };\n\n const sendCollectedMetrics = async () => {\n if (!stores.metrics.size) {\n return;\n }\n\n const timeMetrics = log.time(`aggregating collected metrics`);\n const metricsToSend = getMetricsToSendFromCollectedMetrics();\n\n await context.asyncHook('metrics', metricsToSend);\n timeMetrics.end();\n\n const timeSend = log.time('sending collected metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n const computeMetrics = async () => {\n context.build.end = Date.now();\n context.build.duration = context.build.end - context.build.start!;\n context.build.writeDuration = context.build.end - realBuildEnd;\n\n const timeMetrics = log.time(`aggregating metrics`);\n const timestamp = validatedOptions.timestamp;\n\n const timeUniversal = log.time(`aggregate universal metrics`);\n const universalMetrics = getUniversalMetrics(buildReport, timestamp);\n timeUniversal.end();\n const timePlugin = log.time(`aggregate plugins metrics`);\n const pluginMetrics = getPluginMetrics(timingsReport?.tapables, timestamp);\n timePlugin.end();\n const timeLoader = log.time(`aggregate loaders metrics`);\n const loaderMetrics = getLoaderMetrics(timingsReport?.loaders, timestamp);\n timeLoader.end();\n\n const allMetrics = new Set([...universalMetrics, ...pluginMetrics, ...loaderMetrics]);\n const defaultTags = getDefaultTags(context, validatedOptions.tags);\n\n const metricsToSend = getMetricsToSend(\n allMetrics,\n timestamp,\n validatedOptions.filters,\n defaultTags,\n validatedOptions.prefix,\n );\n\n await context.asyncHook('metrics', metricsToSend);\n\n timeMetrics.end();\n\n const timeReport = log.time('outputing report');\n outputTexts(context, log, timingsReport);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-metrics-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n // Set the timestamp to the build start if not provided.\n if (!options[CONFIG_KEY]?.timestamp) {\n validatedOptions.timestamp = getTimestamp(context.build.start);\n }\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n async timings(timings) {\n timingsReport = timings;\n // Once we have both reports, we can compute the metrics.\n if (buildReport) {\n await computeMetrics();\n }\n },\n\n async buildReport(report) {\n buildReport = report;\n // Once we have both reports (or we don't need the legacy plugin),\n // we can compute the metrics.\n if (timingsReport || !needLegacyPlugin) {\n await computeMetrics();\n }\n },\n async flush() {\n await sendCollectedMetrics();\n },\n };\n\n if (validatedOptions.enableTracing) {\n plugins.push(legacyPlugin);\n }\n\n plugins.push(universalPlugin);\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, Metric, TimingsMap } from '@dd/core/types';\n\nexport const getUniversalMetrics = (buildReport: BuildReport, timestamp: number): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n const inputs = buildReport.inputs || [];\n const outputs = buildReport.outputs || [];\n const entries = buildReport.entries || [];\n const nbWarnings = buildReport.warnings.length;\n const nbErrors = buildReport.errors.length;\n const duration = buildReport.duration;\n\n // Create some indexes to speed up the process.\n const entriesPerInput = new Map<string, string[]>();\n const assetsPerInput = new Map<string, string[]>();\n const entriesPerAsset = new Map<string, string[]>();\n\n for (const entry of entries) {\n for (const input of entry.inputs) {\n if (!entriesPerInput.has(input.filepath)) {\n entriesPerInput.set(input.filepath, []);\n }\n entriesPerInput.get(input.filepath)!.push(entry.name);\n }\n for (const output of entry.outputs) {\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (!entriesPerAsset.has(cleanAssetName)) {\n entriesPerAsset.set(cleanAssetName, []);\n }\n entriesPerAsset.get(cleanAssetName)!.push(entry.name);\n }\n }\n\n for (const output of outputs) {\n for (const input of output.inputs) {\n if (!assetsPerInput.has(input.filepath)) {\n assetsPerInput.set(input.filepath, []);\n }\n assetsPerInput.get(input.filepath)!.push(output.name);\n }\n }\n\n // Counts\n metrics\n .add({\n metric: 'assets.count',\n type: 'count',\n points: [[timestamp, outputs.length]],\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n points: [[timestamp, entries.length]],\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n points: [[timestamp, nbErrors]],\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n points: [[timestamp, inputs.length]],\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n points: [[timestamp, nbWarnings]],\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n points: [[timestamp, duration]],\n tags: [],\n });\n }\n\n // Modules\n for (const input of inputs) {\n const tags = [`moduleName:${input.name}`, `moduleType:${input.type}`];\n if (entriesPerInput.has(input.filepath)) {\n tags.push(\n ...entriesPerInput\n .get(input.filepath)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n\n if (assetsPerInput.has(input.filepath)) {\n tags.push(\n ...assetsPerInput.get(input.filepath)!.map((assetName) => `assetName:${assetName}`),\n );\n }\n metrics\n .add({\n metric: 'modules.size',\n type: 'size',\n points: [[timestamp, input.size]],\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n points: [[timestamp, input.dependencies.size]],\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n points: [[timestamp, input.dependents.size]],\n tags,\n });\n }\n\n // Assets\n for (const output of outputs) {\n const tags = [`assetName:${output.name}`, `assetType:${output.type}`];\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (entriesPerAsset.has(cleanAssetName)) {\n tags.push(\n ...entriesPerAsset\n .get(cleanAssetName)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n metrics\n .add({\n metric: 'assets.size',\n type: 'size',\n points: [[timestamp, output.size]],\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n points: [[timestamp, output.inputs.length]],\n tags,\n });\n }\n\n // Entries\n for (const entry of entries) {\n const tags = [`entryName:${entry.name}`];\n metrics\n .add({\n metric: 'entries.size',\n type: 'size',\n points: [[timestamp, entry.size]],\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n points: [[timestamp, entry.inputs.length]],\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n points: [[timestamp, entry.outputs.length]],\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const getPluginMetrics = (\n plugins: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!plugins) {\n return metrics;\n }\n\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n points: [[timestamp, plugins.size]],\n tags: [],\n });\n\n for (const plugin of plugins.values()) {\n let pluginDuration = 0;\n let pluginCount = 0;\n\n for (const hook of Object.values(plugin.events)) {\n let hookDuration = 0;\n pluginCount += hook.values.length;\n for (const v of hook.values) {\n const duration = v.end - v.start;\n hookDuration += duration;\n pluginDuration += duration;\n }\n metrics\n .add({\n metric: 'plugins.hooks.duration',\n type: 'duration',\n points: [[timestamp, hookDuration]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n points: [[timestamp, hook.values.length]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n });\n }\n\n metrics\n .add({\n metric: 'plugins.duration',\n type: 'duration',\n points: [[timestamp, pluginDuration]],\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n points: [[timestamp, pluginCount]],\n tags: [`pluginName:${plugin.name}`],\n });\n }\n\n return metrics;\n};\n\nexport const getLoaderMetrics = (\n loaders: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!loaders) {\n return metrics;\n }\n\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n points: [[timestamp, loaders.size]],\n tags: [],\n });\n\n for (const loader of loaders.values()) {\n metrics\n .add({\n metric: 'loaders.duration',\n type: 'duration',\n points: [[timestamp, loader.duration]],\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n points: [[timestamp, loader.increment]],\n tags: [`loaderName:${loader.name}`],\n });\n }\n\n return metrics;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'output' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-output-plugin' as const;\nexport const FILE_KEYS = [\n 'build',\n 'bundler',\n 'dependencies',\n 'errors',\n 'logs',\n 'metrics',\n 'timings',\n 'warnings',\n] as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Options } from '@dd/core/types';\n\nimport { CONFIG_KEY } from './constants';\nimport type { FileKey, OutputOptions, OutputOptionsWithDefaults } from './types';\n\n// Sanitize the output path.\nconst sanitizeOutputPath = (key: FileKey, value: boolean | string) => {\n if (typeof value === 'string') {\n // Ensure we end with the correct extension.\n return value.replace(/(\\.json)?$/, '.json');\n }\n\n // Transform the value into a path.\n return value === true ? `${key}.json` : value;\n};\n\nconst validateFilesOptions = (\n files: OutputOptions['files'],\n): OutputOptionsWithDefaults['files'] => {\n // If no files object is provided, we'll output all files.\n const defaultValue = typeof files === 'undefined';\n\n const validatedFiles: OutputOptionsWithDefaults['files'] = {\n // Listing everything to keep TS happy.\n build: sanitizeOutputPath('build', files?.build ?? defaultValue),\n bundler: sanitizeOutputPath('bundler', files?.bundler ?? defaultValue),\n dependencies: sanitizeOutputPath('dependencies', files?.dependencies ?? defaultValue),\n errors: sanitizeOutputPath('errors', files?.errors ?? defaultValue),\n logs: sanitizeOutputPath('logs', files?.logs ?? defaultValue),\n metrics: sanitizeOutputPath('metrics', files?.metrics ?? defaultValue),\n timings: sanitizeOutputPath('timings', files?.timings ?? defaultValue),\n warnings: sanitizeOutputPath('warnings', files?.warnings ?? defaultValue),\n };\n\n return validatedFiles;\n};\n\n// Deal with validation and defaults here.\nexport const validateOptions = (options: Options): OutputOptionsWithDefaults => {\n return {\n path: './',\n ...options[CONFIG_KEY],\n files: validateFilesOptions(options[CONFIG_KEY]?.files),\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 { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport type { GetPlugins, Logger, PluginOptions } from '@dd/core/types';\nimport path from 'path';\nimport type { OutputBundle } from 'rollup';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { FileKey, FileValue, OutputOptions } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n OutputOptions: OutputOptions;\n};\n\nconst getXpackPlugin =\n (\n log: Logger,\n write: (getStats: () => any) => void,\n ): PluginOptions['webpack'] & PluginOptions['rspack'] =>\n (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\n write(() => {\n const statsTimer = log.time('stats serialization');\n const statsJson = stats.toJson({\n all: false,\n assets: true,\n children: true,\n chunks: true,\n chunkGroupAuxiliary: true,\n chunkGroupChildren: true,\n chunkGroups: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n relatedAssets: true,\n warnings: true,\n // These two add a massive amount of time to the serialization on big builds.\n reasons: false,\n chunkModules: false,\n });\n statsTimer.end();\n return statsJson;\n });\n });\n };\n\nconst getRollupPlugin = (\n write: (getOutputs: () => OutputBundle[]) => void,\n): PluginOptions['rollup'] & PluginOptions['vite'] => {\n const outputs: Set<OutputBundle> = new Set();\n return {\n buildStart() {\n // Clear set on build start.\n outputs.clear();\n },\n writeBundle(opts, bundle) {\n outputs.add(bundle);\n },\n closeBundle() {\n write(() => Array.from(outputs));\n },\n };\n};\n\nexport const getFilePath = (outDir: string, pathOption: string, filename: string): string => {\n // If we have an absolute path, we use it as is.\n const outputPath = path.isAbsolute(pathOption)\n ? pathOption\n : // Otherwise, we resolve it relative to the bundler output directory.\n path.resolve(outDir, pathOption);\n return path.resolve(outputPath, filename);\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options);\n\n const writeFile = (name: FileKey, data: any) => {\n const fileValue: FileValue = validatedOptions.files[name];\n if (!data || fileValue === false) {\n return;\n }\n\n const queuedWrite = async () => {\n const timeWrite = log.time(`output ${fileValue}`);\n const filePath = getFilePath(context.bundler.outDir, validatedOptions.path, fileValue);\n let error: unknown;\n\n try {\n const dataToWrite = typeof data === 'function' ? await data() : data;\n await outputJson(filePath, dataToWrite);\n } catch (e) {\n error = e;\n }\n\n if (error) {\n log.error(`Failed writing ${fileValue}: ${error}`);\n } else {\n log.debug(`Wrote \"./${path.relative(context.buildRoot, filePath)}\"`);\n }\n\n timeWrite.end();\n };\n // Do not make the file creations blocking.\n context.queue(queuedWrite());\n };\n\n return [\n {\n name: PLUGIN_NAME,\n buildReport(report) {\n const timeSerialization = log.time(`serialize report`);\n const serializedReport = serializeBuildReport(report);\n timeSerialization.end();\n writeFile('build', {\n bundler: serializedReport.bundler,\n metadata: serializedReport.metadata,\n start: serializedReport.start,\n end: serializedReport.end,\n duration: serializedReport.duration,\n writeDuration: serializedReport.writeDuration,\n entries: serializedReport.entries,\n outputs: serializedReport.outputs,\n });\n writeFile('logs', serializedReport.logs);\n writeFile('timings', serializedReport.timings);\n writeFile('dependencies', serializedReport.inputs);\n writeFile('errors', serializedReport.errors);\n writeFile('warnings', serializedReport.warnings);\n },\n metrics(metrics) {\n writeFile('metrics', () => Array.from(metrics));\n },\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n writeFile('bundler', result.metafile);\n });\n },\n },\n rspack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n rollup: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n vite: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n webpack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\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 { createHash } from 'crypto';\n\nconst VARIANT_CHARS = ['8', '9', 'a', 'b'] as const;\n\n// SHA-256(input) truncated to 128 bits → deterministic UUID-v4-shaped identifier.\n// SHA-256 is used instead of MD5 for FIPS 140-2/3 compliance.\nexport const stringToUUID = (input: string): string => {\n const hash = createHash('sha256').update(input).digest('hex').slice(0, 32);\n const withVersion = `${hash.slice(0, 12)}4${hash.slice(13)}`;\n const variantIndex = withVersion.charCodeAt(16) % 4;\n const withVariant = `${withVersion.slice(0, 16)}${VARIANT_CHARS[variantIndex]}${withVersion.slice(17)}`;\n return [\n withVariant.slice(0, 8),\n withVariant.slice(8, 12),\n withVariant.slice(12, 16),\n withVariant.slice(16, 20),\n withVariant.slice(20, 32),\n ].join('-');\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 { ChunkInfo } from '@dd/core/types';\nimport { randomUUID } from 'crypto';\n\nimport { stringToUUID } from './debugId';\nimport type { SourceCodeContextOptions } from './types';\n\nexport const DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE = 'DD_SOURCE_CODE_CONTEXT' as const;\n\n// The source code context snippet - single injection with function definition and call\n// SSR-safe: checks window before accessing, never throws\n//\n// Unminified version:\n// (function(c, n) {\n// try {\n// if (typeof window === 'undefined') return;\n// var w = window,\n// m = w[n] = w[n] || {},\n// s = new Error().stack;\n// s && (m[s] = c)\n// } catch (e) {}\n// })(context, variableName);\n\ntype SourceCodeContext = {\n service?: string;\n version?: string;\n ddDebugId?: string;\n};\n\nexport type SourceCodeContextSnippet = {\n code: string;\n debugId?: string;\n};\n\nexport const getSourceCodeContextSnippet = (\n contextOptions: SourceCodeContextOptions,\n chunk?: ChunkInfo,\n): SourceCodeContextSnippet => {\n const context: SourceCodeContext = {\n service: contextOptions.service,\n version: contextOptions.version,\n };\n\n if (contextOptions.debugId) {\n // Compute deterministic debug IDs whenever possible preventing the backend from storing duplicate source maps for identical build\n //\n // The `dd` prefix in `ddDebugId` allows upload tools (for example, datadog-ci) to reliably locate the\n // debug ID with a regex and send it as upload metadata alongside the source map.\n context.ddDebugId = chunk ? stringToUUID(chunk.sourceOrHash) : randomUUID();\n }\n\n const code = `(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(context)},${JSON.stringify(DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE)});`;\n\n return { code, debugId: context.ddDebugId };\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-rum-privacy-plugin' as const;\nexport const PRIVACY_HELPERS_FILE_NAME = 'privacy-helpers';\nexport const PRIVACY_HELPERS_MODULE_ID = `\\0datadog:${PRIVACY_HELPERS_FILE_NAME}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { NativeBuildContext } from 'unplugin';\n\nimport { PLUGIN_NAME } from './constants';\nimport { buildTransformOptions } from './transform';\nimport type { PrivacyOptionsWithDefaults } from './types';\n\nfunction getInputSourceMap(nativeBuildContext: NativeBuildContext | undefined): string | undefined {\n // Only rspack and webpack expose the input source map. Beyond that, we wouldn't want\n // to process it on other bundlers, because they automatically merge the source maps\n // produced by chained loaders.\n if (nativeBuildContext?.framework !== 'rspack' && nativeBuildContext?.framework !== 'webpack') {\n return undefined;\n }\n\n switch (typeof nativeBuildContext.inputSourceMap) {\n case 'undefined': // There's no input source map.\n return undefined;\n case 'string': // There's an input source map in serialized form.\n return nativeBuildContext.inputSourceMap;\n default: // There's an input source map in parsed form; we need to serialize it.\n return JSON.stringify(nativeBuildContext.inputSourceMap);\n }\n}\n\nexport const getPrivacyPlugin = (\n pluginOptions: PrivacyOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n\n const transformOptions = buildTransformOptions(\n pluginOptions.helperCodeExpression,\n context.bundler.name,\n );\n let dictionaryEntryCount = 0;\n let fileCount = 0;\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: pluginOptions.include,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n try {\n const map = getInputSourceMap(this.getNativeBuildContext?.());\n const result = instrument({ id, code, map }, transformOptions);\n if (result.privacyDictionarySize === 0) {\n return {\n // This should be the same as the result from js-instrumentation-wasm\n // returning the original code only to make it explicit for debugging purposes\n code,\n };\n }\n dictionaryEntryCount += result.privacyDictionarySize;\n fileCount++;\n return result;\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n buildEnd: () => {\n log.debug(\n `Privacy dictionary will include ${dictionaryEntryCount} entries across ${fileCount} files`,\n {\n forward: true,\n context: {\n dictionaryEntryCount,\n fileCount,\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 { InstrumentationOptions } from '@datadog/js-instrumentation-wasm';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(\n helperCodeExpression: string,\n bundlerName: string,\n): InstrumentationOptions {\n const transformOptions: InstrumentationOptions = {\n privacy: {\n addToDictionaryHelper: {\n expression: {\n code: helperCodeExpression,\n },\n },\n },\n };\n if (['esbuild', 'webpack', 'rspack'].includes(bundlerName)) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n return transformOptions;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { GlobalContext, InjectedValue } from '@dd/core/types';\n\nimport type { RumOptionsWithDefaults, RumOptionsWithSdk } from './types';\n\ntype RumAppResponse = {\n data: {\n attributes: {\n client_token: string;\n };\n };\n};\n\nconst getContent = (opts: RumOptionsWithDefaults) => {\n return `DD_RUM.init({${JSON.stringify(opts.sdk).replace(/(^{|}$)/g, '')}});\n`;\n};\n\nexport const getInjectionValue = (\n options: RumOptionsWithSdk,\n context: GlobalContext,\n): InjectedValue => {\n const sdkOpts = options.sdk;\n // We already have the clientToken, we can inject it directly.\n if (sdkOpts.clientToken) {\n return getContent(options);\n }\n\n // Let's try and fetch the clientToken from the API.\n if (!context.auth.apiKey || !context.auth.appKey) {\n throw new Error(\n 'Missing \"auth.apiKey\" and/or \"auth.appKey\" to fetch \"rum.sdk.clientToken\".',\n );\n }\n\n // Return the value as an async function so it gets resolved during buildStart.\n return async () => {\n let clientToken: string;\n try {\n // Fetch the client token from the API.\n const appResponse = await doRequest<RumAppResponse>({\n url: `https://api.${context.auth.site}/api/v2/rum/applications/${sdkOpts.applicationId}`,\n type: 'json',\n auth: context.auth,\n });\n\n clientToken = appResponse.data?.attributes?.client_token;\n } catch (e: any) {\n // Could not fetch the clientToken.\n // Let's crash the build.\n throw new Error(`Could not fetch the clientToken: ${e.message}`);\n }\n\n // Still no clientToken.\n if (!clientToken) {\n throw new Error('Missing clientToken in the API response.');\n }\n\n return getContent({\n ...options,\n sdk: {\n clientToken,\n ...sdkOpts,\n },\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options, OptionsWithDefaults } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type {\n RumOptions,\n RumOptionsWithDefaults,\n SDKOptionsWithDefaults,\n SourceCodeContextOptions,\n} from './types';\n\nexport const validateOptions = (\n options: OptionsWithDefaults,\n log: Logger,\n): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options);\n const sourceCodeContextResults = validateSourceCodeContextOptions(options);\n\n errors.push(...sdkResults.errors);\n errors.push(...privacyResults.errors);\n errors.push(...sourceCodeContextResults.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 ...options[CONFIG_KEY],\n sdk: undefined,\n privacy: undefined,\n sourceCodeContext: undefined,\n };\n\n // Fill in the defaults.\n if (sdkResults.config) {\n toReturn.sdk = sdkResults.config;\n }\n\n if (privacyResults.config) {\n toReturn.privacy = privacyResults.config;\n\n log.debug(\n `datadog-rum-privacy plugin options: ${JSON.stringify(toReturn.privacy, (_, value) => {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n })}`,\n { forward: true },\n );\n }\n\n if (sourceCodeContextResults.config) {\n toReturn.sourceCodeContext = sourceCodeContextResults.config;\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SDKOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SDKOptionsWithDefaults> = {\n errors: [],\n };\n if (!validatedOptions.sdk) {\n return toReturn;\n }\n\n // Validate the configuration.\n if (!validatedOptions.sdk.applicationId) {\n toReturn.errors.push(`Missing ${red('applicationId')} in the SDK configuration.`);\n }\n\n // Check if we have all we need to fetch the client token if necessary.\n if ((!options.auth.apiKey || !options.auth.appKey) && !validatedOptions.sdk.clientToken) {\n toReturn.errors.push(\n `Missing ${red('\"auth.apiKey\"')} and/or ${red('\"auth.appKey\"')} to fetch missing client token.`,\n );\n }\n\n const sdkWithDefault: SDKOptionsWithDefaults = {\n applicationId: 'unknown_application_id',\n allowUntrustedEvents: false,\n compressIntakeRequests: false,\n defaultPrivacyLevel: 'mask',\n enablePrivacyForActionName: false,\n sessionReplaySampleRate: 0,\n sessionSampleRate: 100,\n silentMultipleInit: false,\n site: options.auth.site || 'datadoghq.com',\n startSessionReplayRecordingManually: false,\n storeContextsAcrossPages: false,\n telemetrySampleRate: 20,\n traceSampleRate: 100,\n trackingConsent: 'granted',\n trackLongTasks: false,\n trackResources: false,\n trackUserInteractions: false,\n trackViewsManually: false,\n };\n\n // Save the config.\n toReturn.config = {\n ...sdkWithDefault,\n ...validatedOptions.sdk,\n };\n\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOptionsWithDefaults> => {\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<PrivacyOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.privacy) {\n const privacyWithDefault: PrivacyOptionsWithDefaults = {\n // Exclude dependencies and preval files from being transformed. Files starting with\n // special characters are likely to be virtual libraries and are excluded to avoid loading them.\n exclude: [/\\/node_modules\\//, /\\.preval\\./, /^[!@#$%^&*()=+~`-]/],\n include: [/\\.(?:c|m)?(?:j|t)sx?$/],\n addToDictionaryFunctionName: '$',\n helperCodeExpression: `/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()`,\n };\n\n toReturn.config = {\n ...privacyWithDefault,\n ...validatedOptions.privacy,\n };\n }\n\n return toReturn;\n};\n\nexport const validateSourceCodeContextOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SourceCodeContextOptions> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SourceCodeContextOptions> = {\n errors: [],\n };\n\n if (!validatedOptions.sourceCodeContext) {\n return toReturn;\n }\n\n const cfg: SourceCodeContextOptions = validatedOptions.sourceCodeContext;\n\n if (!cfg?.debugId && (!cfg?.service || typeof cfg.service !== 'string')) {\n toReturn.errors.push(`Missing ${red('\"rum.sourceCodeContext.service\"')}.`);\n }\n\n // Resolve `version`: prefer the plugin-specific option, then fall back to\n // the shared top-level `metadata.version`. This keeps `metadata.version`\n // as the single canonical place to declare the deployed build identifier.\n toReturn.config = {\n ...cfg,\n version: cfg.version || options.metadata?.version,\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 type { RumInitConfiguration, RumPublicApi } from './browserSdkTypes';\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { getSourceCodeContextSnippet } from './getSourceCodeContextSnippet';\nimport { getPrivacyPlugin } from './privacy';\nimport { getInjectionValue } from './sdk';\nimport type { RumOptions, RumOptionsWithSdk } 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 RumOptions: RumOptions;\n RumPublicApi: RumPublicApi;\n RumInitConfiguration: RumInitConfiguration;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options, log);\n const plugins: PluginOptions[] = [];\n const sourceCodeContext = validatedOptions.sourceCodeContext;\n\n if (sourceCodeContext) {\n context.inject({\n type: 'code',\n position: InjectPosition.BEFORE,\n injectIntoAllChunks: true,\n value: (chunk) => {\n // The debug_id is embedded directly in the returned code (see\n // getSourceCodeContextSnippet.ts); error-tracking reads it back out of the\n // built file's content at upload time, so it doesn't need to be tracked here.\n const { code } = getSourceCodeContextSnippet(sourceCodeContext, chunk);\n return code;\n },\n });\n }\n\n // NOTE: These files are built from \"@dd/tools/rollupConfig.mjs\" and available in the distributed package.\n if (validatedOptions.sdk) {\n // Inject the SDK from the CDN.\n context.inject({\n type: 'file',\n // Using MIDDLE otherwise it's not executed in context.\n position: InjectPosition.MIDDLE,\n // This file is being built alongside the bundler plugin.\n value: path.join(__dirname, './rum-browser-sdk.js'),\n });\n\n // Inject the SDK Initialization.\n context.inject({\n type: 'code',\n position: InjectPosition.MIDDLE,\n value: getInjectionValue(validatedOptions as RumOptionsWithSdk, context),\n });\n }\n\n if (validatedOptions.privacy) {\n // Add the privacy plugin.\n context.inject({\n type: 'file',\n position: InjectPosition.BEFORE,\n value: path.join(__dirname, './privacy-helpers.js'),\n });\n const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n plugins.push(privacyPlugin);\n }\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-analytics-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getAnalyticsPlugins: GetInternalPlugins = ({ context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const buildStartFn = async () => {\n try {\n await context.sendLog({\n message: 'Build started',\n context: {\n plugins: context.pluginNames,\n },\n });\n } catch (e: unknown) {\n // We don't want to break anything in case of error.\n log.debug(`Could not submit data to Datadog: ${e}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n async buildStart() {\n // Only send logs in production.\n if (context.env !== 'production') {\n return;\n }\n\n // Use the queue so it doesn't block the build process.\n context.queue(buildStartFn());\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-async-queue-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME };\n\nexport const getAsyncQueuePlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context, stores } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const errors: string[] = [];\n\n // Initialize the queue function\n context.queue = (promise: Promise<any>) => {\n // Wrap the promise to catch errors immediately\n const wrappedPromise = promise.catch((error: any) => {\n errors.push(error.message || error.toString());\n });\n stores.queue.push(wrappedPromise);\n };\n\n return [\n {\n name: PLUGIN_NAME,\n asyncTrueEnd: async () => {\n // Await for all promises to finish processing.\n await Promise.all(stores.queue);\n if (errors.length > 0) {\n log.error(\n `Error occurred while processing async queue:\\n ${errors.join('\\n ')}`,\n );\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BundlerName, GlobalContext, Logger, ResolvedEntry } from '@dd/core/types';\nimport type { PluginBuild } from 'esbuild';\nimport { glob } from 'glob';\n\n// https://esbuild.github.io/api/#glob-style-entry-points\n// Exported only for testing purposes.\nexport const getAllEntryFiles = (filepath: string): string[] => {\n if (!filepath.includes('*')) {\n return [filepath];\n }\n\n const files = glob.sync(filepath);\n return files;\n};\n\n// Parse, resolve and return all the entries of esbuild.\nexport const getEsbuildEntries = async (\n build: PluginBuild,\n context: GlobalContext,\n log: Logger,\n): Promise<ResolvedEntry[]> => {\n const entries: { name?: string; resolved: string; original: string }[] = [];\n const entryPoints = build.initialOptions.entryPoints;\n const entryPaths: { name?: string; path: string }[] = [];\n const resolutionErrors: string[] = [];\n\n if (Array.isArray(entryPoints)) {\n for (const entry of entryPoints) {\n const fullPath = entry && typeof entry === 'object' ? entry.in : entry;\n entryPaths.push({ path: fullPath });\n }\n } else if (entryPoints && typeof entryPoints === 'object') {\n entryPaths.push(\n ...Object.entries(entryPoints).map(([name, filepath]) => ({ name, path: filepath })),\n );\n }\n\n // Resolve all the paths.\n const proms = entryPaths\n .flatMap((entry) =>\n getAllEntryFiles(entry.path).map<[{ name?: string; path: string }, string]>((p) => [\n entry,\n p,\n ]),\n )\n .map(async ([entry, p]) => {\n const result = await build.resolve(p, {\n kind: 'entry-point',\n resolveDir: context.buildRoot,\n });\n\n if (result.errors.length) {\n resolutionErrors.push(...result.errors.map((e) => e.text));\n }\n\n if (result.path) {\n // Store them for later use.\n entries.push({\n name: entry.name,\n resolved: result.path,\n original: entry.path,\n });\n }\n });\n\n for (const resolutionError of resolutionErrors) {\n log.error(resolutionError);\n }\n\n await Promise.all(proms);\n return entries;\n};\n\n// From a bundler's name, is it part of the \"xpack\" family?\nexport const isXpack = (bundlerName: BundlerName) => ['rspack', 'webpack'].includes(bundlerName);\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\n// Will match any last part of a path after a dot or slash and is a word character.\nconst EXTENSION_RX = /\\.(?!.*(?:\\.|\\/|\\\\))(\\w{1,})/g;\n\n// Will match any type of query characters.\n// \"?\" or \"%3F\" (url encoded \"?\") or \"|\"\nconst QUERY_RX = /(\\?|%3F|\\|)+/gi;\n\nconst getExtension = (filepath: string) => {\n // Reset RX first.\n EXTENSION_RX.lastIndex = 0;\n return EXTENSION_RX.exec(filepath)?.[1];\n};\n\nexport const getType = (name: string): string => {\n if (name === 'unknown') {\n return name;\n }\n\n if (name.includes('webpack/runtime')) {\n return 'runtime';\n }\n\n return getExtension(cleanPath(name)) || 'unknown';\n};\n\nconst BUNDLER_SPECIFICS = ['unknown', 'commonjsHelpers.js', `vite${path.sep}preload-helper.js`];\n// Make list of paths unique, remove the current file and particularities.\nexport const cleanReport = <T = string>(\n report: Set<string>,\n filepath: string,\n filter?: (p: string) => T,\n) => {\n const cleanedReport: Set<T> = new Set();\n for (const reportFilepath of report) {\n const cleanedPath = cleanPath(reportFilepath);\n if (\n // Don't add injections.\n isInjectionFile(reportFilepath) ||\n // Don't add itself into it.\n cleanedPath === filepath ||\n // Remove common specific files injected by bundlers.\n BUNDLER_SPECIFICS.includes(cleanedPath)\n ) {\n continue;\n }\n\n if (filter) {\n const filteredValue = filter(cleanedPath);\n if (filteredValue) {\n cleanedReport.add(filteredValue);\n }\n } else {\n cleanedReport.add(cleanedPath as unknown as T);\n }\n }\n return cleanedReport;\n};\n\n// Clean a path from its query parameters and leading invisible characters.\n// Careful with this and webpack/rspack as loaders may add \"|\" before and after the filepath.\nexport const cleanPath = (filepath: string) => {\n return (\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading, invisible characters,\n // sometimes added in rollup by the commonjs plugin.\n .replace(/^[^\\w\\s.,!@#$%^&*()=+~`\\-/\\\\]+/, '')\n );\n};\n\n// From two file paths, remove the common path prefix.\nexport const removeCommonPrefix = (filepath1: string, filepath2: string) => {\n const filepath2Split = filepath2.split(path.sep);\n const commonPath = filepath1\n .split(path.sep)\n .filter((part, index) => part === filepath2Split[index])\n .join(path.sep);\n return filepath1.replace(commonPath, '');\n};\n\n// Extract a name from a path based on the context (outDir and cwd).\nexport const cleanName = (absoluteOutDir: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath === 'unknown') {\n return filepath;\n }\n\n if (filepath.includes('webpack/runtime')) {\n return filepath.replace('webpack/runtime/', '').replace(/ +/g, '-');\n }\n\n return (\n removeCommonPrefix(\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!,\n absoluteOutDir,\n )\n // Remove node_modules path.\n .split('node_modules')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading dots and slashes.\n .replace(/^((\\.\\.?)?[/\\\\])+/g, '')\n );\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n Output,\n PluginOptions,\n ResolvedEntry,\n} from '@dd/core/types';\nimport path from 'path';\n\nimport { cleanName, getType } from './helpers';\n\n// Re-index metafile data for easier access.\nconst reIndexMeta = <T>(obj: Record<string, T>, buildRoot: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(buildRoot, key);\n return [newKey, value];\n }),\n );\n\nexport const getEsbuildPlugin = (context: GlobalContext, log: Logger): PluginOptions['esbuild'] => {\n return {\n setup(build) {\n const entryNames = new Map();\n let resolvedEntries: ResolvedEntry[] = [];\n const timeBuildReport = log.time('build report', { start: false });\n\n build.onStart(async () => {\n // Start from a clean slate.\n entryNames.clear();\n resolvedEntries = [];\n\n timeBuildReport.resume();\n const timeEntries = log.time('process entries');\n // Store entry names based on the configuration.\n resolvedEntries.push(...(await getEsbuildEntries(build, context, log)));\n for (const entry of resolvedEntries) {\n const cleanedName = cleanName(context.bundler.outDir, entry.resolved);\n if (entry.name) {\n entryNames.set(cleanedName, entry.name);\n } else {\n entryNames.set(cleanedName, cleanedName);\n }\n }\n timeEntries.end();\n timeBuildReport.pause();\n });\n\n build.onEnd(async (result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const outDir = context.bundler.outDir;\n const buildRoot = context.buildRoot;\n for (const error of result.errors) {\n context.build.errors.push(error.text);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.text);\n }\n timeCollect.end();\n\n if (!result.metafile) {\n const warning = 'Missing metafile from build report.';\n context.build.warnings.push(warning);\n log.warn(warning);\n return;\n }\n\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n const timeIndex = log.time('indexing metafile data');\n const metaInputsIndexed = reIndexMeta(result.metafile.inputs, buildRoot);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, buildRoot);\n timeIndex.end();\n\n // From a proxy entry point, created by our injection plugin, get the real path.\n const getRealPathFromInjectionProxy = (entryPoint: string): string => {\n if (!isInjectionFile(entryPoint)) {\n return entryPoint;\n }\n\n const metaInput = metaInputsIndexed[getAbsolutePath(buildRoot, entryPoint)];\n if (!metaInput) {\n return entryPoint;\n }\n\n // Get the first non-injection import.\n const actualImport = metaInput.imports.find(\n (imp) => !isInjectionFile(imp.path),\n );\n if (!actualImport) {\n return entryPoint;\n }\n\n return actualImport.path;\n };\n\n // Loop through inputs.\n const timeInputs = log.time('looping through inputs');\n for (const [filename, input] of Object.entries(result.metafile.inputs)) {\n if (isInjectionFile(filename)) {\n continue;\n }\n\n const filepath = getAbsolutePath(buildRoot, filename);\n const name = cleanName(outDir, filename);\n\n const file: Input = {\n name,\n filepath,\n dependents: new Set(),\n dependencies: new Set(),\n size: input.bytes,\n type: getType(filename),\n };\n reportInputsIndexed[filepath] = file;\n inputs.push(file);\n }\n timeInputs.end();\n\n // Loop through outputs.\n const timeOutputs = log.time('looping through outputs');\n for (const [filename, output] of Object.entries(result.metafile.outputs)) {\n const fullPath = getAbsolutePath(buildRoot, filename);\n const cleanedName = cleanName(outDir, fullPath);\n // Get inputs of this output.\n const inputFiles: Input[] = [];\n for (const inputName of Object.keys(output.inputs)) {\n if (isInjectionFile(inputName)) {\n continue;\n }\n\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, inputName)];\n if (!inputFound) {\n log.debug(`Input ${inputName} not found for output ${cleanedName}`);\n continue;\n }\n\n inputFiles.push(inputFound);\n }\n\n // When splitting, esbuild creates an empty entryPoint wrapper for the chunk.\n // It has no inputs, but still relates to its entryPoint.\n if (output.entryPoint && !inputFiles.length) {\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, output.entryPoint)];\n if (!inputFound) {\n log.debug(\n `Input ${output.entryPoint} not found for output ${cleanedName}`,\n );\n continue;\n }\n inputFiles.push(inputFound);\n }\n\n const file: Output = {\n name: cleanedName,\n filepath: fullPath,\n inputs: inputFiles,\n size: output.bytes,\n type: getType(fullPath),\n };\n\n reportOutputsIndexed[fullPath] = file;\n\n // Store sourcemaps for later filling.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n }\n\n outputs.push(file);\n\n if (!output.entryPoint) {\n continue;\n }\n\n // The entryPoint may have been altered by our injection plugin.\n const inputFile =\n reportInputsIndexed[\n getAbsolutePath(\n buildRoot,\n getRealPathFromInjectionProxy(output.entryPoint),\n )\n ];\n\n if (inputFile) {\n // In the case of \"splitting: true\", all the files are considered entries to esbuild.\n // Not to us.\n // Verify we have listed it as an entry earlier.\n if (!entryNames.get(inputFile.name)) {\n continue;\n }\n\n const entry = {\n ...file,\n name: entryNames.get(inputFile.name) || inputFile.name,\n outputs: [file],\n size: file.size,\n };\n\n tempEntryFiles.push(entry);\n }\n }\n timeOutputs.end();\n\n // Loop through sourcemaps.\n const timeSourcemaps = log.time('looping through sourcemaps');\n for (const sourcemap of tempSourcemaps) {\n const outputFilepath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[outputFilepath];\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n\n // Build our references for the entries.\n const references = {\n inputs: {\n report: reportInputsIndexed,\n meta: metaInputsIndexed,\n },\n outputs: {\n report: reportOutputsIndexed,\n meta: metaOutputsIndexed,\n },\n };\n\n // There are some exceptions we want to ignore.\n const FILE_EXCEPTIONS_RX = /(<runtime>|https:|file:|data:|#)/g;\n const isFileSupported = (filePath: string) => {\n if (isInjectionFile(filePath) || filePath.match(FILE_EXCEPTIONS_RX)) {\n return false;\n }\n return true;\n };\n\n // Go through all imports.\n const getAllImports = <T extends Input | Output>(\n filePath: string,\n ref: typeof references.inputs | typeof references.outputs,\n allImports: Record<string, T> = {},\n ): Record<string, T> => {\n if (!isFileSupported(filePath)) {\n return allImports;\n }\n\n const file = ref.report[filePath];\n if (!file) {\n log.debug(`Could not find report's ${filePath}`);\n return allImports;\n }\n\n // Check if we already have processed it.\n if (allImports[file.filepath]) {\n return allImports;\n }\n\n allImports[file.filepath] = file as T;\n\n const metaFile = ref.meta[filePath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${filePath}`);\n return allImports;\n }\n\n // If there are no imports, we can return what we have.\n if (!metaFile.imports || !metaFile.imports.length) {\n return allImports;\n }\n\n for (const imported of metaFile.imports) {\n const isRelative = imported.path.match(/^\\.\\.?\\//);\n const root = isRelative ? path.dirname(filePath) : buildRoot;\n const absoluteImportPath = getAbsolutePath(root, imported.path);\n\n // We need to register external imports, as this is the first time we see them.\n if (imported.external) {\n if (isFileSupported(imported.path)) {\n // If it's an absolute external import,\n // we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteImportPath : imported.path;\n\n // But we can still add it to the report.\n const inputFile: Input = references.inputs.report[filepath] || {\n filepath,\n name: cleanName(outDir, imported.path),\n size: 0,\n type: 'external',\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if ('dependencies' in file) {\n // file is an Input, so we add the external to its dependencies,\n // and we add file to the external's dependents.\n inputFile.dependents.add(file);\n file.dependencies.add(inputFile);\n }\n\n if ('inputs' in file && !file.inputs.includes(inputFile)) {\n // file is an Output, so we add the external to its inputs.\n file.inputs.push(inputFile);\n }\n\n if (!inputs.includes(inputFile)) {\n inputs.push(inputFile);\n }\n\n references.inputs.report[filepath] = inputFile;\n allImports[inputFile.filepath] = inputFile as T;\n }\n // We can't follow external imports.\n continue;\n }\n\n // Look for the other inputs.\n getAllImports<T>(absoluteImportPath, ref, allImports);\n }\n\n return allImports;\n };\n\n // Loop through entries.\n const timeEntries = log.time('looping through entries');\n // TODO This is slightly underperformant due to getAllImports' recursivity.\n for (const entryFile of tempEntryFiles) {\n const entryInputs: Record<string, Input> = {};\n const entryOutputs: Record<string, Output> = {};\n\n // Do inputs for this entry.\n for (const input of entryFile.inputs) {\n getAllImports<Input>(input.filepath, references.inputs, entryInputs);\n }\n\n // Do outputs for this entry.\n for (const outputFile of entryFile.outputs) {\n getAllImports<Output>(\n outputFile.filepath,\n references.outputs,\n entryOutputs,\n );\n }\n\n entryFile.inputs = Object.values(entryInputs);\n entryFile.outputs = Object.values(entryOutputs);\n entryFile.size = entryFile.outputs.reduce(\n (acc, output) => acc + output.size,\n 0,\n );\n\n entries.push(entryFile);\n }\n timeEntries.end();\n\n // Loop through all inputs to aggregate dependencies and dependents.\n const timeDeps = log.time('aggregate dependencies and dependents');\n for (const input of inputs) {\n // The metafile does not contain external dependencies.\n // So we can only fill in their dependents.\n if (input.type === 'external') {\n continue;\n }\n\n const metaFile = references.inputs.meta[input.filepath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${input.name}`);\n continue;\n }\n\n for (const dependency of metaFile.imports) {\n if (!isFileSupported(dependency.path)) {\n continue;\n }\n\n const isRelative = dependency.path.match(/^\\.?\\.\\//);\n const root = isRelative ? path.dirname(input.filepath) : buildRoot;\n const absoluteDependencyPath = getAbsolutePath(root, dependency.path);\n\n let dependencyFile: Input | undefined;\n if (dependency.external) {\n // If it's an absolute external import, we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteDependencyPath : dependency.path;\n // In case of externals, we use their path directly.\n dependencyFile = references.inputs.report[filepath];\n } else {\n dependencyFile = references.inputs.report[absoluteDependencyPath];\n }\n\n if (!dependencyFile) {\n log.debug(\n `Could not find input file of ${dependency.path} imported from ${input.name}`,\n );\n continue;\n }\n\n input.dependencies.add(dependencyFile);\n // Add itself to the dependency's dependents.\n dependencyFile.dependents.add(input);\n }\n }\n timeDeps.end();\n\n context.build.outputs = outputs;\n context.build.inputs = inputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, Entry, GlobalContext, Input, Output, PluginOptions } from '@dd/core/types';\nimport fs from 'fs';\n\nimport { cleanName, cleanPath, cleanReport, getType } from './helpers';\n\nexport const getRollupPlugin = (context: GlobalContext, log: Logger): PluginOptions['rollup'] => {\n const timeModuleParsing = log.time('module parsing', { start: false });\n const timeBuildReport = log.time('build report', { start: false });\n const timeEntries = log.time('filling entries', { start: false });\n const timeInputsOutputs = log.time('filling inputs and outputs', { start: false });\n const timeCompleteDeps = log.time('completing dependencies and dependents', { start: false });\n const timeDeps = log.time('filling dependencies and dependents', { start: false });\n const timeSourcemaps = log.time('filling sourcemaps inputs', { start: false });\n\n const inputs: Map<string, Input> = new Map();\n const outputs: Map<string, Output> = new Map();\n const entries: Map<string, Entry> = new Map();\n const importsReport: Map<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = new Map();\n\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds.\n // It's useful with a dev server or a build with multiple outputs.\n importsReport.clear();\n inputs.clear();\n outputs.clear();\n entries.clear();\n },\n onLog(level, logItem) {\n if (level === 'warn') {\n context.build.warnings.push(logItem.message || logItem.toString());\n }\n },\n renderError(error) {\n if (error) {\n context.build.errors.push(error.message);\n }\n },\n moduleParsed(info) {\n timeModuleParsing.resume();\n // Store import infos.\n const cleanId = cleanPath(info.id);\n const report = importsReport.get(cleanId) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n // Clean new dependencies and dependents.\n const newDependencies = cleanReport(\n new Set([...info.dynamicallyImportedIds, ...info.importedIds]),\n cleanId,\n );\n\n const newDependents = cleanReport(\n new Set([...info.dynamicImporters, ...info.importers]),\n cleanId,\n );\n\n for (const dependent of newDependents) {\n report.dependents.add(dependent);\n }\n\n for (const dependency of newDependencies) {\n report.dependencies.add(dependency);\n }\n\n importsReport.set(cleanId, report);\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n // This can be called multiple times depending on the number of output configured.\n writeBundle(options, bundle) {\n timeBuildReport.resume();\n const outDir = options.dir\n ? getAbsolutePath(context.buildRoot, options.dir)\n : context.bundler.outDir;\n\n const tempEntryFiles: Set<Entry> = new Set();\n const tempSourcemaps: Set<Output> = new Set();\n const tempOutputsImports: Map<string, Output> = new Map();\n\n // Complete the importsReport with missing dependents and dependencies.\n timeCompleteDeps.resume();\n for (const [filepath, { dependencies, dependents }] of importsReport) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n const report = importsReport.get(cleanedDependency) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependents.has(filepath)) {\n continue;\n }\n\n report.dependents.add(filepath);\n importsReport.set(cleanedDependency, report);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n const report = importsReport.get(cleanedDependent) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependencies.has(filepath)) {\n continue;\n }\n\n report.dependencies.add(filepath);\n importsReport.set(cleanedDependent, report);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n timeInputsOutputs.resume();\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(outDir, filename);\n const size =\n 'code' in asset\n ? Buffer.byteLength(asset.code, 'utf8')\n : Buffer.byteLength(asset.source, 'utf8');\n\n const file: Output = outputs.get(filepath) || {\n name: filename,\n filepath,\n inputs: [],\n size,\n type: getType(filename),\n };\n\n // Store sourcemaps for later filling.\n // Because we may not have reported its input yet.\n if (file.type === 'map') {\n tempSourcemaps.add(file);\n }\n\n if ('modules' in asset) {\n for (const [modulepath, module] of Object.entries(asset.modules)) {\n // We don't want to include commonjs wrappers and proxies that are like:\n // \\u0000{{path}}?commonjs-proxy\n if (cleanPath(modulepath) !== modulepath) {\n continue;\n }\n\n // Since we store as input, we use the originalLength.\n let moduleSize = module.originalLength;\n if (!moduleSize && moduleSize !== 0) {\n // We don't have the size, let's get it.\n // This happens in rolldown, the API doesn't give us the original length.\n try {\n moduleSize = fs.statSync(modulepath).size;\n } catch (e) {\n // Nevermind, we tried our best, fallback to the rendered length (built).\n moduleSize = module.renderedLength;\n }\n }\n\n const moduleFile: Input = inputs.get(modulepath) || {\n name: cleanName(outDir, modulepath),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: modulepath,\n size: moduleSize,\n type: getType(modulepath),\n };\n file.inputs.push(moduleFile);\n inputs.set(moduleFile.filepath, moduleFile);\n }\n }\n\n // Add imports as inputs.\n // These are external imports since they are declared in the output file.\n if ('imports' in asset) {\n for (const importName of asset.imports) {\n const cleanedImport = cleanPath(importName);\n if (!importsReport.has(cleanedImport)) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports.set(getAbsolutePath(outDir, cleanedImport), file);\n continue;\n }\n\n if (inputs.has(cleanedImport)) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = inputs.get(cleanedImport) || {\n name: cleanName(outDir, importName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: cleanedImport,\n // Since it's external, we don't have the size.\n size: 0,\n type: 'external',\n };\n file.inputs.push(importFile);\n inputs.set(importFile.filepath, importFile);\n }\n }\n\n // Store entries for later filling.\n // As we may not have reported its outputs and inputs yet.\n if ('isEntry' in asset && asset.isEntry) {\n tempEntryFiles.add({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n outputs.set(file.filepath, file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of tempOutputsImports) {\n const outputReport = outputs.get(filepath);\n if (!outputReport) {\n log.debug(`Could not find the output report for ${filepath}.`);\n continue;\n }\n\n if (!output.inputs.includes(outputReport)) {\n output.inputs.push(outputReport);\n }\n }\n\n // Fill in inputs' dependencies and dependents.\n timeDeps.resume();\n for (const [filepath, input] of inputs) {\n const importReport = importsReport.get(filepath);\n if (!importReport) {\n log.debug(`Could not find the import report for ${input.name}.`);\n continue;\n }\n\n for (const dependency of importReport.dependencies) {\n const foundInput = inputs.get(dependency);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(outDir, dependency)} of ${input.name}`,\n );\n continue;\n }\n input.dependencies.add(foundInput);\n }\n\n for (const dependent of importReport.dependents) {\n const foundInput = inputs.get(dependent);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(outDir, dependent)} of ${input.name}`,\n );\n continue;\n }\n input.dependents.add(foundInput);\n }\n }\n timeDeps.end();\n\n // Fill in sourcemaps' inputs if necessary\n if (tempSourcemaps.size) {\n timeSourcemaps.resume();\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = outputs.get(outputPath);\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n }\n\n // Gather all outputs from a filepath, following imports.\n const getAllOutputs = (\n filepath: string,\n allOutputs: Map<string, Output> = new Map(),\n ) => {\n // We already processed it.\n if (allOutputs.has(filepath)) {\n return allOutputs;\n }\n const filename = cleanName(outDir, filepath);\n\n // Get its output.\n const foundOutput = outputs.get(filepath);\n if (!foundOutput) {\n // If it's been reported in the inputs, it means it's an external here.\n // Do not log about externals, we don't expect to find them.\n if (!inputs.has(filename)) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs.set(filepath, foundOutput);\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(outDir, filepath)];\n if (!asset) {\n log.debug(`Could not find asset for ${filename}`);\n return allOutputs;\n }\n\n // Imports are stored in two different places.\n const imports = [];\n if ('imports' in asset) {\n imports.push(...asset.imports);\n }\n if ('dynamicImports' in asset) {\n imports.push(...asset.dynamicImports);\n }\n\n for (const importName of imports) {\n getAllOutputs(getAbsolutePath(outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n timeEntries.resume();\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Array.from(entryOutputs.values());\n\n // NOTE: This might not be as accurate as expected, some inputs could be side-effects.\n // Rollup doesn't provide a way to get the imports of an input.\n entryFile.inputs = Array.from(\n new Set(entryFile.outputs.flatMap((output) => output.inputs)),\n );\n entryFile.size = entryFile.outputs.reduce((acc, output) => acc + output.size, 0);\n\n if (entries.has(entryFile.filepath)) {\n log.debug(\n `Entry \"${entryFile.name}\":\"${cleanName(outDir, entryFile.filepath)}\" already reported.`,\n );\n }\n\n entries.set(entryFile.filepath, entryFile);\n }\n timeEntries.pause();\n timeBuildReport.pause();\n },\n async closeBundle() {\n context.build.inputs = Array.from(inputs.values());\n context.build.outputs = Array.from(outputs.values());\n context.build.entries = Array.from(entries.values());\n\n timeEntries.end();\n timeBuildReport.end();\n\n await context.asyncHook('buildReport', context.build);\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n IterableElement,\n Output,\n PluginOptions,\n} from '@dd/core/types';\n\nimport { cleanName, cleanPath, getType } from './helpers';\n\nexport const getXpackPlugin =\n (\n context: GlobalContext,\n PLUGIN_NAME: string,\n log: Logger,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n let inputs: Input[] = [];\n let outputs: Output[] = [];\n let entries: Entry[] = [];\n\n // Types for the xpack hooks.\n type Compilation = Parameters<Parameters<typeof compiler.hooks.thisCompilation.tap>[1]>[0];\n type Module = IterableElement<Compilation['modules']>;\n type Dependency = IterableElement<IterableElement<Module['blocks']>['dependencies']>;\n type Chunk = IterableElement<Compilation['chunks']>;\n type IndexedModule = {\n identifier: Module['identifier'];\n dependencies: Dependency[];\n blocks: any[];\n externalType: unknown;\n external: unknown;\n };\n\n // Some indexes to help with the report generation.\n const reportInputsIndexed: Map<string, Input> = new Map();\n const reportOutputsIndexed: Map<string, Output> = new Map();\n const modulesPerFile: Map<string, Set<string>> = new Map();\n const moduleIndex: Map<string, IndexedModule> = new Map();\n\n // Some temporary holders to later fill in more data.\n const tempSourcemaps: Output[] = [];\n const tempDeps: Map<string, { dependencies: Set<string>; dependents: Set<string> }> =\n new Map();\n\n const timeBuildReport = log.time('build report', { start: false });\n\n const isModuleSupported = (moduleIdentifier?: string): boolean => {\n return (\n // Ignore unidentified modules and runtimes.\n !!moduleIdentifier &&\n !moduleIdentifier.startsWith('webpack/runtime') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack.\n * 1. Build a dependency graph from all the initial modules once they're finished\n * In afterEmit, modules are concatenated and obfuscated.\n * 2. Once the build is finished and emitted, we can compute the outputs and the entries.\n */\n\n // Clear the data in case we have multiple compilations (dev server, etc...).\n const clear = () => {\n inputs = [];\n outputs = [];\n entries = [];\n reportInputsIndexed.clear();\n reportOutputsIndexed.clear();\n moduleIndex.clear();\n tempDeps.clear();\n };\n\n const cleanExternalName = (name: string) => {\n // Removes \"external \" prefix and surrounding quotes from external dependency names\n // Example: 'external var \"lodash\"' -> 'lodash'\n return name.replace(/(^external[^\"]+\"|\"$)/g, '');\n };\n\n // Index the module by its identifier, resource, request, rawRequest, and userRequest.\n const getKeysToIndex = (mod: Module): Set<string> => {\n const indexes = new Set<string>();\n\n const keysOfModuleToIndexOn: string[] = [\n 'rawRequest',\n 'resource',\n 'request',\n 'userRequest',\n ];\n\n const indexValue = (value: string) => {\n const valueToIndex = cleanPath(value);\n indexes.add(valueToIndex);\n // RSpack only use \"external ...\" for external dependencies.\n // So we need to clean and add the actual name to the index too.\n if (valueToIndex.startsWith('external ')) {\n indexes.add(cleanExternalName(valueToIndex));\n }\n };\n\n // Start by indexing the identifier.\n indexValue(mod.identifier());\n\n // Then index all the other keys.\n for (const key of keysOfModuleToIndexOn) {\n const value = mod[key as keyof Module];\n if (key && key in mod && typeof value === 'string') {\n indexValue(value);\n }\n }\n\n return indexes;\n };\n\n const createIndexedModule = (mod: Module): IndexedModule => {\n const id = mod.identifier();\n return {\n identifier: () => id,\n dependencies: 'dependencies' in mod ? [...mod.dependencies] : [],\n blocks: 'blocks' in mod ? [...mod.blocks] : [],\n externalType: 'externalType' in mod ? mod.externalType : undefined,\n external: 'external' in mod ? mod.external : undefined,\n };\n };\n\n const indexModule = (mod: Module) => {\n const moduleToIndex = createIndexedModule(mod);\n const keysToIndex = getKeysToIndex(mod);\n for (const key of keysToIndex) {\n if (moduleIndex.has(key)) {\n // Update the existing module.\n const previousModule = moduleIndex.get(key)!;\n previousModule.dependencies.push(...(moduleToIndex.dependencies || []));\n previousModule.blocks.push(...(moduleToIndex.blocks || []));\n } else {\n moduleIndex.set(key, moduleToIndex);\n }\n }\n };\n\n // Aggregate all dependencies from a module.\n const getAllDependencies = (\n module: Module | Dependency | Module['blocks'][number],\n dependencies: Dependency[] = [],\n ) => {\n if ('dependencies' in module) {\n for (const dependency of module.dependencies) {\n dependencies.push(dependency);\n getAllDependencies(dependency, dependencies);\n }\n }\n\n if ('blocks' in module) {\n for (const block of module.blocks) {\n getAllDependencies(block, dependencies);\n }\n }\n\n return dependencies;\n };\n\n const getModuleFromDep = (mod: Module, dep: Dependency): IndexedModule | undefined => {\n if ('request' in dep && dep.request) {\n const cleanRequest = cleanPath(dep.request);\n if (moduleIndex.has(cleanRequest)) {\n return moduleIndex.get(cleanRequest);\n }\n if (mod.context) {\n const cleanedPath = getAbsolutePath(cleanPath(mod.context), cleanRequest);\n if (moduleIndex.has(cleanedPath)) {\n return moduleIndex.get(cleanedPath);\n }\n }\n }\n };\n\n const isExternal = (mod: Module | IndexedModule) => {\n if ('externalType' in mod && mod.externalType) {\n return true;\n }\n if ('external' in mod && mod.external) {\n return true;\n }\n if (mod.identifier?.().startsWith('external ')) {\n return true;\n }\n return false;\n };\n\n // Intercept the compilation to then get the modules.\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n clear();\n // Intercept the modules to build the dependency graph.\n compilation.hooks.finishModules.tap(\n PLUGIN_NAME,\n (finishedModules: Iterable<Module>) => {\n timeBuildReport.resume();\n const timeGraph = log.time('dependency graph');\n // First loop to create indexes.\n const timeIndex = log.time('indexing modules');\n for (const module of finishedModules) {\n indexModule(module);\n }\n timeIndex.end();\n\n // Second loop to create the dependency graph.\n const timeInputs = log.time('building inputs');\n for (const module of finishedModules) {\n const moduleIdentifier = module.identifier();\n const moduleName = cleanName(context.bundler.outDir, moduleIdentifier);\n const dependencies: Set<string> = new Set(\n getAllDependencies(module)\n .map((dep) => {\n const mod = getModuleFromDep(module, dep);\n\n // Ignore those we can't identify.\n if (!mod?.identifier()) {\n return false;\n }\n\n const identifier = mod.identifier();\n\n // Only what we support.\n if (!isModuleSupported(identifier)) {\n return false;\n }\n\n // Don't add itself as a dependency.\n if (identifier === moduleIdentifier) {\n return false;\n }\n\n return isExternal(mod)\n ? cleanExternalName(identifier)\n : identifier;\n })\n .filter(Boolean) as string[],\n );\n\n if (!isModuleSupported(moduleIdentifier)) {\n continue;\n }\n\n // Create dependents relationships.\n const moduleDeps = tempDeps.get(moduleIdentifier) || {\n dependents: new Set(),\n dependencies: new Set(),\n };\n for (const depIdentifier of dependencies) {\n const depDeps = tempDeps.get(depIdentifier) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n depDeps.dependents.add(moduleIdentifier);\n moduleDeps.dependencies.add(depIdentifier);\n tempDeps.set(depIdentifier, depDeps);\n }\n\n // Store the dependencies.\n tempDeps.set(moduleIdentifier, moduleDeps);\n\n // Store the inputs.\n const file: Input = isExternal(module)\n ? {\n size: 0,\n name: cleanExternalName(moduleName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: 'external',\n }\n : {\n size: module.size() || 0,\n name: moduleName,\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: getType(moduleIdentifier),\n };\n\n inputs.push(file);\n reportInputsIndexed.set(moduleIdentifier, file);\n\n // If it's an external dependency, we also need to index it by its cleaned name.\n if (isExternal(module)) {\n reportInputsIndexed.set(cleanExternalName(moduleIdentifier), file);\n }\n }\n timeInputs.end();\n\n // Assign dependencies and dependents.\n const timeAssign = log.time('assigning dependencies and dependents');\n for (const input of inputs) {\n const depsReport = tempDeps.get(input.filepath);\n\n if (!depsReport) {\n log.debug(`Could not find dependency report for ${input.name}`);\n continue;\n }\n\n for (const dependency of depsReport.dependencies) {\n const depInput = reportInputsIndexed.get(dependency);\n if (!depInput) {\n log.debug(`Could not find input of dependency ${dependency}`);\n continue;\n }\n input.dependencies.add(depInput);\n }\n\n for (const dependent of depsReport.dependents) {\n const depInput = reportInputsIndexed.get(dependent);\n if (!depInput) {\n log.debug(`Could not find input of dependent ${dependent}`);\n continue;\n }\n input.dependents.add(depInput);\n }\n }\n timeAssign.end();\n timeGraph.end();\n timeBuildReport.pause();\n },\n );\n });\n\n compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (result: Compilation) => {\n timeBuildReport.resume();\n const chunks = result.chunks;\n const assets = result.getAssets();\n\n const getChunkFiles = (chunk: Chunk) => {\n return [...(chunk.files || []), ...(chunk.auxiliaryFiles || [])].map((f: string) =>\n getAbsolutePath(context.bundler.outDir, f),\n );\n };\n\n const timeChunks = log.time('indexing chunks');\n const chunkGraph = result.chunkGraph;\n for (const chunk of chunks) {\n const files = getChunkFiles(chunk);\n\n const chunkModules =\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n (chunkGraph?.getChunkModules(chunk) || [])\n .flatMap((m) => {\n // modules exists but isn't in the types.\n return 'modules' in m && Array.isArray(m.modules)\n ? m.modules.map((m2) => m2.identifier())\n : m.identifier();\n })\n .filter(isModuleSupported);\n\n for (const file of files) {\n if (getType(file) === 'map') {\n continue;\n }\n const fileModules = modulesPerFile.get(file) || new Set();\n for (const module of chunkModules) {\n fileModules.add(module);\n }\n modulesPerFile.set(file, fileModules);\n }\n }\n timeChunks.end();\n\n // Build outputs\n const timeOutputs = log.time('building outputs');\n for (const asset of assets) {\n const file: Output = {\n size: asset.source.size() || 0,\n name: asset.name,\n inputs: [],\n filepath: getAbsolutePath(context.bundler.outDir, asset.name),\n type: getType(asset.name),\n };\n\n reportOutputsIndexed.set(file.filepath, file);\n outputs.push(file);\n\n // If it's a sourcemap, store it, we'll fill its input when we'll have\n // referenced all the outputs.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n continue;\n }\n\n // Add the inputs.\n const fileModules = modulesPerFile.get(file.filepath);\n if (!fileModules) {\n log.debug(`Could not find modules for ${file.name}`);\n continue;\n }\n\n for (const moduleIdentifier of fileModules) {\n const inputFound = reportInputsIndexed.get(moduleIdentifier);\n if (!inputFound) {\n log.debug(`Could not find input of ${moduleIdentifier}`);\n continue;\n }\n file.inputs.push(inputFound);\n }\n }\n timeOutputs.end();\n\n // Fill in inputs for sourcemaps.\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputFound = reportOutputsIndexed.get(\n sourcemap.filepath.replace(/\\.map$/, ''),\n );\n\n if (!outputFound) {\n log.debug(`Output not found for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(outputFound);\n }\n timeSourcemaps.end();\n\n // Build entries\n const timeEntries = log.time('building entries');\n\n // Helper to recursively get all chunks from a chunk group, including async chunks.\n const getAllChunksFromGroup = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunkGroup: any,\n visited: Set<unknown> = new Set(),\n ): Set<Chunk> => {\n if (visited.has(chunkGroup)) {\n return new Set();\n }\n visited.add(chunkGroup);\n\n const allChunks: Set<Chunk> = new Set(chunkGroup.chunks);\n\n // Recursively get chunks from child chunk groups (async chunks).\n for (const childGroup of chunkGroup.childrenIterable || []) {\n const childChunks = getAllChunksFromGroup(childGroup, visited);\n for (const chunk of childChunks) {\n allChunks.add(chunk);\n }\n }\n\n return allChunks;\n };\n\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 // Get all chunks including async chunks from child chunk groups.\n const allChunks = getAllChunksFromGroup(entrypoint);\n const entryFiles = Array.from(allChunks).flatMap(getChunkFiles);\n\n // FIXME This is not a 100% reliable way to get the entry filename.\n const entryFilename = entrypoint.chunks\n // Get the chunks that have entry modules.\n .filter(\n (chunk: Chunk) =>\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk) || false,\n )\n // Get the files of those chunks.\n .flatMap((c) => Array.from(c.files))\n // Filter the ones that includes the entry name.\n .filter(\n (f) => f.includes(name) || (entrypoint.name && f.includes(entrypoint.name)),\n )\n // Only keep JS files.\n .find((f) => getType(f) === 'js');\n\n for (const file of entryFiles) {\n const outputFound = reportOutputsIndexed.get(file);\n if (!file || !outputFound) {\n log.debug(`Could not find output of ${JSON.stringify(file)}`);\n continue;\n }\n if (outputFound.type !== 'map' && !entryOutputs.has(outputFound.name)) {\n entryOutputs.set(outputFound.name, outputFound);\n // We know it's not a map, so we cast it.\n for (const input of outputFound.inputs as Input[]) {\n if (!entryInputs.has(input.filepath)) {\n entryInputs.set(input.filepath, input);\n }\n }\n // We don't want to include sourcemaps in the sizing.\n size += outputFound.size;\n }\n }\n\n const file: Entry = {\n name,\n filepath: entryFilename\n ? getAbsolutePath(context.bundler.outDir, entryFilename)\n : 'unknown',\n size,\n inputs: Array.from(entryInputs.values()),\n outputs: Array.from(entryOutputs.values()),\n type: entryFilename ? getType(entryFilename) : 'unknown',\n };\n entries.push(file);\n }\n timeEntries.end();\n\n // Save everything in the context.\n for (const error of result.errors) {\n context.build.errors.push(error.message);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.message);\n }\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions } from '@dd/core/types';\n\nimport { getEsbuildPlugin } from './esbuild';\nimport { getRollupPlugin } from './rollup';\nimport { getXpackPlugin } from './xpack';\n\nexport const PLUGIN_NAME = 'datadog-build-report-plugin';\n\nexport const getBuildReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n esbuild: getEsbuildPlugin(context, log),\n rspack: getXpackPlugin(context, PLUGIN_NAME, log),\n webpack: getXpackPlugin(context, PLUGIN_NAME, log),\n // Vite and Rollup have the same API.\n vite: getRollupPlugin(context, log) as PluginOptions['vite'],\n rollup: getRollupPlugin(context, log),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath, getNearestCommonDirectory } from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\nimport type { InputOptions, OutputOptions } from 'rollup';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\nexport const getAbsoluteOutDir = (buildRoot: string, outDir?: string) => {\n if (!outDir) {\n return '';\n }\n\n return path.isAbsolute(outDir) ? outDir : path.resolve(buildRoot, outDir);\n};\n\nexport const getOutDirsFromOutputs = (\n outputOptions?: OutputOptions | OutputOptions[],\n): string[] => {\n if (!outputOptions) {\n return [];\n }\n\n const normalizedOutput = Array.isArray(outputOptions) ? outputOptions : [outputOptions];\n return normalizedOutput\n .map((o) => {\n if (o.dir) {\n return o.dir;\n }\n if (o.file) {\n return path.dirname(o.file);\n }\n })\n .filter(Boolean) as string[];\n};\n\nexport const getIndirsFromInputs = (options: InputOptions) => {\n const inDirs: Set<string> = new Set();\n\n if (options.input) {\n const normalizedInput = Array.isArray(options.input)\n ? options.input\n : typeof options.input === 'object'\n ? Object.values(options.input)\n : [options.input];\n\n for (const input of normalizedInput) {\n if (typeof input !== 'string') {\n throw new Error('Invalid input type');\n }\n inDirs.add(path.dirname(input));\n }\n }\n\n return Array.from(inDirs);\n};\n\nconst xpackPlugin: (context: GlobalContext) => PluginOptions['webpack'] & PluginOptions['rspack'] =\n (context) => (compiler) => {\n context.bundler.rawConfig = compiler.options;\n\n if (compiler.options.output?.path) {\n // While webpack doesn't allow for non-absolute paths,\n // rspack does, and will fallback to use process.cwd().\n context.bundler.outDir = getAbsoluteOutDir(process.cwd(), compiler.options.output.path);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.buildRoot = compiler.options.context;\n }\n context.hook('buildRoot', context.buildRoot);\n };\n\nconst vitePlugin = (context: GlobalContext): PluginOptions['vite'] => {\n return {\n configResolved(config) {\n context.bundler.rawConfig = config;\n // If we have the outDir configuration from Vite.\n let outDir = config.build?.outDir ?? 'dist';\n // We need to know if we have a rollup output configuration.\n // As it will override Vite's outDir and root.\n const output = config.build?.rollupOptions?.output as\n | OutputOptions\n | OutputOptions[]\n | undefined;\n\n const outDirs = getOutDirsFromOutputs(output);\n\n // Vite will fallback to process.cwd() if no root is provided.\n context.buildRoot = config.root ?? process.cwd();\n // Vite will fallback to process.cwd() if we have an output configuration with dirs.\n if (output && outDirs.length) {\n // Now compute the nearest common directory from the output directories.\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Make sure the outDir is absolute.\n context.bundler.outDir = getAbsoluteOutDir(context.buildRoot, outDir);\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n },\n };\n};\n\n// TODO: Add universal config report with list of plugins (names), loaders.\nexport const getBundlerReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const bundlerReportPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: {\n setup(build) {\n context.bundler.rawConfig = build.initialOptions;\n\n if (build.initialOptions.absWorkingDir) {\n context.buildRoot = build.initialOptions.absWorkingDir;\n }\n\n if (build.initialOptions.outdir) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n build.initialOptions.outdir,\n );\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n path.dirname(build.initialOptions.outfile),\n );\n }\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n },\n },\n webpack: xpackPlugin(context),\n rspack: xpackPlugin(context),\n vite: vitePlugin(context),\n rollup: {\n options(options) {\n // By default, with relative paths, rollup will use process.cwd() as the CWD.\n let outDir;\n if ('output' in options) {\n const outDirs = getOutDirsFromOutputs(\n options.output as OutputOptions | OutputOptions[],\n );\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Compute input directories if possible.\n const inDirs = getIndirsFromInputs(options);\n\n if (outDir) {\n context.bundler.outDir = getAbsolutePath(process.cwd(), outDir);\n const computedCwd = getNearestCommonDirectory(\n [outDir, ...inDirs],\n process.cwd(),\n );\n // If the computed CWD is the root directory, it means we could not compute it,\n // so we fallback to process.cwd().\n context.buildRoot = computedCwd === path.sep ? process.cwd() : computedCwd;\n } else {\n // Fallback to process.cwd()/dist as it is rollup's default.\n context.buildRoot = getNearestCommonDirectory(inDirs, process.cwd());\n context.bundler.outDir = path.resolve(process.cwd(), 'dist');\n }\n\n context.hook('buildRoot', context.buildRoot);\n },\n buildStart(options) {\n // Save the resolved options.\n context.bundler.rawConfig = options;\n },\n renderStart(outputOptions) {\n // Save the resolved options.\n context.bundler.rawConfig.outputs = context.bundler.rawConfig.outputs || [];\n context.bundler.rawConfig.outputs.push(outputOptions);\n context.hook('bundlerReport', context.bundler);\n\n // Verify that the output directory is the same as the one computed in the options hook.\n const outDirs = getOutDirsFromOutputs(outputOptions);\n // Rollup always uses process.cwd() as the CWD.\n const outDir = getNearestCommonDirectory(outDirs, process.cwd());\n if (!outDir.startsWith(context.bundler.outDir)) {\n log.warn(\n 'The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.',\n );\n }\n },\n },\n };\n\n return [bundlerReportPlugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-custom-hooks-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, TriggerHook } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getCustomHooksPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const executeHooks =\n (async: boolean): TriggerHook<Promise<void[]> | void> =>\n (hookName, ...hookArgs) => {\n const timeHook = log.time(`execution | ${hookName}`, {\n tags: ['type:custom-hook', `hook:${hookName}`],\n });\n const errors: string[] = [];\n const proms: Promise<void>[] = [];\n\n for (const plugin of context.plugins) {\n if (!(hookName in plugin)) {\n continue;\n }\n\n const hookFn = plugin[hookName];\n if (typeof hookFn !== 'function') {\n errors.push(\n `Plugin \"${plugin.name}\" has an invalid hook type for \"${hookName}\". [${typeof hookFn}]`,\n );\n continue;\n }\n\n try {\n // Re-typing to take over typechecking.\n const result: any = hookFn(...(hookArgs as any[]));\n\n if (result instanceof Promise) {\n // Confirm that the result is not an unsupported Promise.\n if (!async) {\n errors.push(\n `Plugin \"${plugin.name}\" returned a promise on the non async hook \"${hookName}\".`,\n );\n }\n proms.push(result);\n }\n } catch (e) {\n errors.push(`Plugin \"${plugin.name}\" errored on hook \"${hookName}\". [${e}]`);\n }\n }\n\n if (errors.length > 0) {\n for (const error of errors) {\n log.error(error);\n }\n throw new Error(`Some plugins errored during the hook execution.`);\n }\n\n return Promise.all(proms).finally(() => timeHook.end());\n };\n\n // Define the hook functions.\n context.hook = executeHooks(false);\n // Define the asyncHook functions.\n context.asyncHook = executeHooks(true) as TriggerHook<Promise<void[]>>;\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFileSync } from '@dd/core/helpers/fs';\n\n// TrackedFilesMatcher can compute the list of tracked files related to a particular sourcemap.\n// The current implementation simply returns all tracked files whose filename is found inside\n// the sourcemap 'sources' field.\n// It is used so that we don't send every tracked files to the backend since most won't be of any use\n// for a particular sourcemap.\nexport class TrackedFilesMatcher {\n // A map with tracked filenames as key and the related tracked file paths as value.\n private trackedFilenames: Map<string, string[]>;\n\n constructor(trackedFiles: string[]) {\n this.trackedFilenames = new Map<string, string[]>();\n for (const f of trackedFiles) {\n const filename = this.getFilename(f);\n const list = this.trackedFilenames.get(filename);\n if (list) {\n list.push(f);\n } else {\n this.trackedFilenames.set(filename, new Array<string>(f));\n }\n }\n }\n\n private displaySource(src: string) {\n if (src.length <= 40) {\n return src;\n }\n return `[...]${src.slice(-35)}`;\n }\n\n // Looks up the sources declared in the sourcemap and return a list of related tracked files.\n public matchSourcemap(\n srcmapPath: string,\n onSourcesNotFound: (reason: string) => void,\n ): string[] | undefined {\n const buff = readFileSync(srcmapPath);\n const srcmapObj = JSON.parse(buff);\n if (!srcmapObj.sources) {\n onSourcesNotFound(`Missing 'sources' field in sourcemap.`);\n return undefined;\n }\n const sources = srcmapObj.sources as string[];\n if (sources.length === 0) {\n onSourcesNotFound(`Empty 'sources' field in sourcemap.`);\n return undefined;\n }\n const filtered = this.matchSources(sources);\n if (filtered.length === 0) {\n onSourcesNotFound(\n `${sources.map(this.displaySource).join(', ')} not in the tracked files.`,\n );\n return undefined;\n }\n\n return filtered;\n }\n\n public matchSources(sources: string[]): string[] {\n let filtered: string[] = [];\n const filenameAlreadyMatched = new Set<string>();\n for (const source of sources) {\n const filename = this.getFilename(source);\n if (filenameAlreadyMatched.has(filename)) {\n continue;\n }\n filenameAlreadyMatched.add(filename);\n const trackedFiles = this.trackedFilenames.get(filename);\n if (trackedFiles) {\n filtered = filtered.concat(trackedFiles);\n }\n }\n\n return filtered;\n }\n\n // Return a list of all tracked files\n public rawTrackedFilesList() {\n let rawList: string[] = [];\n this.trackedFilenames.forEach((value) => {\n rawList = rawList.concat(value);\n });\n\n return rawList;\n }\n\n // Extract the filename from a path.\n //\n // We are removing any suffix that is after the character '?'. The only reason this is done\n // is because we noticed that a non-negligible (~5%) amount of source paths from our customers\n // source maps contained query parameters.\n // We are assuming that the files may not actually be named with the interrogation mark but that\n // it is only an artifact of the build process. The query parameters look random. It looks\n // like it may be used as a trick to force a web browser to reload the file content.\n // The only side effect of doing that operation is that more tracked files paths may be sent\n // alongside the sourcemap which is not a problem.\n // Example: webpack:///./src/folder/ui/select.vue?821e\n private getFilename(s: string): string {\n let start = s.lastIndexOf('/');\n if (start === -1) {\n start = 0;\n } else {\n start++;\n }\n let end = s.lastIndexOf('?');\n if (end === -1 || end <= start) {\n end = s.length;\n }\n\n return s.substring(start, end);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { filterSensitiveInfoFromRepositoryUrl } from '@dd/core/helpers/strings';\nimport type { RepositoryData } from '@dd/core/types';\nimport type { SimpleGit, BranchSummary } from 'simple-git';\nimport { simpleGit } from 'simple-git';\n\nimport { TrackedFilesMatcher } from './trackedFilesMatcher';\n\n// Returns a configured SimpleGit.\nexport const newSimpleGit = async (cwd?: string): Promise<SimpleGit> => {\n const options = {\n baseDir: cwd || process.cwd(),\n binary: 'git',\n // We are invoking at most 3 git commands at the same time.\n maxConcurrentProcesses: 3,\n };\n try {\n // Attempt to set the baseDir to the root of the repository so the 'git ls-files' command\n // returns the tracked files paths relative to the root of the repository.\n const git = simpleGit(options);\n const root = await git.revparse('--show-toplevel');\n options.baseDir = root;\n } catch {\n // Ignore exception as it will fail if we are not inside a git repository.\n }\n\n return simpleGit(options);\n};\n\n// Returns the remote of the current repository.\nexport const gitRemote = async (git: SimpleGit): Promise<string> => {\n const remotes = await git.getRemotes(true);\n if (remotes.length === 0) {\n throw new Error('No git remotes available');\n }\n const defaultRemote = await getDefaultRemoteName(git);\n\n for (const remote of remotes) {\n if (remote.name === defaultRemote) {\n return filterSensitiveInfoFromRepositoryUrl(remote.refs.push);\n }\n }\n\n // Falling back to picking the first remote in the list if the default remote is not found.\n return filterSensitiveInfoFromRepositoryUrl(remotes[0].refs.push);\n};\n\nexport const getDefaultRemoteName = async (git: SimpleGit): Promise<string> => {\n try {\n return (await git.getConfig('clone.defaultRemoteName'))?.value ?? 'origin';\n } catch (e) {\n return 'origin';\n }\n};\n\n// Returns the hash of the current repository.\nexport const gitHash = async (git: SimpleGit): Promise<string> => git.revparse('HEAD');\n\n// Returns the tracked files of the current repository.\nexport const gitTrackedFiles = async (git: SimpleGit): Promise<string[]> => {\n const files = await git.raw('ls-files');\n\n return files.split(/\\r\\n|\\r|\\n/);\n};\n\nexport const gitBranch = async (git: SimpleGit): Promise<BranchSummary> => git.branch();\n\nexport const gitMessage = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%s']);\n\nexport const gitAuthorAndCommitter = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%an,%ae,%aI,%cn,%ce,%cI']);\n\nexport const gitRepositoryURL = async (git: SimpleGit): Promise<string> =>\n git.listRemote(['--get-url']);\n\n// Returns the current hash and remote as well as a TrackedFilesMatcher.\n//\n// To obtain the list of tracked files paths tied to a specific sourcemap, invoke the 'matchSourcemap' method.\nexport const getRepositoryData = async (git: SimpleGit): Promise<RepositoryData> => {\n // Invoke git commands to retrieve some informations and tracked files.\n // We're using Promise.all instead of Promise.allSettled since we want to fail early if\n // any of the promises fails.\n\n const proms: [\n ReturnType<typeof gitHash>,\n ReturnType<typeof gitBranch>,\n ReturnType<typeof gitMessage>,\n ReturnType<typeof gitAuthorAndCommitter>,\n ReturnType<typeof gitTrackedFiles>,\n ReturnType<typeof gitRemote>,\n ] = [\n gitHash(git),\n gitBranch(git),\n gitMessage(git),\n gitAuthorAndCommitter(git),\n gitTrackedFiles(git),\n gitRemote(git),\n ];\n\n const [hash, branch, message, authorAndCommitter, trackedFiles, remote] =\n await Promise.all(proms);\n\n const [authorName, authorEmail, authorDate, committerName, committerEmail, committerDate] =\n authorAndCommitter.split(',').map((item) => item.trim());\n\n const data: RepositoryData = {\n commit: {\n author: {\n name: authorName,\n email: authorEmail,\n date: authorDate,\n },\n committer: {\n name: committerName,\n email: committerEmail,\n date: committerDate,\n },\n message: message.trim(),\n hash,\n },\n hash,\n branch: branch.current,\n remote: remote.trim(),\n trackedFilesMatcher: new TrackedFilesMatcher(trackedFiles),\n };\n\n return data;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getClosest } from '@dd/core/helpers/paths';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\nimport path from 'path';\n\nimport { getRepositoryData, newSimpleGit } from './helpers';\n\nexport const PLUGIN_NAME = 'datadog-git-plugin';\n\nexport const getGitPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { options, context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const timeGit = log.time('get git information', { start: false });\n const processGit = async (gitDir: string) => {\n try {\n const git = await newSimpleGit(path.dirname(gitDir));\n const remotes = await git.getRemotes(true);\n if (remotes.length === 0) {\n log.warn(\n 'No git remotes available, skipping git plugin. ' +\n 'This is expected for a repository that has not been pushed yet.',\n );\n timeGit.end();\n return;\n }\n\n const repositoryData = await getRepositoryData(git);\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\n } catch (e: any) {\n log.error(`Could not get git information: ${e.message}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n buildRoot(buildRoot) {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n timeGit.resume();\n // Add git information to the context.\n const gitDir = getClosest(buildRoot, '.git');\n if (!gitDir) {\n log.warn('No .git directory found, skipping git plugin.');\n timeGit.end();\n return;\n }\n\n // buildRoot hook is sync because xpack can't make it async.\n // So we queue the async part of the plugin.\n context.queue(processGit(gitDir));\n } catch (e: any) {\n // We don't want to have the build fail for this.\n log.error(`Could not get git information: ${e.message}`);\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const PLUGIN_NAME = 'datadog-injection-plugin';\nexport const DISTANT_FILE_RX = /^https?:\\/\\//;\nexport const BEFORE_INJECTION = `// begin injection by Datadog build plugins`;\nexport const AFTER_INJECTION = `// end injection by Datadog build plugins`;\nexport const SUPPORTED_EXTENSIONS = ['.mjs', '.mjsx', '.js', '.ts', '.tsx', '.jsx'];\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 { ChunkInfo, Logger, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport {\n AFTER_INJECTION,\n BEFORE_INJECTION,\n DISTANT_FILE_RX,\n SUPPORTED_EXTENSIONS,\n} from './constants';\nimport type { ContentsToInject, ContentToInject } from './types';\n\nconst yellow = chalk.bold.yellow;\n\nconst MAX_TIMEOUT_IN_MS = 5000;\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 function hasBeforeAfterInjection(contentsToInject: ContentToInject[]) {\n return contentsToInject.some(\n (content) =>\n content.position === InjectPosition.BEFORE || content.position === InjectPosition.AFTER,\n );\n}\n\nexport function hasChunkInjection(contentsToInject: ContentToInject[]) {\n return contentsToInject.some((content) => content.injectIntoAllChunks);\n}\n\nexport const getContentToInject = (\n contentToInject: ContentToInject[],\n position: InjectPosition,\n chunk?: ChunkInfo,\n) => {\n const filtered = contentToInject.filter((content) => {\n return (\n content.position === position &&\n (!chunk || chunk.isEntry || content.injectIntoAllChunks)\n );\n });\n\n // Resolve function-valued content against the current chunk, drop empties.\n const values = filtered\n .map((content) => (isFunction(content.value) ? content.value(chunk!) : content.value))\n .filter(Boolean);\n\n if (values.length === 0) {\n return '';\n }\n\n const stringToInject = values\n // Wrapping it in order to avoid variable name collisions.\n .map((value) => `(() => {${value}})();`)\n .join('\\n\\n');\n return `${BEFORE_INJECTION}\\n${stringToInject}\\n${AFTER_INJECTION}`;\n};\n\nexport const resolveWithFallback = async (\n item: ToInjectItem,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<string> => {\n const value = isFunction(item.value) ? await item.value() : item.value;\n\n try {\n if (item.type === 'file') {\n const filePath = value;\n return await (filePath.match(DISTANT_FILE_RX)\n ? processDistantFile(filePath)\n : processLocalFile(filePath, cwd));\n }\n return value;\n } catch (error: any) {\n const itemId = `${item.type} - ${truncateString(value)}`;\n if (item.fallback) {\n log.debug(`Fallback for \"${itemId}\": ${error.toString()}`);\n return resolveWithFallback(item.fallback, log, cwd);\n }\n log.warn(`Failed \"${itemId}\": ${error.toString()}`);\n return '';\n }\n};\nexport const prepareInjections = async (\n log: Logger,\n toInject: ToInjectItem[],\n contentsToInject: ContentsToInject,\n cwd: string = process.cwd(),\n) => {\n // Per-chunk functions receive the full ChunkInfo for the chunk they're injected into.\n const dynamicPerChunk = toInject.filter(isPerChunk).map((item) => {\n const userFn = item.value as (chunk?: ChunkInfo) => string;\n return { ...item, value: (chunk: ChunkInfo) => userFn(chunk) };\n });\n\n // Static items (strings and async loaders) are resolved once per build.\n const staticInject = toInject.filter((item) => !isPerChunk(item));\n const resolvedStaticInject = await Promise.all(\n staticInject.map(async (item) => ({\n ...item,\n value: await resolveWithFallback(item, log, cwd),\n })),\n );\n\n const normalize = <T extends { position?: InjectPosition }>(item: T) => ({\n ...item,\n position: item.position ?? InjectPosition.BEFORE,\n });\n contentsToInject.push(\n ...dynamicPerChunk.map(normalize),\n ...resolvedStaticInject.map(normalize),\n );\n};\n\nexport interface NodeSystemError extends Error {\n code: string;\n}\n\nexport const isNodeSystemError = (e: unknown): e is NodeSystemError => {\n return e instanceof Error && 'code' in e;\n};\n\nexport const isFileSupported = (ext: string): boolean => {\n return SUPPORTED_EXTENSIONS.includes(ext);\n};\n\nexport const warnUnsupportedFile = (log: Logger, ext: string, filename: string): void => {\n log.warn(`\"${yellow(ext)}\" files are not supported (${yellow(filename)}).`);\n};\n\nconst isPerChunk = (\n item: ToInjectItem,\n): item is ToInjectItem & { value: (chunk: ChunkInfo) => string } =>\n typeof item.value === 'function' && item.value.length === 1;\n\nconst isFunction = (value: any): value is Function => typeof value === 'function';\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { outputFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, PluginOptions, GlobalContext, ResolvedEntry } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport {\n getContentToInject,\n hasChunkInjection,\n isNodeSystemError,\n isFileSupported,\n warnUnsupportedFile,\n hasBeforeAfterInjection,\n} from './helpers';\nimport type { ContentsToInject } from './types';\n\nconst fsp = fs.promises;\n\nexport const getEsbuildPlugin = (\n log: Logger,\n context: GlobalContext,\n contentsToInject: ContentsToInject,\n): PluginOptions['esbuild'] => ({\n setup(build) {\n const { onStart, onResolve, onLoad, onEnd, esbuild, initialOptions } = build;\n const entries: ResolvedEntry[] = [];\n // Use a narrower identifier to avoid cross build collisions.\n const id = context.bundler.name;\n const filePath = `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`;\n const tmpDir = fs.realpathSync(os.tmpdir());\n const absoluteFilePath = path.resolve(tmpDir, filePath);\n const injectionRx = new RegExp(`${filePath}$`);\n\n // InjectPosition.MIDDLE\n // Inject the file in the build using the \"inject\" option.\n // NOTE: This is made \"safer\" for sub-builds by actually creating the file.\n const initialInject = initialOptions.inject;\n initialOptions.inject = initialInject ? [...initialInject] : [];\n initialOptions.inject.push(absoluteFilePath);\n\n onStart(async () => {\n // Get all the entry points for later reference.\n entries.push(...(await getEsbuildEntries(build, context, log)));\n\n // Remove our injected file from the config, so we reduce our chances to leak our changes.\n build.initialOptions.inject = initialInject;\n\n try {\n // Create the MIDDLE file because esbuild will crash if it doesn't exist.\n // It seems to load entries outside of the onLoad hook once.\n await outputFile(absoluteFilePath, '');\n } catch (e: any) {\n log.error(`Could not create the files: ${e.message}`);\n }\n });\n\n onResolve(\n {\n filter: injectionRx,\n },\n async (args) => {\n // Mark the file as being injected by us.\n return { path: args.path, namespace: PLUGIN_NAME };\n },\n );\n\n onLoad(\n {\n filter: injectionRx,\n namespace: PLUGIN_NAME,\n },\n async () => {\n const content = getContentToInject(contentsToInject, InjectPosition.MIDDLE);\n\n return {\n // We can't use an empty string otherwise esbuild will crash.\n contents: content || ' ',\n // Resolve the imports from the project's root.\n resolveDir: context.buildRoot,\n loader: 'js',\n };\n },\n );\n\n // InjectPosition.START and InjectPosition.END\n onEnd(async (result) => {\n if (!result.metafile) {\n log.warn('Missing metafile from build result.');\n return;\n }\n\n if (!hasBeforeAfterInjection(contentsToInject)) {\n return;\n }\n\n const proms: Promise<void>[] = [];\n\n // Process all output files\n for (const [p, o] of Object.entries(result.metafile.outputs)) {\n // Determine if this is an entry point\n const isEntry = Boolean(\n o.entryPoint && entries.some((e) => e.resolved.endsWith(o.entryPoint!)),\n );\n\n if (!isEntry && !hasChunkInjection(contentsToInject)) {\n continue;\n }\n\n const absolutePath = getAbsolutePath(context.buildRoot, p);\n const { base, ext } = path.parse(absolutePath);\n\n // Check if file type is supported\n if (!isFileSupported(ext)) {\n warnUnsupportedFile(log, ext, base);\n continue;\n }\n\n // Inject content\n proms.push(\n (async () => {\n try {\n const mapPath = `${absolutePath}.map`;\n const sourceOrHash = await fsp.readFile(absolutePath, 'utf-8');\n const sourcemap = await fsp\n .readFile(mapPath, 'utf-8')\n .catch(() => false as const);\n const fileName = path.basename(absolutePath);\n // Resolve static and per-chunk content in one pass.\n const banner = getContentToInject(\n contentsToInject,\n InjectPosition.BEFORE,\n { sourceOrHash, fileName, isEntry },\n );\n const footer = getContentToInject(\n contentsToInject,\n InjectPosition.AFTER,\n { sourceOrHash, fileName, isEntry },\n );\n\n if (!banner && !footer) {\n return;\n }\n\n // Strip existing sourceMappingURL and inline the map so esbuild chains it.\n const cleaned = sourceOrHash.replace(\n /\\n?\\/\\/# sourceMappingURL=.*$/m,\n '',\n );\n const input = sourcemap\n ? `${cleaned}\\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(sourcemap!).toString('base64')}`\n : cleaned;\n\n const data = await esbuild.transform(input, {\n loader: 'default',\n banner,\n footer,\n sourcemap: sourcemap ? 'external' : undefined,\n sourcefile: fileName,\n });\n\n await Promise.all([\n fsp.writeFile(absolutePath, data.code),\n sourcemap && data.map ? fsp.writeFile(mapPath, data.map) : null,\n ]);\n } catch (e) {\n if (isNodeSystemError(e) && e.code === 'ENOENT') {\n // When we are using sub-builds, the entry file of sub-builds may not exist\n // Hence we should skip the file injection in this case.\n log.warn(`Could not inject content in ${absolutePath}: ${e}`);\n } else {\n throw e;\n }\n }\n })(),\n );\n }\n\n await Promise.all(proms);\n });\n },\n});\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { Logger, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport MagicString from 'magic-string';\nimport path from 'path';\nimport type { RenderedChunk } from 'rollup';\n\nimport { getContentToInject, isFileSupported, warnUnsupportedFile } 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 = (\n log: Logger,\n contentsToInject: ContentsToInject,\n): PluginOptions['rollup'] => {\n return {\n renderChunk(code, chunk: RenderedChunk) {\n const { base, ext } = path.parse(chunk.fileName);\n if (!isFileSupported(ext)) {\n warnUnsupportedFile(log, ext, base);\n return null;\n }\n\n const banner = getContentToInject(contentsToInject, InjectPosition.BEFORE, {\n sourceOrHash: code,\n fileName: chunk.fileName,\n isEntry: chunk.isEntry,\n });\n const footer = getContentToInject(contentsToInject, InjectPosition.AFTER, {\n sourceOrHash: code,\n fileName: chunk.fileName,\n isEntry: chunk.isEntry,\n });\n\n if (!banner && !footer) {\n return null;\n }\n\n const s = new MagicString(code);\n\n if (banner) {\n s.prepend(`${banner}\\n`);\n }\n if (footer) {\n s.append(`\\n${footer}`);\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({ file: chunk.fileName, hires: 'boundary' }),\n };\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 // Skip HTML entries - Vite handles these specially via transformIndexHtml\n // The proxy mechanism breaks Vite's HTML->module tracking\n if (source.endsWith('.html')) {\n return null;\n }\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 };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { outputFileSync, rmSync } from '@dd/core/helpers/fs';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport {\n getContentToInject,\n prepareInjections,\n isFileSupported,\n warnUnsupportedFile,\n} from './helpers';\nimport type { ContentsToInject } from './types';\n\nexport const getXpackPlugin =\n (\n bundler: any,\n log: Logger,\n context: GlobalContext,\n toInject: ToInjectItem[],\n contentsToInject: ContentsToInject,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n const cache = new WeakMap();\n // Use a narrower identifier to avoid cross build collisions.\n const ConcatSource = bundler.sources.ConcatSource;\n const id = context.bundler.name;\n // Use a cache directory within the project root instead of outDir,\n // so that webpack's output.clean option doesn't delete the file\n // before it can be resolved as an entry point.\n // https://github.com/DataDog/build-plugins/issues/304\n const filePath = path.resolve(\n context.buildRoot,\n 'node_modules',\n '.cache',\n 'datadog-build-plugins',\n `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`,\n );\n\n // NOTE: RSpack MAY try to resolve the entry points before the loader is ready.\n // There must be some race condition around this, because it's not always failing.\n outputFileSync(filePath, '');\n // WARNING: Can't use shutdown.tapPromise as rspack would randomly crash the process.\n // Seems to be fixed in rspack@1.2.*\n // We also do it for webpack, as it fixes some resolution edge cases.\n const hookFn = () => {\n // Delete the file we created.\n rmSync(filePath);\n };\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n\n // Handle the InjectPosition.MIDDLE.\n type Entry = typeof compiler.options.entry;\n // TODO: Move this into @dd/core, add rspack/webpack types and tests.\n const injectEntry = (initialEntry: Entry): Entry => {\n const injectedEntry = {\n import: [filePath],\n };\n\n const objectInjection = (entry: Entry) => {\n for (const [entryKey, entryValue] of Object.entries(entry)) {\n if (typeof entryValue === 'object') {\n entryValue.import = entryValue.import || [];\n entryValue.import.unshift(filePath);\n } else if (typeof entryValue === 'string') {\n // @ts-expect-error - Badly typed for strings.\n entry[entryKey] = [filePath, entryValue];\n } else if (Array.isArray(entryValue)) {\n entryValue.unshift(filePath);\n } else {\n log.error(`Invalid entry type: ${typeof entryValue}`);\n }\n }\n };\n\n if (!initialEntry) {\n return {\n ddHelper: injectedEntry,\n };\n } else if (typeof initialEntry === 'function') {\n // @ts-expect-error - This is webpack / rspack typing conflict.\n return async () => {\n const originEntry = await initialEntry();\n objectInjection(originEntry);\n return originEntry;\n };\n } else if (typeof initialEntry === 'object') {\n objectInjection(initialEntry);\n } else if (typeof initialEntry === 'string') {\n // @ts-expect-error - Badly typed for strings.\n return [injectedEntry, initialEntry];\n } else {\n log.error(`Invalid entry type: ${typeof initialEntry}`);\n return initialEntry;\n }\n return initialEntry;\n };\n\n // We need to prepare the injections before the build starts.\n // Otherwise they'll be empty once resolved.\n const setupInjections = async () => {\n // Prepare the injections.\n await prepareInjections(log, toInject, contentsToInject, context.buildRoot);\n };\n\n // For one-time builds (production mode)\n compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, setupInjections);\n\n // For watch mode / dev server (webpack dev mode)\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, setupInjections);\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 for (const chunk of compilation.chunks) {\n const isEntry = chunk.canBeInitial();\n // Per-chunk content (e.g. context snippets) keys off the chunk\n // content hash, the only chunk source available at this stage.\n const chunkSource = chunk.contentHash?.javascript ?? chunk.hash;\n\n for (const file of chunk.files) {\n const { base, ext } = path.parse(file);\n const isOutputSupported = isFileSupported(ext);\n if (!isOutputSupported) {\n warnUnsupportedFile(log, ext, base);\n continue;\n }\n\n const fileName = base;\n // Resolve static and per-chunk content in one pass.\n const banner = getContentToInject(contentsToInject, InjectPosition.BEFORE, {\n sourceOrHash: chunkSource,\n fileName,\n isEntry,\n });\n const footer = getContentToInject(contentsToInject, InjectPosition.AFTER, {\n sourceOrHash: chunkSource,\n fileName,\n isEntry,\n });\n\n if (banner === '' && footer === '') {\n continue;\n }\n\n compilation.updateAsset(file, (old) => {\n const cached = cache.get(old);\n\n // If anything changed, we need to re-create the source.\n if (!cached || cached.banner !== banner || cached.footer !== footer) {\n const source = new ConcatSource(banner, '\\n', old, '\\n', footer);\n\n // Cache the result.\n cache.set(old, { source, banner, footer });\n return source;\n }\n\n return cached.source;\n });\n }\n }\n };\n\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n });\n\n // We inject the new entry.\n const newEntry = injectEntry(compiler.options.entry);\n compiler.options.entry = newEntry;\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE_RX } from '@dd/core/constants';\nimport { isXpack } from '@dd/core/helpers/bundlers';\nimport {\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 { prepareInjections, 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: ToInjectItem[] = [];\n\n // Storage for all the positional contents we want to inject.\n const contentsToInject: ContentsToInject = [];\n\n context.inject = (item: ToInjectItem) => {\n injections.push(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(log, contentsToInject),\n vite: {\n ...(getRollupPlugin(log, contentsToInject) as PluginOptions['vite']),\n enforce: 'pre',\n transformIndexHtml: {\n order: 'pre',\n handler() {\n // For Vite, we inject MIDDLE content by adding a script tag\n // that references the virtual injected file\n const middleContent = getContentToInject(\n contentsToInject,\n InjectPosition.MIDDLE,\n );\n if (middleContent) {\n // Return a tag descriptor instead of modifying HTML directly\n return [\n {\n tag: 'script',\n attrs: {\n type: 'module',\n src: `/@id/__datadog-helper-file`,\n },\n injectTo: 'head-prepend',\n },\n ];\n }\n return [];\n },\n },\n },\n };\n\n // We need to handle the resolution in xpack,\n // and it's easier to use unplugin's hooks for it.\n if (isXpack(context.bundler.name)) {\n plugin.load = {\n filter: {\n id: INJECTED_FILE_RX,\n },\n handler() {\n return {\n code: getContentToInject(contentsToInject, InjectPosition.MIDDLE),\n };\n },\n };\n } else {\n // In xpack, we need to prepare the injections BEFORE the build starts.\n // Otherwise, the bundler doesn't have the content when it needs it.\n // So we do it in their specific plugin.\n // Here for all the other non-xpack bundlers.\n plugin.buildStart = async () => {\n // Prepare the injections.\n await prepareInjections(log, injections, contentsToInject, context.buildRoot);\n };\n }\n\n return [plugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions, PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-true-end-plugin' as const;\n\nexport const getTrueEndPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n // TODO: Reconsider the lifecycle names around trueEnd and flush together.\n // Having a final hook after \"trueEnd\" is confusing, so these likely need a broader rename.\n const asyncHookFn = async () => {\n await context.asyncHook('asyncTrueEnd');\n };\n const flushHookFn = async () => {\n await context.asyncHook('flush');\n };\n const syncHookFn = () => {\n context.hook('syncTrueEnd');\n };\n const bothHookFns = async () => {\n syncHookFn();\n await asyncHookFn();\n await flushHookFn();\n };\n\n const xpackPlugin: PluginOptions['rspack'] & PluginOptions['webpack'] = (compiler) => {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n };\n\n const rollupPlugin: PluginOptions['rollup'] & PluginOptions['vite'] = {\n async writeBundle() {\n // TODO: Need to fallback here in case the closeBundle isn't called.\n },\n async closeBundle() {\n await bothHookFns();\n },\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n webpack: xpackPlugin,\n esbuild: {\n setup(build) {\n // NOTE: \"onEnd\" is the best we can do for esbuild, but it's very far from being the \"true end\" of the build.\n build.onEnd(async () => {\n await asyncHookFn();\n await flushHookFn();\n });\n // NOTE: \"onDispose\" is strictly synchronous.\n build.onDispose(() => {\n syncHookFn();\n });\n },\n },\n vite: rollupPlugin,\n rollup: rollupPlugin,\n rspack: xpackPlugin,\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n/* eslint-disable arca/import-ordering, arca/newline-after-import-section */\n// This file is mostly generated.\n// Anything between\n// - #imports-injection-marker\n// - #types-export-injection-marker\n// - #internal-plugins-injection-marker\n// - #helpers-injection-marker\n// - #configs-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type {\n BundlerName,\n Env,\n FactoryMeta,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPlugins,\n GlobalContext,\n GlobalData,\n GlobalStores,\n Options,\n OptionsWithDefaults,\n} from '@dd/core/types';\nimport type { UnpluginContextMeta, UnpluginInstance } from 'unplugin';\nimport { createUnplugin } from 'unplugin';\nimport chalk from 'chalk';\n\nimport { validateOptions } from './validate';\nimport { getContext } from './helpers/context';\nimport { wrapGetPlugins } from './helpers/wrapPlugins';\nimport { ALL_ENVS, HOST_NAME } from '@dd/core/constants';\nimport { notifyOnEnvOverrides } from '@dd/core/helpers/env';\nimport { resolveEnable } from '@dd/core/helpers/options';\n// #imports-injection-marker\nimport * as apps from '@dd/apps-plugin';\nimport * as errorTracking from '@dd/error-tracking-plugin';\nimport * as liveDebugger from '@dd/live-debugger-plugin';\nimport * as metrics from '@dd/metrics-plugin';\nimport * as output from '@dd/output-plugin';\nimport * as rum from '@dd/rum-plugin';\nimport { getAnalyticsPlugins } from '@dd/internal-analytics-plugin';\nimport { getAsyncQueuePlugins } from '@dd/internal-async-queue-plugin';\nimport { getBuildReportPlugins } from '@dd/internal-build-report-plugin';\nimport { getBundlerReportPlugins } from '@dd/internal-bundler-report-plugin';\nimport { getCustomHooksPlugins } from '@dd/internal-custom-hooks-plugin';\nimport { getGitPlugins } from '@dd/internal-git-plugin';\nimport { getInjectionPlugins } from '@dd/internal-injection-plugin';\nimport { getTrueEndPlugins } from '@dd/internal-true-end-plugin';\n// #imports-injection-marker\n// #types-export-injection-marker\nexport type { types as AppsTypes } from '@dd/apps-plugin';\nexport type { types as ErrorTrackingTypes } from '@dd/error-tracking-plugin';\nexport type { types as LiveDebuggerTypes } from '@dd/live-debugger-plugin';\nexport type { types as MetricsTypes } from '@dd/metrics-plugin';\nexport type { types as OutputTypes } from '@dd/output-plugin';\nexport type { types as RumTypes } from '@dd/rum-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [metrics.CONFIG_KEY]: metrics.helpers,\n // #helpers-injection-marker\n};\n\nconst red = chalk.bold.red;\n\nconst blockOnDuplicateNames = (names: string[]) => {\n const duplicates = new Set(names.filter((name) => names.filter((n) => n === name).length > 1));\n if (duplicates.size > 0) {\n throw new Error(`Duplicate plugin names: ${red(Array.from(duplicates).join(', '))}`);\n }\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 const pluginStart = Date.now();\n // TODO: Implement config overrides with environment variables.\n // TODO: Validate API Key and endpoint.\n // TODO: Inject a metric logger into the global context.\n\n const options: OptionsWithDefaults = validateOptions(opts);\n\n // Set the host name for the esbuild plugin.\n if (unpluginMetaContext.framework === 'esbuild') {\n unpluginMetaContext.esbuildHostName = HOST_NAME;\n }\n\n // Use \"production\" if there is no env passed.\n const passedEnv: Env = (process.env.BUILD_PLUGINS_ENV as Env) || 'production';\n // Fallback to \"development\" if the passed env is wrong.\n const env = ALL_ENVS.includes(passedEnv) ? passedEnv : 'development';\n // We need to account for how each bundler exposes its version.\n // - (webpack|esbuild|vite).version\n // - rollup.VERSION\n // - rspack.rspackVersion\n const bundlerVersion = bundler.rspackVersion || bundler.version || bundler.VERSION;\n const bundlerName = unpluginMetaContext.framework as BundlerName;\n\n const data: GlobalData = {\n bundler: {\n name: bundlerName,\n version: bundlerVersion,\n },\n env,\n metadata: options.metadata || {},\n packageName: `@datadog/${bundlerName}-plugin`,\n version,\n };\n\n const stores: GlobalStores = {\n errors: [],\n logs: [],\n metrics: new Set(),\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: pluginStart });\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 // Customer-facing plugins are gated by their `<configKey>.enable` flag.\n // Resolving here lets every plugin share the same semantics:\n // - config key absent → disabled\n // - config key present without `enable` → enabled\n // - non-boolean `enable` → coerced, with a single deprecation warning\n const userFacingPlugins: [name: string, configKey: string, GetPlugins][] = [\n // #configs-injection-marker\n ['apps', apps.CONFIG_KEY, apps.getPlugins],\n ['error-tracking', errorTracking.CONFIG_KEY, errorTracking.getPlugins],\n ['live-debugger', liveDebugger.CONFIG_KEY, liveDebugger.getPlugins],\n ['metrics', metrics.CONFIG_KEY, metrics.getPlugins],\n ['output', output.CONFIG_KEY, output.getPlugins],\n ['rum', rum.CONFIG_KEY, rum.getPlugins],\n // #configs-injection-marker\n ];\n\n for (const [name, configKey, getPlugins] of userFacingPlugins) {\n if (resolveEnable(options, configKey, log)) {\n pluginsToAdd.push([name, getPlugins]);\n }\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 // Verify and notify about any overrides from the environment.\n notifyOnEnvOverrides(log);\n // List all our plugins in the context.\n context.pluginNames.push(...context.plugins.map((plugin) => plugin.name));\n // Verify we don't have plugins with the same name, as they would override each other.\n blockOnDuplicateNames(context.pluginNames);\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 AppsTypes,\n ErrorTrackingTypes,\n LiveDebuggerTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport webpack from 'webpack';\n\nimport pkg from '../package.json';\n\nexport type WebpackPluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n AppsTypes,\n ErrorTrackingTypes,\n LiveDebuggerTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogWebpackPlugin = factory.buildPluginFactory({\n bundler: webpack,\n version: pkg.version,\n}).webpack;\n\nexport const version = pkg.version;\nexport const helpers = factory.helpers;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport type {\n BuildReport,\n GlobalContext,\n GlobalData,\n GlobalStores,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nimport { getLoggerFactory } from './logger';\n\nexport const getContext = ({\n start,\n options,\n data,\n stores,\n}: {\n start: number;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n}): GlobalContext => {\n const buildRoot = process.cwd();\n const build: BuildReport = {\n errors: stores.errors,\n warnings: stores.warnings,\n logs: stores.logs,\n metadata: data.metadata,\n timings: stores.timings,\n bundler: data.bundler,\n };\n const context: GlobalContext = {\n // This will be updated in the metrics plugin on initialization.\n addMetric: () => {\n throw new Error('AddMetric function called before it was initialized.');\n },\n auth: options.auth,\n pluginNames: [],\n bundler: {\n ...build.bundler,\n // This will be updated in the bundler-report plugin once we have the configuration.\n outDir: buildRoot,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n buildRoot,\n env: data.env,\n getLogger: getLoggerFactory(data, stores, options.logLevel),\n // This will be updated in the injection plugin on initialization.\n asyncHook: () => {\n throw new Error('AsyncHook function called before it was initialized.');\n },\n hook: () => {\n throw new Error('Hook function called before it was initialized.');\n },\n // This will be updated in the injection plugin on initialization.\n inject: () => {\n throw new Error('Inject function called before it was initialized.');\n },\n plugins: [],\n // This will be updated in the async-queue plugin on initialization.\n queue: () => {\n throw new Error('Queue function called before it was initialized.');\n },\n sendLog: getSendLog(data),\n start,\n version: data.version,\n };\n\n return context;\n};\n"],"names":["INJECTED_FILE","INJECTED_FILE_RX","RegExp","ALL_ENVS","SITES","DEFAULT_SITE","HOST_NAME","green","chalk","bold","yellow","OVERRIDE_VARIABLES","getDDEnvValue","key","process","env","parseBoolEnv","value","defaultValue","lower","toLowerCase","includes","getUsedKey","usedKeys","push","resolveSite","source","errors","parsed","lowerValue","exactMatch","find","s","site","suffixMatches","filter","endsWith","length","reduce","longest","subdomain","slice","test","parseSite","formatErrorEntry","e","Object","entries","map","JSON","stringify","join","getOriginHeaders","opts","bundler","plugin","version","createRequestData","async","options","getForm","defaultHeaders","zip","form","req","Request","method","body","data","pipeThrough","CompressionStream","headers","fromEntries","ERROR_CODES_NO_RETRY","doRequest","auth","url","getData","type","retryOpts","retries","onRetry","maxTimeout","minTimeout","retry","bail","attempt","response","requestInit","duplex","requestHeaders","accessToken","Authorization","apiKey","appKey","fetch","error","ok","errorMessage","status","statusText","details","bodyText","parse","Array","isArray","entry","parseErrorDetails","text","Error","result","json","getSendLog","message","context","payload","ddsource","packageName","service","team","name","metadata","cleanPluginName","replace","isInjectionFile","filename","serializeBuildReport","report","jsonReport","warnings","logs","timings","start","end","duration","writeDuration","inputs","outputs","newEntry","file","filepath","input","newInput","dependencies","dependents","dependency","dependent","output","newOutput","shouldGetGitInfo","gitEnabledFromSourcemaps","errorTracking","sourcemaps","gitEnabledFromRoot","enableGit","formatDuration","days","Math","floor","d","Date","hours","getUTCHours","minutes","getUTCMinutes","seconds","getUTCSeconds","milliseconds","getUTCMilliseconds","timeString","trim","truncateString","str","maxLength","placeholder","stringLength","max","leftStop","min","rightStop","filterSensitiveInfoFromRepositoryUrl","repositoryUrl","startsWith","URL","cleanPath","pathname","protocol","host","normalizeTagValue","prettyObject","obj","String","toString","formatValue","logPriority","debug","info","warn","none","cleanName","split","getLogFn","stores","logLevel","cleanedName","forward","color","c","dim","logFn","console","log","red","cyan","prefix","content","pluginName","time","now","forwardLog","sendLog","subLogger","queue","getTimeLogger","store","label","level","toLog","tags","timer","spans","total","getUncompleteSpans","span","resume","startTime","pause","pauseTime","uncompleteSpans","param","endTime","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","getLoggerFactory","getLogger","subName","logger","HOOKS_TO_TRACE","wrapHook","hookName","hook","wrapWithTiming","fn","args","apply","this","Promise","finally","handler","wrapGetPlugins","getPlugins","arg","initTimer","wrappedPlugins","wrappedPlugin","wrapPlugin","pluginNames","warnedKeys","Set","resolveEnable","configKey","pluginConfig","enable","has","add","CONFIG_KEY","PLUGIN_NAME","APPS_API_PATH","ARCHIVE_FILENAME","BACKEND_FILE_RE","BACKEND_CODE_EXTENSIONS","AUTH_METHODS","validateOptions","resolvedOptions","resolveAuthMethod","authOverrides","Boolean","hasApiKeyAuth","include","dryRun","identifier","description","selfService","permissions","rm","dir","fsp","force","maxRetries","recursive","mkdir","outputFileSync","path","dirname","fs","mkdirSync","writeFileSync","encoding","readFileSync","existsSync","code","getFile","openAsBlob","blob","contentType","File","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","InjectPosition","loadOauth","import","base64Url","buffer","getDatadogOAuthConfig","clientId","getOAuthClientId","authorizationUrl","cacheTokens","openBrowser","redirectUri","timeoutMs","tokenUrl","getOAuthClient","client_id","getAuthorizationServer","issuer","origin","authorization_endpoint","token_endpoint","getOAuthCredentialAccount","createHash","update","digest","getOAuthCredentialFingerprint","respond","res","statusCode","writeHead","tokenResponseToOAuthToken","tokenResponse","receivedAt","access_token","expiresAt","expires_in","expiresIn","refreshToken","refresh_token","scope","tokenType","token_type","isObject","getErrorMessage","isNoEntryError","getErrorCode","createOAuthCredentialEntry","AsyncEntry","secureStorageError","operation","readOAuthTokenFromKeychain","raw","getPassword","token","assertStoredOAuthCredential","saveOAuthToken","cacheSite","credential","setPassword","writeOAuthTokenToKeychain","toCachedToken","deleteOAuthToken","deletePassword","deleteOAuthTokenFromKeychain","getCachedOAuthToken","cachedToken","fromCachedToken","refreshedToken","oauth","authorizationServer","client","refreshTokenGrantRequest","None","processRefreshTokenResponse","refreshOAuthToken","authorizeWithPKCE","codeVerifier","randomBytes","codeChallenge","calculatePKCECodeChallenge","generateCodeChallenge","state","searchParams","set","buildAuthorizationUrl","callbackPromise","redirectUrl","port","Number","isInteger","timeout","settled","server","http","createServer","resolve","reject","finish","on","reqUrl","callbackParameters","validateAuthResponse","get","once","setTimeout","hostname","listen","clearTimeout","listening","close","closeAllConnections","closeIdleConnections","waitForOAuthCallback","opener","platform","command","child","spawn","detached","stdio","unref","tryOpenBrowser","authorizationCodeGrantRequest","processAuthorizationCodeResponse","exchangeAuthorizationCode","tokenCache","Map","resolveOAuthToken","pending","persistAfterSuccessfulRequest","resolveOAuthTokenFromStorage","catch","delete","AUTH_GUIDANCE","MissingAuthenticationError","constructor","super","getAuthenticatedRequest","siteSubdomain","doOAuthRequest","ensureProgram","node","isProgramNode","isStringLiteral","isTypeOnly","importKind","exportKind","extractExportedFunctions","ast","program","declarations","id","kind","init","spec","specifiers","local","buildDeclarationMap","backendExports","declaration","namesFromDeclaration","localName","exported","validateSpecifierBinding","enumerateBackendExports","backendExport","NON_CALLABLE_INIT_TYPES","isNonCallableInit","decl","flatMap","encodeQueryName","ref","posixPath","relativePath","sep","generateProxyModule","exports","lines","exportName","queryName","isPackageExportInstalled","packageExport","fromDir","require","paths","generateVirtualEntryContent","functionName","entryPath","projectRoot","hasDatadogAppsBackendRuntime","isActionCatalogInstalled","walkAst","visitors","visit","currentNode","_","getSpecializedVisitor","keys","visitChildren","item","isAstNode","analyzeModuleScope","nodeWithRange","range","scopeManager","eslintScope","analyze","ecmaVersion","ignoreEval","sourceType","referencesByIdentifier","scopes","reference","references","moduleScope","getModuleScope","resolveIdentifier","scopeAnalysis","resolved","isImportVariable","variable","defs","some","definition","getModuleVariable","globalScope","findActionCatalogCallSites","callState","unsupportedAliases","collectUnsupportedActionCatalogAliases","callSites","CallExpression","callee","resolvesTo","unsupportedActionCatalogCall","actionFunctions","optional","isNamespaceMember","hasUnsupportedMemberAccess","classifyActionCatalogCall","VariableDeclarator","aliasVariable","getDeclaredVariables","actionNamespaces","aliasNames","properties","property","computed","collectPatternIdentifiers","getActionCatalogAliasVariables","AssignmentExpression","left","right","getResolvedVariables","aliasIdentifiers","getAssignedActionCatalogAliasVariables","root","getMemberExpressionRoot","object","variables","resolvesToModuleVariable","identifiers","names","wantedNames","pattern","argument","elements","element","unsupported","ACTION_CATALOG_PACKAGE","resolveStaticDefinitionForIdentifier","modules","moduleId","record","unsupportedMissingModuleRecordForVariable","isDefinitionIdentifier","unsupportedUnresolvedIdentifier","resolveVariable","visitedExports","resolveExport","hops","reason","requestKind","unsupportedMissingModuleRecordForExport","unsupportedDefaultExport","visitKey","unsupportedCycle","explicitExport","exportsByName","binding","exportReason","unsupportedExport","importedName","resolvedId","sourceModuleId","sourceExportName","resolveExplicitExport","candidate","starExport","starExports","isSameLocalDefinition","unsupportedAmbiguousStarExport","unsupportedMissingExport","resolveStarExport","importBinding","importsByVariable","unsupportedDefaultImport","variableName","unsupportedNamespaceImport","resolveImportBinding","topLevelBindingsByVariable","declarationKind","unsupportedMutableBinding","bindingReason","unsupportedBinding","unsupportedMissingStaticBinding","resolveExpression","rawExpression","expression","unwrapStaticExpression","valueType","unsupportedNonStringLiteral","resolveLiteral","expressions","unsupportedDynamicTemplateLiteral","quasis","quasi","cooked","resolveTemplateLiteral","unsupportedStaticDefinition","unsupportedUninitializedConst","seenVariables","resolveIdentifierValue","resolvedExpression","resolveObjectMemberExpression","resolveMemberExpressionValue","expressionType","unsupportedExpression","unsupportedOptionalMemberExpression","unsupportedComputedMemberExpression","propertyType","unsupportedNonStaticMemberProperty","objectExpression","resolveObjectExpressionValue","propertyName","match","unsupportedObjectSpread","unsupportedComputedObjectProperty","getStaticPropertyKey","unsupportedDuplicateObjectProperty","unsupportedAccessorObjectProperty","hasExpressionValue","unsupportedObjectPropertyValue","unsupportedMissingObjectProperty","resolveObjectPropertyExpression","unsupportedNonObjectMemberValue","memberExpression","mutatedImportedObjectVariables","unsupportedImportedObjectMutation","collectMutatedImportedObjectVariables","mutatedVariables","values","markMutatedImportedPattern","UpdateExpression","UnaryExpression","operator","ForInStatement","markMutatedImportedForIterationTarget","ForOfStatement","markMutatedImportedIdentifier","resolveImportedObjectAlias","initializer","getVariableInitializer","getImportedObjectAliasRoot","current","isTypeScriptExpressionWrapper","PACKAGE_MANAGER_DIRS","createParsedModuleRecord","buildRoot","staticDependencies","shouldTraverseCollectedModule","staticModuleDependencies","staticDependencyIds","staticModuleSources","getStaticModuleSources","index","collectStaticModuleDependencies","unsupportedDependencies","collectUnsupportedModuleDependencies","collectImportBindings","collectExportBindings","collectStarExports","collectTopLevelBindings","getResolvedSource","specifier","getModuleExportName","imported","collectNamespaceExportBinding","collectNamedExportBindings","declarator","collectDeclarationExportBindings","exportedName","getExportAllExportedName","bindings","collectTopLevelNodeBindings","markAssignedPattern","markForIterationTarget","markReassignedTopLevelBindings","collectVariableDeclarationBindings","markAssignedVariable","ImportExpression","getLiteralSpecifier","getImportExpressionSpecifier","shouldFailDynamicImport","isImportCallExpression","arguments","getImportCallSpecifier","isLocalSpecifier","isLocalRequireCall","getRequireSpecifier","extension","relative","isAbsolute","segment","fallback","unsupportedModuleGraphDependency","extractConnectionIdsFromModuleGraph","entryId","connectionIds","visited","shift","dependencyId","walkModuleGraph","imports","functions","namespaces","collectActionCatalogImports","analyzeActionCatalogScopes","callSite","connectionId","extractConnectionIdFromActionCall","sort","firstArg","connectionIdProperty","isConnectionIdKey","findConnectionIdProperty","resolveStaticStringValue","getStaticStringUnsupportedReason","VIRTUAL_MODULE_ID_RE","createBackendModuleGraphCollector","records","moduleParsed","moduleInfo","normalizeViteModuleId","importedIdResolutions","importedIds","getStaticDependencyIds","getModuleRecords","createBackendConnectionIdCollector","moduleGraphCollector","getAllowedConnectionIds","createVirtualPlugin","virtualEntries","enforce","resolveId","moduleSideEffects","load","getBaseBackendBuildConfig","plugins","configFile","build","minify","target","rollupOptions","format","inlineDynamicImports","preserveEntrySignatures","treeshake","onwarn","warning","defaultHandler","extensions","formatRef","func","bundleBackendFunction","viteBuild","displayName","virtualId","virtualContent","cwd","generateDevVirtualEntryContent","absolutePath","connectionIdCollector","baseConfig","write","enrichedFunc","allowedConnectionIds","executeScriptViaDatadog","scriptBody","doAuthenticatedRequest","endpoint","attributes","query","randomUUID","fqn","script","backendFunctionArgs","onlyTriggerManually","template_params","initialResult","receiptId","detail","title","attrs","done","pollQueryExecution","sendError","setHeader","success","HttpError","validateAndBundle","functionsByName","bundle","chunk","parseRequestBody","createDevServerMiddleware","getBackendFunctions","initialFunctions","f","next","backendFunctions","handleDebugBundle","handleExecuteAction","collectAssets","patterns","matches","all","glob","absolute","nodir","flat","relativePaths","from","commonPrefix","segments","i","every","p","findCommonPrefix","strippedPath","getAbsolutePath","getClosest","currentDir","closest","getNearestCommonDirectory","dirs","splitPaths","minLength","parts","commonParts","component","getPackageJson","packageJsonPath","packageJson","pkg","repository","inputRepositoryUrl","getRepositoryUrlFromPkg","sanitizedUrl","resolveRepositoryUrl","plainIdentifier","buildIdentifier","resolveAppBuilderUrl","action","appBuilderUrl","appBuilderId","buildMissingAppUrlWarning","archivePath","archiveFile","FormData","append","versionName","uploadArchive","archive","intakeUrl","appId","bundlerName","configurationString","summary","assets","prettyBytes","app_builder_url","app_builder_id","shouldPublish","version_id","releaseUrl","getReleaseUrl","releaseResponse","releaseAppBuilderUrl","err","MANIFEST_FILE_NAME","writeManifestFile","manifestDir","mkdtemp","os","tmpdir","manifestPath","writeFile","manifest","backend","protectionLevel","runAs","buildManifest","manifestAsset","cleanup","handleUpload","backendOutputs","outDir","git","handleTimer","archiveDir","cleanupManifest","toThrow","identifierTimer","remote","relativeOutdir","assetGlobs","backendPaths","allAssets","a","asset","bundleName","archiveTimer","tempDir","JSZip","binary","compression","compressionOptions","createWriteStream","generateNodeStream","streamFiles","pipe","createArchive","uploadTimer","uploadErrors","uploadWarnings","listOfErrors","cause","stack","APPS_RUNTIME_PATH","__dirname","doDryRunAuthenticatedRequest","getVitePlugin","inject","position","MIDDLE","setBackendFunctions","functionsByEntryPath","createBackendFunctionRegistry","transform","exclude","exportNames","proxyCode","refPath","proxyExports","buildProxyModule","closeBundle","backendOutDir","allowedConnectionIdsByEntryPath","emptyOutDir","entryFileNames","isEntry","fileName","buildBackendFunctions","configureServer","middlewares","use","validatedOptions","vite","decomposePath","absoluteOutDir","sourcemapFilePath","extname","minifiedFilePath","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","DEBUG_ID_RX","extractDebugId","fileContent","fd","open","Buffer","alloc","bytesRead","read","readFilePrefix","exec","matchDebugId","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","pathParts","prefixParts","normalizedPath","partialPrefix","getPayload","sourcemap","debugId","resultMinFile","resultSourcemap","repeatedPrefix","getSourcemapValidity","debug_id","minified_url","files","trackedFilesMatcher","matchSourcemap","basename","hash","repository_url","getStatusCodeTag","getErrorTypeTag","statusCodeTag","incrementUploadMetric","uploadMetrics","metricKey","getMetricKey","currentMetric","metrics","recordSourcemapUploadRetry","baseTags","recordSourcemapUploadFailure","addSourcemapUploadMetrics","sendMetrics","timestamp","metric","points","getSourcemapUploadMetrics","addMetric","Blob","upload","payloads","queueTimer","PQueue","default","concurrency","maxConcurrency","createSourcemapUploadMetrics","addPromises","warningMessage","bailOnError","onIdle","uploadSourcemaps","sourcemapsTime","minifiedPathPrefix","getSourcemapsFiles","sendTime","git_repository_url","git_commit_sha","plugin_version","project_path","releaseVersion","payloadsTimer","payloadsQueue","debugIdCount","addAll","errorMsg","fileMetadata","errorToPrint","sendSourcemaps","validateSourcemapsOptions","config","toReturn","sourcemapsCfg","validateMinifiedPathPrefix","timeOptions","sourcemapsResults","sendSourcemapUploadMetrics","gitInfo","buildReport","sourcemapsHandled","handleSourcemaps","totalTime","repoData","asyncTrueEnd","runtimeStubs","buildMetadataGlobal","getRuntimeBootstrap","resolveCjsDefaultExport","generateFunctionId","functionPath","anonymousSiblingIndex","typesModule","getFunctionName","locationSuffix","line","loc","column","getFunctionLocation","parent","isIdentifier","isObjectMethod","isClassMethod","isClassPrivateMethod","getPropertyLikeName","isVariableDeclarator","isAssignmentExpression","isMemberExpression","isOptionalMemberExpression","objectName","getMemberObjectName","getMemberPropertyName","getAssignmentTargetName","isObjectProperty","isClassProperty","isClassPrivateProperty","isThisExpression","parentObjectName","isComputed","isPrivateName","isNumericLiteral","isBigIntLiteral","hasSkipComment","skipComment","leadingComments","comment","getLocalVariableDeclarations","functionNode","isBlockStatement","paramNames","params","getPatternIdentifiers","paramSet","stmt","isVariableDeclaration","declarationEnd","temporalDeadZones","cappedVariables","localNames","localNameSet","temporalDeadZonesByName","functionBody","collectTemporalDeadZonesFromStatement","getNestedTemporalDeadZonesByName","isFunctionDeclaration","isClassDeclaration","collectTemporalDeadZonesFromBlock","isIfStatement","consequent","alternate","isForStatement","isForInStatement","isForOfStatement","isWhileStatement","isDoWhileStatement","isSwitchStatement","caseClause","cases","addTemporalDeadZonesFromStatements","collectTemporalDeadZonesFromSwitch","isTryStatement","block","finalizer","isLabeledStatement","isWithStatement","statements","scopeStart","addVariableDeclarationTemporalDeadZones","addTemporalDeadZone","existingZones","isRestElement","isAssignmentPattern","isObjectPattern","isArrayPattern","isTSParameterProperty","parameter","REQUIRED_PEER_DEPS","traverse","babelTypes","MagicString","hasLoadedTransformRuntime","requireOptionalPeerDep","loadKnownPeerDep","dep","isMissingPeerDepError","missingDep","rewrapMissingPeerDepError","HAS_FUNCTION_SYNTAX","transformCode","honorSkipComments","functionTypes","namedOnly","failedCount","instrumentedCount","skippedByCommentCount","skippedUnsupportedCount","totalFunctions","containsUnsupportedImports","skippedFileCount","sourceFilename","targets","constructorBodyStartsByNode","constructorsUsingThisAlias","superCallsByConstructorNode","anonymousCountByParent","probeVarCounter","Function","derivedConstructor","isDerivedClassMethod","getDerivedConstructor","statement","collectSuperCallTargetsFromNode","getSuperCallTargets","generator","canInstrumentFunction","isStatement","isExportDeclaration","parentPath","shouldSkipFunction","isArrowFunctionExpression","getFunctionKind","parentNode","functionId","idx","probeVarName","entryVars","getParameterNames","localVars","isExpressionBody","hasSequenceExpressionBody","isSequenceExpression","constructorPath","isFunction","getDerivedConstructorForLexicalThis","useThisAlias","returns","needsTrailingReturn","alwaysReturns","directivesEnd","collectReturnStatements","directives","bodyStart","bodyEnd","functionEnd","aliasesExpressionBodySuperCall","isSuperCallExpression","bodyParenStart","extra","parenStart","probeIdx","superCallRangesHandledByExpressionBodies","ranges","getRangeKey","getSuperCallRangesHandledByExpressionBodies","constructorThisAliasTargets","constructorNode","superCalls","superCall","getConstructorThisAliasTargets","injectInstrumentation","injectConstructorThisAlias","generateMap","hires","entryHelper","rvVarName","receiverArg","entryVarsList","hasParams","argsArg","probeDecl","character","entryHelperDecl","entryCall","catchBlock","openingParens","parens","getLeadingArrowBodyParens","closingParens","getTrailingArrowBodyParens","parenCount","openingParen","closingParen","remove","expressionSuffix","suffix","getReturnCaptureArgs","bodyPrefix","preamble","ret","returnCaptureArgs","argStart","argEnd","assignmentPrefix","hasSequenceExpressionArgument","assignmentSuffix","appendLeft","anchor","trailingReturnCaptureArgs","postamble","collectSuperCallTargetsFromUnknown","isNode","isCallExpression","isSuper","classPath","classNode","isClassExpression","superClass","exitPosition","localsArg","availableLocals","isInTemporalDeadZone","getLocalCaptureArg","isReturnStatement","last","VALID_FUNCTION_KINDS","DD_LD_LIMIT","Infinity","getLiveDebuggerPlugin","pluginOptions","transformedFileCount","totalFilesWithFunctions","inputMap","ctx","native","getNativeBuildContext","inputSourceMap","getInputSourceMap","composedMap","instrumentMap","remapping","_file","depth","composeWithInputMap","buildEnd","metadataVersion","BEFORE","injectIntoAllChunks","defaultFilters","thresholds","count","accumulator","currentPoint","getTimestamp","getDefaultTags","configuredTags","defaultTags","getMetric","getMetricsToSend","filters","metricsToSend","processedMetrics","toSend","m","formatCwd","getDisplayName","pop","formatModuleName","getModuleName","module","compilation","userRequest","moduleGraph","getIssuer","_identifier","getModulePath","formatLoaderName","loader","getValueContext","numColor","nameColor","sortDesc","attr","b","aVal","bVal","getTimingValues","times","durationsToPrint","top","increment","outputTexts","globalContext","valuesToPrint","loaders","tapables","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","serializedReport","fileDependencies","fileDependents","dependenciesSet","dependentsSet","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","getModulesValues","nbModules","nbAssets","nbWarnings","nbErrors","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","v","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","METRICS_API_PATH","metricIterations","metricsNames","nameA","nameB","localeCompare","series","FN_TO_WRAP","loadersMap","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","cb","pluginTiming","events","isLoader","initialFunction","modulePath","moduleTiming","performance","statsObject","loaderTiming","getEsbuildPlugin","setup","initialOptions","metafile","timeWrap","initialPlugins","oldSetup","esbuild","wrapPlugins","onEnd","timeResult","asyncHook","Loaders","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","getPromiseTapPatch","checkNewHooks","returnValue","then","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","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","initializeMetricsCollector","enableDefaultPrefix","enableTracing","legacyPlugin","webpack","rspack","timeBuild","needLegacyPlugin","timingsReport","sendCollectedMetrics","timeMetrics","clear","getMetricsToSendFromCollectedMetrics","timeSend","computeMetrics","timeUniversal","universalMetrics","entriesPerInput","assetsPerInput","entriesPerAsset","cleanAssetName","entryName","assetName","getUniversalMetrics","timePlugin","pluginMetrics","pluginDuration","pluginCount","hookDuration","getPluginMetrics","timeLoader","loaderMetrics","getLoaderMetrics","allMetrics","timeReport","universalPlugin","buildStart","flush","sanitizeOutputPath","validateFilesOptions","getXpackPlugin","stats","statsTimer","statsJson","toJson","children","chunks","chunkGroupAuxiliary","chunkGroupChildren","chunkGroups","chunkRelations","entrypoints","ids","nestedModules","relatedAssets","reasons","chunkModules","getRollupPlugin","writeBundle","fileValue","timeWrite","pathOption","outputPath","getFilePath","dataToWrite","writable","readable","JsonStreamStringify","prom","outputJson","queuedWrite","timeSerialization","getStats","rollup","getOutputs","VARIANT_CHARS","getSourceCodeContextSnippet","contextOptions","ddDebugId","withVersion","variantIndex","charCodeAt","withVariant","stringToUUID","sourceOrHash","getPrivacyPlugin","transformOptions","helperCodeExpression","privacy","addToDictionaryHelper","inlineSourceMap","embedCodeInSourceMap","buildTransformOptions","dictionaryEntryCount","fileCount","nativeBuildContext","framework","instrument","privacyDictionarySize","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","client_token","validateSDKOptions","sdkWithDefault","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacyWithDefault","addToDictionaryFunctionName","validateSourceCodeContextOptions","sourceCodeContext","cfg","sdkResults","privacyResults","sourceCodeContextResults","privacyPlugin","getAnalyticsPlugins","buildStartFn","getAsyncQueuePlugins","promise","wrappedPromise","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","fullPath","in","proms","getAllEntryFiles","sync","resolveDir","original","resolutionError","EXTENSION_RX","QUERY_RX","getType","lastIndex","BUNDLER_SPECIFICS","cleanReport","cleanedReport","reportFilepath","cleanedPath","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","entryNames","resolvedEntries","timeBuildReport","onStart","timeEntries","timeCollect","tempEntryFiles","tempSourcemaps","reportInputsIndexed","reportOutputsIndexed","timeIndex","metaInputsIndexed","metaOutputsIndexed","getRealPathFromInjectionProxy","entryPoint","metaInput","actualImport","imp","timeInputs","bytes","timeOutputs","inputFiles","inputName","inputFound","inputFile","timeSourcemaps","foundOutput","meta","FILE_EXCEPTIONS_RX","isFileSupported","getAllImports","allImports","metaFile","isRelative","absoluteImportPath","external","entryFile","entryInputs","entryOutputs","outputFile","timeDeps","absoluteDependencyPath","dependencyFile","timeModuleParsing","timeInputsOutputs","timeCompleteDeps","importsReport","onLog","logItem","renderError","cleanId","newDependencies","dynamicallyImportedIds","newDependents","dynamicImporters","importers","tempOutputsImports","cleanedDependency","cleanedDependent","byteLength","modulepath","moduleSize","originalLength","statSync","renderedLength","moduleFile","importName","cleanedImport","importFile","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","modulesPerFile","moduleIndex","tempDeps","isModuleSupported","moduleIdentifier","cleanExternalName","indexModule","mod","moduleToIndex","blocks","externalType","createIndexedModule","keysToIndex","indexes","keysOfModuleToIndexOn","indexValue","valueToIndex","getKeysToIndex","previousModule","getAllDependencies","getModuleFromDep","request","cleanRequest","isExternal","finishModules","finishedModules","timeGraph","moduleDeps","depIdentifier","depDeps","timeAssign","depsReport","depInput","getAssets","getChunkFiles","auxiliaryFiles","timeChunks","chunkGraph","getChunkModules","m2","fileModules","outputFound","getAllChunksFromGroup","chunkGroup","allChunks","childGroup","childrenIterable","childChunks","entrypoint","entryFiles","entryFilename","getChunkEntryModulesIterable","getBuildReportPlugins","getAbsoluteOutDir","getOutDirsFromOutputs","outputOptions","o","xpackPlugin","rawConfig","vitePlugin","configResolved","outDirs","getBundlerReportPlugins","absWorkingDir","outdir","outfile","inDirs","normalizedInput","getIndirsFromInputs","computedCwd","renderStart","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","TrackedFilesMatcher","trackedFiles","trackedFilenames","getFilename","list","displaySource","src","srcmapPath","onSourcesNotFound","buff","srcmapObj","sources","filtered","matchSources","filenameAlreadyMatched","concat","rawTrackedFilesList","rawList","forEach","lastIndexOf","substring","gitRemote","remotes","getRemotes","defaultRemote","getDefaultRemoteName","refs","getConfig","gitHash","revparse","gitTrackedFiles","gitBranch","branch","gitMessage","show","gitAuthorAndCommitter","getGitPlugins","timeGit","processGit","gitDir","baseDir","maxConcurrentProcesses","simpleGit","newSimpleGit","repositoryData","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","commit","author","email","date","committer","getRepositoryData","DISTANT_FILE_RX","SUPPORTED_EXTENSIONS","processLocalFile","readFile","hasChunkInjection","contentsToInject","getContentToInject","contentToInject","resolveWithFallback","timeoutId","race","processDistantFile","itemId","prepareInjections","toInject","dynamicPerChunk","isPerChunk","userFn","staticInject","resolvedStaticInject","normalize","isNodeSystemError","ext","warnUnsupportedFile","promises","onResolve","onLoad","tmpDir","realpathSync","absoluteFilePath","injectionRx","initialInject","namespace","contents","AFTER","hasBeforeAfterInjection","base","mapPath","banner","footer","cleaned","sourcefile","TO_INJECT_ID","TO_INJECT_SUFFIX","renderChunk","prepend","importer","resolution","getModuleInfo","hasDefaultExport","cache","WeakMap","ConcatSource","shutdown","rmSync","setupInjections","beforeRun","watchRun","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","processAssets","canBeInitial","chunkSource","contentHash","javascript","updateAsset","old","cached","initialEntry","injectedEntry","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","transformIndexHtml","order","injectTo","getTrueEndPlugins","asyncHookFn","flushHookFn","syncHookFn","bothHookFns","rollupPlugin","onDispose","CONFIG_KEY$2","metrics.CONFIG_KEY","metrics.helpers","datadogWebpackPlugin","createUnplugin","unpluginMetaContext","pluginStart","validateMetadata","envRaw","resolvedSite","defineProperty","enumerable","esbuildHostName","passedEnv","BUILD_PLUGINS_ENV","bundlerVersion","rspackVersion","VERSION","getContext","timeInit","pluginsToAdd","customPlugins","userFacingPlugins","apps.CONFIG_KEY","apps.getPlugins","errorTracking.CONFIG_KEY","errorTracking.getPlugins","liveDebugger.CONFIG_KEY","liveDebugger.getPlugins","metrics.getPlugins","output.CONFIG_KEY","output.getPlugins","rum.CONFIG_KEY","rum.getPlugins","overridenValues","k","usedKey","notifyOnEnvOverrides","duplicates","n","blockOnDuplicateNames","factory.buildPluginFactory","factory.helpers"],"mappings":"s1BAIO,MAAMA,EAAgB,wBAChBC,EAAmB,IAAIC,OAAOF,GAE9BG,EAAW,CAAC,cAAe,aAAc,QAMzCC,EAAQ,CACjB,gBACA,oBACA,oBACA,eACA,eACA,mBACA,oBACA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I89D,EAAW1rD,KAAO,EAClB,MAAM,IAAI5N,MAAM,2BAA2BuG,GAAI5G,MAAMiwB,KAAK0pC,GAAYh9D,KAAK,SAC/E,EAqIIk9D,CAAsBn5D,EAAQ2J,aAE9B3J,EAAQ2I,KAAK,OAAQ3I,GACrB83D,EAAS32D,MAEFnB,EAAQ6qB,OAAA,GAClB,EClL+BuuC,CAA2B,CAC3Dh9D,QAASw9C,EACTt9C,QAASu0B,KACV+oB,QAEUt9C,GAAUu0B,GACVyoB,GAAU+f"}
1
+ {"version":3,"file":"index.js","sources":["../../../../core/src/constants.ts","../../../../core/src/helpers/env.ts","../../../../factory/src/validate.ts","../../../../core/src/helpers/site.ts","../../../../core/src/helpers/request.ts","../../../../core/src/helpers/log.ts","../../../../core/src/helpers/plugins.ts","../../../../core/src/helpers/strings.ts","../../../../factory/src/helpers/logger.ts","../../../../factory/src/helpers/wrapPlugins.ts","../../../../core/src/helpers/options.ts","../../../../plugins/apps/src/constants.ts","../../../../plugins/apps/src/validate.ts","../../../../core/src/helpers/fs.ts","../../../../core/src/types.ts","../../../../plugins/apps/src/auth.ts","../../../../plugins/apps/src/backend/ast-parsing/type-guards.ts","../../../../plugins/apps/src/backend/ast-parsing/extract-backend-functions.ts","../../../../plugins/apps/src/backend/ast-parsing/walk-ast.ts","../../../../plugins/apps/src/backend/ast-parsing/module-scope.ts","../../../../plugins/apps/src/backend/ast-parsing/action-catalog-call-sites.ts","../../../../plugins/apps/src/backend/ast-parsing/action-catalog-imports.ts","../../../../plugins/apps/src/backend/ast-parsing/static-definition-resolution.ts","../../../../plugins/apps/src/backend/ast-parsing/static-string-resolution.ts","../../../../plugins/apps/src/backend/ast-parsing/module-graph.ts","../../../../plugins/apps/src/backend/ast-parsing/extract-connection-ids-from-module-graph.ts","../../../../plugins/apps/src/backend/ast-parsing/walk-module-graph.ts","../../../../plugins/apps/src/backend/ast-parsing/reject-node-builtin-imports.ts","../../../../plugins/apps/src/backend/ast-parsing/ambient-global-access.ts","../../../../plugins/apps/src/backend/ast-parsing/reject-restricted-globals.ts","../../../../plugins/apps/src/backend/ast-parsing/warn-divergent-globals.ts","../../../../plugins/apps/src/backend/ast-parsing/run-backend-static-checks.ts","../../../../plugins/apps/src/backend/encodeQueryName.ts","../../../../plugins/apps/src/backend/proxy-codegen.ts","../../../../plugins/apps/src/backend/shared.ts","../../../../plugins/apps/src/backend/virtual-entry.ts","../../../../plugins/apps/src/vite/backend-module-graph-collector.ts","../../../../plugins/apps/src/vite/backend-connection-id-collector.ts","../../../../plugins/apps/src/vite/backend-static-checks-plugin.ts","../../../../plugins/apps/src/vite/build-config.ts","../../../../plugins/apps/src/archive.ts","../../../../plugins/apps/src/assets.ts","../../../../plugins/apps/src/vite/custom-credentials-resolver.ts","../../../../plugins/apps/src/vite/build-package.ts","../../../../plugins/apps/src/vite/dev-server-module-graph.ts","../../../../plugins/apps/src/vite/execution-epoch.ts","../../../../plugins/apps/src/vite/retry-delay.ts","../../../../plugins/apps/src/vite/local-execution.ts","../../../../plugins/apps/src/vite/dev-server.ts","../../../../plugins/apps/src/vite/index.ts","../../../../plugins/apps/src/vite/build-backend-functions.ts","../../../../plugins/apps/src/index.ts","../../../../plugins/error-tracking/src/constants.ts","../../../../plugins/error-tracking/src/sourcemaps/files.ts","../../../../plugins/error-tracking/src/sourcemaps/debugId.ts","../../../../plugins/error-tracking/src/sourcemaps/payload.ts","../../../../plugins/error-tracking/src/sourcemaps/upload-metrics.ts","../../../../plugins/error-tracking/src/sourcemaps/sender.ts","../../../../plugins/error-tracking/src/sourcemaps/index.ts","../../../../plugins/error-tracking/src/validate.ts","../../../../plugins/error-tracking/src/index.ts","../../../../plugins/live-debugger/src/constants.ts","../../../../plugins/live-debugger/src/filter.ts","../../../../plugins/live-debugger/src/runtime-bootstrap.ts","../../../../plugins/live-debugger/src/transform/cjs-interop.ts","../../../../plugins/live-debugger/src/transform/functionId.ts","../../../../plugins/live-debugger/src/transform/instrumentation.ts","../../../../plugins/live-debugger/src/transform/scopeTracker.ts","../../../../plugins/live-debugger/src/transform/index.ts","../../../../plugins/live-debugger/src/types.ts","../../../../plugins/live-debugger/src/validate.ts","../../../../plugins/live-debugger/src/index.ts","../../../../plugins/metrics/src/collector.ts","../../../../plugins/metrics/src/common/filters.ts","../../../../plugins/metrics/src/constants.ts","../../../../plugins/metrics/src/common/helpers.ts","../../../../plugins/metrics/src/common/output/text.ts","../../../../plugins/metrics/src/common/sender.ts","../../../../plugins/metrics/src/esbuild-plugin/plugins.ts","../../../../plugins/metrics/src/esbuild-plugin/index.ts","../../../../plugins/metrics/src/webpack-plugin/loaders.ts","../../../../plugins/metrics/src/webpack-plugin/tapables.ts","../../../../plugins/metrics/src/webpack-plugin/index.ts","../../../../plugins/metrics/src/index.ts","../../../../plugins/metrics/src/common/aggregator.ts","../../../../plugins/output/src/constants.ts","../../../../plugins/output/src/validate.ts","../../../../plugins/output/src/index.ts","../../../../plugins/rum/src/constants.ts","../../../../plugins/rum/src/debugId.ts","../../../../plugins/rum/src/getSourceCodeContextSnippet.ts","../../../../plugins/rum/src/privacy/constants.ts","../../../../plugins/rum/src/privacy/index.ts","../../../../plugins/rum/src/privacy/transform.ts","../../../../plugins/rum/src/sdk.ts","../../../../plugins/rum/src/validate.ts","../../../../plugins/rum/src/index.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","../../../../plugins/apps/src/vite/guarded-wrapper.ts","../../../../plugins/apps/src/vite/shared-module-singleton.ts","../../../../plugins/apps/src/vite/network-guard.ts","../../../../plugins/apps/src/vite/env-guard.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\nexport const INJECTED_FILE = '__datadog-helper-file';\nexport const INJECTED_FILE_RX = new RegExp(INJECTED_FILE);\n\nexport const ALL_ENVS = ['development', 'production', 'test'] as const;\nexport const ALL_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack', 'rolldown', 'farm'];\nexport const SUPPORTED_BUNDLERS = ['webpack', 'vite', 'esbuild', 'rollup', 'rspack'] as const;\n\n// source of truth: site parameter column of the site list in\n// https://docs.datadoghq.com/getting_started/site/\nexport const SITES = [\n 'datadoghq.com',\n 'us3.datadoghq.com',\n 'us5.datadoghq.com',\n 'datadoghq.eu',\n 'ddog-gov.com',\n 'us2.ddog-gov.com',\n 'ap1.datadoghq.com',\n 'ap2.datadoghq.com',\n 'datad0g.com',\n] as const;\n\nexport const DEFAULT_SITE = SITES[0];\n\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 chalk from 'chalk';\n\nimport type { Logger } from '../types';\n\nconst green = chalk.bold.green;\nconst yellow = chalk.bold.yellow;\n\n// All the variables that can be overriden, listed for easier code search:\n// - DD_API_KEY\n// - DATADOG_API_KEY\n// - DD_APP_KEY\n// - DATADOG_APP_KEY\n// - DD_SOURCEMAP_INTAKE_URL\n// - DATADOG_SOURCEMAP_INTAKE_URL\n// - DD_APPS_PACKAGE_DIR\n// - DATADOG_APPS_PACKAGE_DIR\n// - DD_OAUTH_ACCESS_TOKEN\n// - DATADOG_OAUTH_ACCESS_TOKEN\n// - DD_SITE\n// - DATADOG_SITE\nexport const OVERRIDE_VARIABLES = [\n 'API_KEY',\n 'APP_KEY',\n 'SOURCEMAP_INTAKE_URL',\n 'APPS_PACKAGE_DIR',\n 'OAUTH_ACCESS_TOKEN',\n 'SITE',\n] as const;\ntype ENV_KEY = (typeof OVERRIDE_VARIABLES)[number];\n\n// Return the environment variable that would be prefixed with either DATADOG_ or DD_.\nexport const getDDEnvValue = (key: ENV_KEY) => {\n return process.env[`DATADOG_${key}`] || process.env[`DD_${key}`];\n};\n\n// Parse a boolean env var that can be set as 0/1 or false/true (case-insensitive).\n// Returns defaultValue when the variable is not set or the value is unrecognized.\nexport const parseBoolEnv = (value: string | undefined, defaultValue: boolean): boolean => {\n if (value === undefined) {\n return defaultValue;\n }\n const lower = value.toLowerCase();\n if (['1', 'true', 'yes', 'on'].includes(lower)) {\n return true;\n }\n if (['0', 'false', 'no', 'off'].includes(lower)) {\n return false;\n }\n return defaultValue;\n};\n\n// Returns the keys that are defined in the environment.\nexport const getUsedKey = (key: ENV_KEY) => {\n const usedKeys: string[] = [];\n if (process.env[`DD_${key}`]) {\n usedKeys.push(`DD_${key}`);\n }\n if (process.env[`DATADOG_${key}`]) {\n usedKeys.push(`DATADOG_${key}`);\n }\n return usedKeys;\n};\n\n// Keep track of which configurations are overriden by the environment.\nexport const notifyOnEnvOverrides = (log: Logger) => {\n const overridenValues: string[] = [];\n\n for (const value of OVERRIDE_VARIABLES) {\n const usedKeys = getUsedKey(value);\n\n if (\n usedKeys.length > 1 &&\n !usedKeys.every((k) => process.env[k] === process.env[usedKeys[0]])\n ) {\n // Notify if more than one is defined, and that they are different.\n // Resulting in a conflict, given getDDEnvValue() we resolve with DATADOG_${value}.\n const keys = usedKeys.map((k) => yellow(k)).join(' and ');\n const usedKey = yellow(`DATADOG_${value}`);\n log.warn(`Conflicting keys ${keys}, will use ${usedKey}`);\n overridenValues.push(`${keys} (using ${usedKey})`);\n } else if (usedKeys.length) {\n // Key is used with no conflicts.\n const keys = usedKeys.map((k) => green(k)).join(' and ');\n overridenValues.push(`${keys} (same value)`);\n }\n }\n\n if (overridenValues.length) {\n log.info(`Overrides from environment:\\n - ${overridenValues.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 { DEFAULT_SITE } from '@dd/core/constants';\nimport { getDDEnvValue } from '@dd/core/helpers/env';\nimport { parseSite } from '@dd/core/helpers/site';\nimport type {\n AuthOptionsWithDefaults,\n BuildMetadata,\n Options,\n OptionsWithDefaults,\n SourcemapsOptions,\n} from '@dd/core/types';\n\nconst SITES_DOC_URL = 'https://docs.datadoghq.com/getting_started/site/';\n\nconst resolveSite = (\n value: string | undefined,\n source: string,\n errors: string[],\n): ReturnType<typeof parseSite> => {\n if (value === undefined) {\n return undefined;\n }\n const parsed = parseSite(value);\n if (parsed) {\n return parsed;\n }\n errors.push(\n `${source} \"${value}\" is not a supported Datadog site. See the site parameters in ${SITES_DOC_URL}.`,\n );\n return undefined;\n};\n\nconst validateMetadata = (metadata: BuildMetadata | undefined): string[] => {\n const errors: string[] = [];\n if (metadata === undefined) {\n return errors;\n }\n // TODO(next-major): also reject non-string `metadata.name`. Skipped today\n // because `metadata.name` has historically been unvalidated (and the root\n // README documents its default as `null`), so adding a type-check here\n // would be a breaking change for users who took the docs literally.\n if (metadata.version !== undefined && typeof metadata.version !== 'string') {\n errors.push('metadata.version must be a string');\n }\n return errors;\n};\n\nconst normalizeSourcemapsOptions = (options: Options, errors: string[]): Options => {\n if (options.sourcemaps === undefined) {\n return options;\n }\n\n if (\n options.sourcemaps === null ||\n typeof options.sourcemaps !== 'object' ||\n Array.isArray(options.sourcemaps)\n ) {\n errors.push('sourcemaps must be an object');\n return options;\n }\n\n const sourcemaps = options.sourcemaps as SourcemapsOptions;\n const runtimeOptions = sourcemaps as unknown as Record<string, unknown>;\n\n if (runtimeOptions.debugId !== true) {\n errors.push('sourcemaps.debugId must be true');\n }\n if (runtimeOptions.upload !== undefined && typeof runtimeOptions.upload !== 'boolean') {\n errors.push('sourcemaps.upload must be a boolean');\n }\n if (\n runtimeOptions.upload !== true &&\n ['bailOnError', 'dryRun', 'maxConcurrency'].some(\n (option) => runtimeOptions[option] !== undefined,\n )\n ) {\n errors.push(\n 'sourcemaps.bailOnError, sourcemaps.dryRun, and sourcemaps.maxConcurrency require sourcemaps.upload to be true',\n );\n }\n if (options.rum?.sourceCodeContext?.debugId === false) {\n errors.push(\n 'rum.sourceCodeContext.debugId cannot be false when sourcemaps.debugId is true',\n );\n }\n if (options.rum?.enable === false) {\n errors.push('rum.enable cannot be false when sourcemaps is configured');\n }\n if (options.errorTracking?.sourcemaps !== undefined) {\n errors.push('sourcemaps cannot be combined with errorTracking.sourcemaps');\n }\n if (runtimeOptions.upload === true && options.errorTracking?.enable === false) {\n errors.push('errorTracking.enable cannot be false when sourcemaps.upload is true');\n }\n\n if (errors.length > 0) {\n return options;\n }\n\n const normalized: Options = {\n ...options,\n rum: {\n ...options.rum,\n sourceCodeContext: {\n ...options.rum?.sourceCodeContext,\n debugId: true,\n },\n },\n };\n\n if (sourcemaps.upload === true) {\n normalized.errorTracking = {\n ...options.errorTracking,\n sourcemaps: {\n debugId: true,\n ...(sourcemaps.bailOnError !== undefined && {\n bailOnError: sourcemaps.bailOnError,\n }),\n ...(sourcemaps.dryRun !== undefined && { dryRun: sourcemaps.dryRun }),\n ...(sourcemaps.maxConcurrency !== undefined && {\n maxConcurrency: sourcemaps.maxConcurrency,\n }),\n },\n };\n }\n\n return normalized;\n};\n\nexport const validateOptions = (options: Options = {}): OptionsWithDefaults => {\n const errors: string[] = validateMetadata(options.metadata);\n const normalizedOptions = normalizeSourcemapsOptions(options, errors);\n // DATADOG_SITE env var takes precedence over configuration; only validate\n // auth.site when no env var is set, so a stale auth.site can't block a\n // build that has already opted into an env override.\n const envRaw = getDDEnvValue('SITE');\n const resolvedSite =\n resolveSite(envRaw, 'DATADOG_SITE/DD_SITE', errors) ??\n resolveSite(normalizedOptions.auth?.site, 'auth.site', errors);\n\n const auth: AuthOptionsWithDefaults = {\n site: resolvedSite?.site ?? DEFAULT_SITE,\n };\n\n if (errors.length) {\n throw new Error(`Invalid Datadog plugin configuration:\\n - ${errors.join('\\n - ')}`);\n }\n\n // Prevent these from being accidentally logged.\n Object.defineProperty(auth, 'apiKey', {\n value: getDDEnvValue('API_KEY') || normalizedOptions.auth?.apiKey,\n enumerable: false,\n });\n\n Object.defineProperty(auth, 'appKey', {\n value: getDDEnvValue('APP_KEY') || normalizedOptions.auth?.appKey,\n enumerable: false,\n });\n\n return {\n enableGit: true,\n logLevel: 'warn',\n metadata: {},\n ...normalizedOptions,\n auth,\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { SITES } from '@dd/core/constants';\n\n// A site value can be a bare known site (e.g. \"datadoghq.com\") or a single-label\n// custom subdomain on top of one (e.g. \"myorg.us5.datadoghq.com\"), used by orgs\n// with a custom Datadog URL. Picks the longest (most specific) matching base site\n// so \"myorg.us5.datadoghq.com\" resolves to \"us5.datadoghq.com\", not \"datadoghq.com\".\n// Matching is case-insensitive; the returned site and subdomain are normalized to lowercase.\nexport const parseSite = (\n value: string,\n): { site: (typeof SITES)[number]; subdomain?: string } | undefined => {\n // Config isn't enforced by the type system at runtime (e.g. plain JS configs),\n // so a non-string can reach here despite the `string` signature.\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const lowerValue = value.toLowerCase();\n\n const exactMatch = SITES.find((s) => s === lowerValue);\n if (exactMatch) {\n return { site: exactMatch };\n }\n\n const suffixMatches = SITES.filter((s) => lowerValue.endsWith(`.${s}`));\n if (!suffixMatches.length) {\n return undefined;\n }\n\n const site = suffixMatches.reduce((longest, s) => (s.length > longest.length ? s : longest));\n const subdomain = lowerValue.slice(0, lowerValue.length - site.length - 1);\n if (!subdomain || !/^[a-z0-9-]+$/.test(subdomain)) {\n return undefined;\n }\n\n return { site, subdomain };\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\nconst formatErrorEntry = (e: unknown): string => {\n if (e === null || typeof e !== 'object') {\n return '';\n }\n return Object.entries(e)\n .map(\n ([key, value]) =>\n `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`,\n )\n .join(', ');\n};\n\nconst parseErrorDetails = (bodyText: string): string => {\n try {\n const body: unknown = JSON.parse(bodyText);\n if (body !== null && typeof body === 'object') {\n if ('errors' in body && Array.isArray(body.errors)) {\n const details = body.errors\n .map(formatErrorEntry)\n .filter((s) => s.length > 0)\n .join('\\n');\n if (details) {\n return details;\n }\n } else {\n const entry = formatErrorEntry(body);\n if (entry) {\n return entry;\n }\n }\n }\n } catch {\n // Body is not JSON.\n }\n return bodyText;\n};\n\nexport const getOriginHeaders = (opts: { bundler: string; plugin: string; version: string }) => {\n return {\n 'DD-EVP-ORIGIN': `${opts.bundler}-build-plugin_${opts.plugin}`,\n 'DD-EVP-ORIGIN-VERSION': opts.version,\n };\n};\n\nexport type RequestData = {\n data: ReadableStream;\n headers: Record<string, string>;\n};\n\nexport type FormBuilder = () => Promise<FormData> | FormData;\n\nexport const createRequestData = async (options: {\n getForm: FormBuilder;\n defaultHeaders: Record<string, string>;\n zip?: boolean;\n}): Promise<RequestData> => {\n const { getForm, defaultHeaders = {}, zip = true } = options;\n const form = await getForm();\n\n // Serialize FormData through Request to get a streaming body\n // and auto-generated headers (boundary) that we can forward while piping through gzip.\n const req = new Request('fake://url', { method: 'POST', body: form });\n\n // Use Web Streams pipeThrough instead of Node.js pipe() to keep the pipeline lazy.\n // Node.js pipe() immediately puts the source into flowing mode (starts reading blobs\n // via process.nextTick), which races with cleanup of file-backed blobs after the\n // request completes. Web Streams only start reading when the output is consumed.\n const data = zip ? req.body!.pipeThrough(new CompressionStream('gzip')) : req.body!;\n\n const headers = {\n 'Content-Encoding': zip ? 'gzip' : 'multipart/form-data',\n ...defaultHeaders,\n ...Object.fromEntries(req.headers.entries()),\n };\n\n return { data, headers };\n};\n\nexport const ERROR_CODES_NO_RETRY = [400, 401, 403, 404, 405, 409, 413];\nexport const NB_RETRIES = 5;\n\n// Do a retriable fetch.\nexport const doRequest = async <T>(opts: RequestOpts): Promise<T> => {\n const {\n auth,\n url,\n method = 'GET',\n getData,\n type = 'text',\n onResponse,\n signal,\n fetchImpl = fetch,\n } = 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 signal,\n };\n let requestHeaders: RequestInit['headers'] = {\n 'X-Datadog-Origin': 'build-plugins',\n };\n\n // Do auth if present.\n if (auth && 'accessToken' in auth) {\n if (auth.accessToken) {\n requestHeaders.Authorization = `Bearer ${auth.accessToken}`;\n }\n } else {\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\n if (typeof getData === 'function') {\n const { data, headers } = await getData();\n requestInit.body = data;\n requestHeaders = { ...requestHeaders, ...headers };\n }\n\n response = await fetchImpl(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 let errorMessage = `HTTP ${response.status} ${response.statusText}`;\n try {\n const bodyText = await response.text();\n const details = parseErrorDetails(bodyText);\n if (details) {\n errorMessage += `\\n${details}`;\n }\n } catch {\n // Ignore if body cannot be read.\n }\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 // Expose the successful response (headers, status) before the body is consumed.\n onResponse?.(response);\n\n try {\n let result;\n // Await it so we catch any parsing error and bail.\n if (type === 'json') {\n result = await response.json();\n } else {\n result = await response.text();\n }\n\n return result as T;\n } catch (error: any) {\n // We don't want to retry on parsing errors.\n bail(error);\n // bail(error) throws so the return is never executed.\n return {} as T;\n }\n }, retryOpts);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '../constants';\nimport type { GlobalData, DdLogOptions } from '../types';\n\nimport { doRequest } from './request';\n\nexport const INTAKE_PATH = 'v1/input/pub44d5f4eb86e1392037b7501f7adc540e';\nexport const INTAKE_HOST = 'browser-http-intake.logs.datadoghq.com';\n\nexport const getSendLog =\n (data: GlobalData) =>\n ({ message, context }: DdLogOptions): Promise<void> => {\n return doRequest({\n // Don't delay the build too much on error.\n retries: 2,\n minTimeout: 100,\n url: `https://${INTAKE_HOST}/${INTAKE_PATH}`,\n method: 'POST',\n type: 'json',\n getData: async () => {\n const payload = {\n ddsource: data.packageName || HOST_NAME,\n message,\n service: 'build-plugins',\n team: 'language-foundations',\n env: data.env,\n version: data.version,\n bundler: {\n name: data.bundler.name,\n version: data.bundler.version,\n },\n metadata: data.metadata,\n ...context,\n };\n return {\n data: JSON.stringify(payload),\n headers: {\n 'Content-Type': 'application/json',\n },\n };\n },\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport type {\n BuildReport,\n Entry,\n FileReport,\n Input,\n Options,\n Output,\n SerializedBuildReport,\n SerializedEntry,\n SerializedInput,\n SerializedOutput,\n} from '@dd/core/types';\n\nexport const cleanPluginName = (name: string) => {\n // Will remove the \"@dd/\", \"@dd/datadog-\", \"@dd/internal-\", \"datadog-\" prefixes and the \"-plugin\" suffix.\n return name.replace(/^@dd\\/(datadog-|internal-)?|^datadog-|-plugin$/g, '');\n};\n\n// Is the file coming from the injection plugin?\nexport const isInjectionFile = (filename: string) => filename.includes(INJECTED_FILE);\n\n// Returns an object that is safe to serialize to JSON.\n// Mostly useful for debugging and testing.\nexport const serializeBuildReport = (report: BuildReport): SerializedBuildReport => {\n // Report is an object that self reference some of its values.\n // To make it JSON serializable, we need to remove the self references\n // and replace them with strings, we'll use \"filepath\" to still have them uniquely identifiable.\n const jsonReport: SerializedBuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n entries: [],\n inputs: [],\n outputs: [],\n };\n\n for (const entry of report.entries || []) {\n const newEntry: SerializedEntry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs.map((file: FileReport) => file.filepath);\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.entries.push(newEntry);\n }\n\n for (const input of report.inputs || []) {\n const newInput: SerializedInput = { ...input, dependencies: [], dependents: [] };\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n newInput.dependencies.push(dependency.filepath);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n newInput.dependents.push(dependent.filepath);\n }\n }\n jsonReport.inputs.push(newInput);\n }\n\n for (const output of report.outputs || []) {\n const newOutput: SerializedOutput = { ...output, inputs: [] };\n if (output.inputs) {\n newOutput.inputs = output.inputs.map((file: FileReport) => file.filepath);\n }\n jsonReport.outputs.push(newOutput);\n }\n\n return jsonReport;\n};\n\n// Returns an object that is unserialized from serializeBuildReport().\n// Mostly useful for debugging and testing.\nexport const unserializeBuildReport = (report: SerializedBuildReport): BuildReport => {\n const buildReport: BuildReport = {\n bundler: report.bundler,\n errors: report.errors,\n metadata: report.metadata,\n warnings: report.warnings,\n logs: report.logs,\n timings: report.timings,\n start: report.start,\n end: report.end,\n duration: report.duration,\n writeDuration: report.writeDuration,\n };\n\n const reportInputs = report.inputs || [];\n const reportOutputs = report.outputs || [];\n\n const entries: Entry[] = [];\n\n // Prefill inputs and outputs as they are sometimes self-referencing themselves.\n const indexedInputs: Map<string, Input> = new Map();\n const inputs: Input[] = reportInputs.map<Input>((input) => {\n const newInput: Input = {\n ...input,\n // Keep them empty for now, we'll fill them later.\n dependencies: new Set(),\n dependents: new Set(),\n };\n indexedInputs.set(input.filepath, newInput);\n return newInput;\n });\n\n const indexedOutputs: Map<string, Output> = new Map();\n const outputs: Output[] = reportOutputs.map<Output>((output) => {\n const newOutput: Output = { ...output, inputs: [] };\n indexedOutputs.set(output.filepath, newOutput);\n return newOutput;\n });\n\n // Fill in the inputs' dependencies and dependents.\n for (const input of reportInputs) {\n const newInput: Input = indexedInputs.get(input.filepath)!;\n\n // Re-assign the dependencies and dependents to the actual objects.\n if (input.dependencies) {\n for (const dependency of input.dependencies) {\n const newDependency = indexedInputs.get(dependency)!;\n newInput.dependencies.add(newDependency);\n }\n }\n if (input.dependents) {\n for (const dependent of input.dependents) {\n const newDependent = indexedInputs.get(dependent)!;\n newInput.dependents.add(newDependent);\n }\n }\n }\n\n // Fill in the outputs' inputs.\n for (const output of reportOutputs) {\n const newOutput: Output = indexedOutputs.get(output.filepath)!;\n if (output.inputs) {\n // Re-assign the inputs to the actual objects.\n newOutput.inputs = output.inputs\n .map<\n // Can be either an input or an output (for sourcemaps).\n Input | Output | undefined\n >((filepath: string) => indexedInputs.get(filepath) || indexedOutputs.get(filepath))\n .filter(Boolean) as (Input | Output)[];\n }\n }\n\n for (const entry of report.entries || []) {\n const newEntry: Entry = { ...entry, inputs: [], outputs: [] };\n if (entry.inputs) {\n newEntry.inputs = entry.inputs\n .map((filepath: string) => indexedInputs.get(filepath))\n .filter(Boolean) as (Output | Input)[];\n }\n if (entry.outputs) {\n newEntry.outputs = entry.outputs\n .map((filepath: string) => indexedOutputs.get(filepath))\n .filter(Boolean) as Output[];\n }\n entries.push(newEntry);\n }\n\n return {\n ...buildReport,\n entries,\n inputs,\n outputs,\n };\n};\n\n// Verify that we should get the git information based on the options.\n// Only get git information if sourcemaps are enabled and git is enabled.\nexport const shouldGetGitInfo = (options: Options): boolean => {\n // If we don't have sourcemaps enabled, we don't need git.\n const gitEnabledFromSourcemaps = !!options.errorTracking?.sourcemaps;\n // If we have the 'enableGit' configuration at the root, use it and default to `true`.\n const gitEnabledFromRoot = options.enableGit ?? true;\n return gitEnabledFromSourcemaps && gitEnabledFromRoot;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport chalk from 'chalk';\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\nexport const normalizeTagValue = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_:./-]+/g, '_')\n .replace(/^_+|_+$/g, '') || 'unknown';\n\nconst formatValue = (value: unknown) => {\n if (value === undefined) {\n return 'undefined';\n }\n\n if (value === null) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return value.join(', ');\n }\n\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n\n return value?.toString() ?? '';\n};\n\nexport const prettyObject = (obj: any) => {\n return Object.entries(obj)\n .map(([key, value]) => ` - ${key}: ${chalk.bold.green(formatValue(value))}`)\n .join('\\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, context } = {}) => {\n // By default (debug) we print dimmed.\n let color = c.dim;\n let logFn = console.log;\n\n if (type === 'error') {\n color = c.red;\n logFn = console.error;\n } else if (type === 'warn') {\n color = c.yellow;\n logFn = console.warn;\n } else if (type === 'info') {\n color = c.cyan;\n logFn = console.log;\n }\n\n const buildName = data.metadata?.name ? `${data.metadata.name}|` : '';\n const prefix = `[${buildName}${type}|${data.bundler.name}|${cleanedName}]`;\n\n // Keep a trace of the log in the build report.\n const content = typeof text === 'string' ? text : JSON.stringify(text, null, 2);\n stores.logs.push({\n bundler: data.bundler.name,\n pluginName: name,\n type,\n message: content,\n time: Date.now(),\n });\n\n if (type === 'error') {\n stores.errors.push(content);\n }\n if (type === 'warn') {\n stores.warnings.push(content);\n }\n\n if (forward) {\n const forwardLog = async () => {\n try {\n const sendLog = getSendLog(data);\n await sendLog({\n message: content,\n context: { plugin: name, status: type, ...context },\n });\n } catch (e) {\n // Log the error using the parent logger.\n const subLogger = getLogFn(name, data, stores, logLevel);\n subLogger(`Error forwarding log: ${e}`, 'debug');\n }\n };\n stores.queue.push(forwardLog());\n }\n\n // Only log if the log level is high enough.\n if (logPriority[type] >= logPriority[logLevel]) {\n logFn(`${color(prefix)} ${content}`);\n }\n };\n};\n\nexport const getTimeLogger = (\n name: string,\n store: GlobalStores['timings'],\n log: LogFn,\n): TimeLog => {\n return (label, opts = {}) => {\n const { level = 'debug', start = true, log: toLog = true, tags = [] } = opts;\n const timer: Timer = {\n pluginName: name,\n label,\n spans: [],\n tags: [...tags, `plugin:${name}`, `level:${level}`],\n logLevel: level,\n total: 0,\n };\n\n // Add it to the build report.\n store.push(timer);\n\n const getUncompleteSpans = () => timer.spans.filter((span) => !span.end);\n\n // Push a new span.\n const resume: TimeLogger['resume'] = (startTime?: number) => {\n // Ignore if there is already an ongoing span.\n const uncompleteSpans = getUncompleteSpans();\n if (uncompleteSpans.length) {\n return;\n }\n\n // Log the start if it's the first span.\n if (!timer.spans.length && toLog) {\n log(c.dim(`[${c.cyan(label)}] : start`), 'debug');\n }\n\n // Add the new span.\n timer.spans.push({\n start: startTime || Date.now(),\n tags: [`plugin:${name}`],\n });\n };\n\n // Complete all the uncompleted spans.\n const pause: TimeLogger['pause'] = (pauseTime?: number, warn: boolean = true) => {\n const uncompleteSpans = getUncompleteSpans();\n\n if (!uncompleteSpans?.length) {\n if (warn) {\n log(`Timer ${c.cyan(label)} cannot be paused, no ongoing span.`, 'debug');\n }\n return;\n }\n\n if (uncompleteSpans.length > 1) {\n log(`Timer ${c.cyan(label)} has more than one ongoing span.`, 'debug');\n }\n\n for (const span of uncompleteSpans) {\n span.end = pauseTime || Date.now();\n }\n };\n\n // End the timer and add it to the build report.\n const end: TimeLogger['end'] = (endTime?: number) => {\n // We don't want to log a warning if the timer is already paused.\n pause(endTime, false);\n // Compute the total duration.\n const duration = timer.spans.reduce((acc, span) => acc + (span.end! - span.start), 0);\n timer.total = duration;\n if (toLog) {\n log(`[${c.cyan(label)}] : ${c.cyan(formatDuration(duration))}`, level);\n }\n };\n\n // Add a tag to the timer or the ongoing spans.\n const tag: TimeLogger['tag'] = (tagsToAdd, tagOpts = {}) => {\n const { span = false } = tagOpts;\n if (span) {\n const uncompleteSpans = getUncompleteSpans();\n for (const uncompleteSpan of uncompleteSpans) {\n uncompleteSpan.tags.push(...tagsToAdd);\n }\n } else {\n timer.tags.push(...tagsToAdd);\n }\n };\n\n // Auto start the timer.\n if (start) {\n let param: number | undefined;\n if (typeof start === 'number') {\n param = start;\n }\n resume(param);\n }\n\n const timeLogger: TimeLogger = {\n timer,\n resume,\n end,\n pause,\n tag,\n };\n\n return timeLogger;\n };\n};\n\nexport const getLoggerFactory =\n (data: GlobalData, stores: GlobalStores, logLevel: LogLevel = 'warn'): GetLogger =>\n (name) => {\n const log = getLogFn(name, data, stores, logLevel);\n return {\n getLogger: (subName: string) => {\n const logger = getLoggerFactory(data, stores, logLevel);\n return logger(`${cleanName(name)}${NAME_SEP}${subName}`);\n },\n time: getTimeLogger(name, stores.timings, log),\n error: (text: any, opts?: LogOptions) => log(text, 'error', opts),\n warn: (text: any, opts?: LogOptions) => log(text, 'warn', opts),\n info: (text: any, opts?: LogOptions) => log(text, 'info', opts),\n debug: (text: any, opts?: LogOptions) => log(text, 'debug', opts),\n };\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { HOST_NAME } from '@dd/core/constants';\nimport { cleanPluginName } from '@dd/core/helpers/plugins';\nimport type {\n CustomPluginOptions,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPluginsArg,\n GetPlugins,\n GlobalContext,\n Logger,\n PluginOptions,\n GetWrappedPlugins,\n CustomHooks,\n} from '@dd/core/types';\nimport type { UnpluginOptions } from 'unplugin';\n\n// Unplugin universal hooks.\nconst UNPLUGIN_HOOKS = [\n 'buildEnd',\n 'buildStart',\n 'load',\n 'resolveId',\n 'transform',\n 'watchChange',\n 'writeBundle',\n] as const;\n\n// Custom hooks.\nconst CUSTOM_HOOKS = ['buildRoot', 'init', 'buildReport', 'bundlerReport', 'git'] as const;\n\n// All the hooks that we want to trace.\nconst HOOKS_TO_TRACE = [...UNPLUGIN_HOOKS, ...CUSTOM_HOOKS];\n\n// Represents the hook names a plugin can have (including those we're not tracing).\ntype PluginHookName = keyof (PluginOptions | CustomPluginOptions);\n// Represents the custom hook names.\ntype CustomHookName = (typeof CUSTOM_HOOKS)[number];\n// Represents the unplugin hook names.\ntype UnpluginHookName = (typeof UNPLUGIN_HOOKS)[number];\n// Represents the hook names that we want to trace.\ntype HookName = CustomHookName | UnpluginHookName;\n// Represents the hook handler that we want to trace.\ntype HookFn = NonNullable<CustomHooks[CustomHookName] | UnpluginOptions[UnpluginHookName]>;\n\nexport const wrapHook = <T extends HookFn>(\n pluginName: string,\n hookName: HookName,\n hook: T,\n log: Logger,\n): T => {\n // Create a wrapper function that adds timing to any hook function\n const wrapWithTiming = <F extends (...args: any[]) => any>(fn: F): F => {\n return function (this: any, ...args) {\n const timer = log.time(`${pluginName} | ${hookName}`, {\n log: false,\n tags: ['type:hook', `hook:${hookName}`],\n });\n const result = fn.apply(this, args);\n\n if (result instanceof Promise) {\n return result.finally(() => {\n timer.end();\n });\n }\n\n timer.end();\n return result;\n } as F;\n };\n\n // Handle object hooks (with filter/handler pattern)\n if (typeof hook === 'object' && hook !== null && 'handler' in hook) {\n return {\n ...hook,\n handler: wrapWithTiming(hook.handler),\n };\n }\n\n // Handle function hooks\n return wrapWithTiming(hook) as T;\n};\n\nexport const wrapPlugin = (plugin: PluginOptions | CustomPluginOptions, log: Logger) => {\n const wrappedPlugin: PluginOptions | CustomPluginOptions = {\n ...plugin,\n };\n const name = cleanPluginName(plugin.name);\n\n // Wrap all the hooks that we want to trace.\n for (const hookName of HOOKS_TO_TRACE) {\n const hook = plugin[hookName];\n if (hook) {\n wrappedPlugin[hookName as PluginHookName] = wrapHook(name, hookName, hook, log);\n }\n }\n\n return wrappedPlugin;\n};\n\nexport const wrapGetPlugins = (\n context: GlobalContext,\n getPlugins: GetPlugins | GetCustomPlugins | GetInternalPlugins,\n name: string,\n): GetWrappedPlugins => {\n const log = context.getLogger(HOST_NAME);\n // Return the getPlugins function wrapped, so we can measure the initialization time.\n return (arg: GetPluginsArg) => {\n // Start our timer.\n const initTimer = log.time(`hook | init ${name}`, { log: false });\n\n // Wrap all the plugins that are returned by the initial getPlugins function.\n const wrappedPlugins = getPlugins(arg).map((plugin) => wrapPlugin(plugin, log));\n\n // Tag our timer with the plugin names.\n const pluginNames = wrappedPlugins.map((plugin) => `plugin:${plugin.name}`);\n initTimer.tag(pluginNames);\n\n // End of initialization.\n initTimer.end();\n return wrappedPlugins;\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\n\nconst warnedKeys = new Set<string>();\n\n/**\n * Resolve the `enable` value for a plugin config key, emitting a deprecation\n * warning when the caller passes a non-boolean truthy/falsy value.\n *\n * Semantics:\n * - Config key absent / undefined / falsy → false (plugin disabled).\n * - Config key is a truthy object without an `enable` property → true.\n * - Config key is a truthy object with `enable` set → coerce to boolean,\n * warning once per key if it isn't already a boolean.\n */\nexport const resolveEnable = <T extends { [K in C]?: unknown }, C extends string>(\n options: T,\n configKey: C,\n log: Logger,\n): boolean => {\n const pluginConfig = options[configKey];\n\n if (pluginConfig && typeof pluginConfig === 'object' && 'enable' in pluginConfig) {\n const value = pluginConfig.enable;\n\n if (typeof value !== 'boolean' && value !== undefined) {\n if (!warnedKeys.has(configKey)) {\n warnedKeys.add(configKey);\n log.warn(\n `\\`${configKey}.enable\\` should be a boolean, got ${typeof value}. ` +\n `Non-boolean values are coerced today but will be rejected in the next major.`,\n );\n }\n }\n\n if (value !== undefined) {\n // TODO(next major): drop this coercion and reject non-boolean `enable`\n // outright. The warning above gives callers one major to migrate.\n return !!value;\n }\n }\n\n return !!pluginConfig;\n};\n\n/** @internal Exposed only for tests to reset the warn-once set between cases. */\nexport const resetEnableWarnings = (): void => {\n warnedKeys.clear();\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 = 'apps' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-apps-plugin' as const;\n\nexport const ARCHIVE_FILENAME = 'datadog-app-assets.zip';\nexport const BACKEND_FILE_RE = /\\.backend\\.(ts|tsx|js|jsx)$/;\n\n/** Query suffix marking a local-execution load, so the transform hook can target it directly instead of matching on the broader `options.ssr` flag. */\nexport const LOCAL_EXECUTION_LOAD_SUFFIX = '?dd-local-exec';\n// Matches a backend file with any (or no) trailing query string — scoping only to the exact local-execution suffix would let an unrecognized query slip past this filter and leak the real backend source instead of the safe proxy stub; the handler decides safety per case.\nexport const BACKEND_FILE_WITH_QUERY_RE = new RegExp(\n `${BACKEND_FILE_RE.source.slice(0, -1)}(\\\\?.*)?$`,\n);\n\n/** Vite's `--mode` for `npm run dev:verify`; read via `server.config.mode` since `import.meta.env.MODE` breaks Jest's CommonJS transform. */\nexport const DEV_VERIFY_MODE = 'dev-verify';\n\nexport const BACKEND_CODE_EXTENSIONS = [\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.mjs',\n '.cjs',\n '.mts',\n '.cts',\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';\n\nimport { CONFIG_KEY } from './constants';\nimport type { AppsOptions, AppsOptionsWithDefaults } from './types';\n\nexport const resolveLongPolling = (\n longPolling: AppsOptions['longPolling'],\n): AppsOptionsWithDefaults['longPolling'] => {\n const maxRetries = longPolling?.maxRetries ?? 10;\n const timeoutMs = longPolling?.timeoutMs ?? 40_000;\n\n if (!Number.isInteger(maxRetries) || maxRetries < 1) {\n throw new Error('apps.longPolling.maxRetries must be an integer >= 1.');\n }\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error('apps.longPolling.timeoutMs must be a positive number.');\n }\n\n return {\n maxRetries,\n timeoutMs,\n jitter: longPolling?.jitter ?? true,\n exponentialBackoff: longPolling?.exponentialBackoff ?? true,\n };\n};\n\nexport const validateOptions = (options: Options): AppsOptionsWithDefaults => {\n const resolvedOptions = (options[CONFIG_KEY] || {}) as AppsOptions;\n\n return {\n include: resolvedOptions.include || [],\n longPolling: resolveLongPolling(resolvedOptions.longPolling),\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 { JsonStreamStringify } from 'json-stream-stringify';\nimport path from 'path';\nimport { Readable } from 'stream';\n\nimport type { FileValidity, LocalAppendOptions } from '../types';\n\n// Replacing fs-extra with local helpers.\n// Delete folders recursively.\nexport const rm = async (dir: string) => {\n return fsp.rm(dir, { force: true, maxRetries: 3, recursive: true });\n};\nexport const rmSync = (dir: string) => {\n return fs.rmSync(dir, { force: true, maxRetries: 3, recursive: true });\n};\n\n// Mkdir recursively.\nexport const mkdir = async (dir: string) => {\n return fsp.mkdir(dir, { recursive: true });\n};\n\nexport const mkdirSync = (dir: string) => {\n return fs.mkdirSync(dir, { recursive: true });\n};\n\n// Write a file but first ensure the directory exists.\nexport const outputFile = async (filepath: string, data: string) => {\n await mkdir(path.dirname(filepath));\n await fsp.writeFile(filepath, data, { encoding: 'utf-8' });\n};\n\nexport const outputFileSync = (filepath: string, data: string) => {\n mkdirSync(path.dirname(filepath));\n fs.writeFileSync(filepath, data, { encoding: 'utf-8' });\n};\n\n// Output a JSON file.\nexport const outputJson = async (filepath: string, data: any) => {\n await mkdir(path.dirname(filepath));\n // Use streams so it doesn't crash on very large data.\n const writable = fs.createWriteStream(filepath);\n const readable = new JsonStreamStringify(data, undefined, 2);\n const prom = new Promise<void>((resolve, reject) => {\n readable.on('end', () => {\n resolve();\n });\n\n readable.on('error', (err) => {\n reject(err);\n });\n });\n readable.pipe(writable);\n return prom;\n};\n\nexport const outputJsonSync = (filepath: string, data: any) => {\n // FIXME: This will crash on strings too long.\n const dataString = JSON.stringify(data, null, 4);\n outputFileSync(filepath, dataString);\n};\n\n// Read a JSON file.\nexport const readJsonSync = (filepath: string) => {\n const data = fs.readFileSync(filepath, { encoding: 'utf-8' });\n return JSON.parse(data);\n};\n\n// Read a file.\nexport const readFile = (filepath: string) => {\n return fsp.readFile(filepath, { encoding: 'utf-8' });\n};\n\nexport const readFileSync = (filepath: string) => {\n return fs.readFileSync(filepath, { encoding: 'utf-8' });\n};\n\nexport const existsSync = (filepath: string) => {\n try {\n return fs.existsSync(filepath);\n } catch (error: any) {\n // If the file does not exist, return false.\n if (error.code === 'ENOENT') {\n return false;\n }\n // If some other error occurs, rethrow it.\n throw error;\n }\n};\n\n// Some other more specific helpers.\n\n// From a path, returns a File to use with native FormData and fetch.\nexport const getFile = async (filepath: string, options: LocalAppendOptions) => {\n if (typeof fs.openAsBlob === 'function') {\n // Support NodeJS 19+\n const blob = await fs.openAsBlob(filepath, { type: options.contentType });\n return new File([blob], options.filename);\n } else {\n // Support NodeJS 18-\n const stream = Readable.toWeb(fs.createReadStream(filepath));\n const blob = await new Response(stream).blob();\n const file = new File([blob], options.filename, { type: options.contentType });\n return file;\n }\n};\n\n// Verify that every files are available.\nexport const checkFile = async (filePath: string): Promise<FileValidity> => {\n const validity: FileValidity = {\n empty: false,\n exists: true,\n };\n\n try {\n const { size } = await fsp.stat(filePath);\n if (size === 0) {\n validity.empty = true;\n }\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n validity.exists = false;\n } else {\n // Other kind of error\n throw error;\n }\n }\n\n return validity;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\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 { AppsOptions } from '@dd/apps-plugin/types';\nimport type * as apps from '@dd/apps-plugin';\nimport type { ErrorTrackingOptions } from '@dd/error-tracking-plugin/types';\nimport type * as errorTracking from '@dd/error-tracking-plugin';\nimport type { LiveDebuggerOptions } from '@dd/live-debugger-plugin/types';\nimport type * as liveDebugger from '@dd/live-debugger-plugin';\nimport type { MetricsOptions } from '@dd/metrics-plugin/types';\nimport type * as metrics from '@dd/metrics-plugin';\nimport type { OutputOptions } from '@dd/output-plugin/types';\nimport type * as output from '@dd/output-plugin';\nimport type { RumOptions } from '@dd/rum-plugin/types';\nimport type * as rum from '@dd/rum-plugin';\n// #imports-injection-marker\n/* eslint-enable arca/import-ordering */\nimport type { BodyInit } from 'undici-types';\nimport type { UnpluginOptions } from 'unplugin';\n\nimport type { ALL_ENVS, SITES, SUPPORTED_BUNDLERS } from './constants';\n\nexport type Assign<A, B> = Omit<A, keyof B> & B;\nexport type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };\nexport type IterableElement<IterableType extends Iterable<unknown>> =\n IterableType extends Iterable<infer ElementType> ? ElementType : never;\n\nexport interface RepositoryData {\n commit: {\n hash: string;\n message: string;\n author: {\n name: string;\n email: string;\n date: string;\n };\n committer: {\n name: string;\n email: string;\n date: string;\n };\n };\n hash: string;\n branch: string;\n remote: string;\n trackedFilesMatcher: TrackedFilesMatcher;\n}\n\nexport type FileReport = { filepath: string; name: string; size: number; type: string };\nexport type Input = FileReport & { dependencies: Set<Input>; dependents: Set<Input> };\nexport type Output = FileReport & { inputs: (Input | Output)[] };\nexport type Entry = Output & { outputs: Output[] };\n\nexport type SerializedEntry = Assign<Entry, { inputs: string[]; outputs: string[] }>;\nexport type SerializedInput = Assign<Input, { dependencies: string[]; dependents: string[] }>;\nexport type SerializedOutput = Assign<Output, { inputs: string[] }>;\n\nexport interface Metric {\n metric: string;\n type: 'count' | 'size' | 'duration';\n points: [number, number][];\n tags: string[];\n}\n\nexport interface MetricToSend extends Metric {\n toSend: boolean;\n}\n\nexport type Log = {\n bundler?: BundlerName;\n pluginName: string;\n type: LogLevel;\n message: string;\n time: number;\n};\nexport type LogTags = string[];\nexport type Timer = {\n label: string;\n pluginName: string;\n spans: { start: number; end?: number; tags: LogTags }[];\n tags: LogTags;\n total: number;\n logLevel: LogLevel;\n};\n\nexport type BuildMetadata = {\n name?: string;\n version?: string;\n};\n\nexport type BuildReport = {\n bundler: GlobalData['bundler'];\n errors: GlobalStores['errors'];\n warnings: GlobalStores['warnings'];\n logs: GlobalStores['logs'];\n timings: GlobalStores['timings'];\n metadata: GlobalData['metadata'];\n entries?: Entry[];\n inputs?: Input[];\n outputs?: Output[];\n start?: number;\n end?: number;\n duration?: number;\n writeDuration?: number;\n};\n\n// A JSON safe version of the report.\nexport type SerializedBuildReport = Assign<\n BuildReport,\n {\n entries: SerializedEntry[];\n inputs: SerializedInput[];\n outputs: SerializedOutput[];\n }\n>;\n\nexport type BundlerName = (typeof SUPPORTED_BUNDLERS)[number];\nexport type BundlerReport = GlobalData['bundler'] & {\n outDir: string;\n rawConfig?: any;\n};\n\nexport type ChunkInfo = {\n sourceOrHash: string;\n fileName: string;\n isEntry: boolean;\n};\n\n// Static string, lazy async loader (e.g. file fetch), or per-chunk code generator.\nexport type InjectedValue = string | (() => Promise<string>) | ((chunk?: ChunkInfo) => string);\n\nexport enum InjectPosition {\n BEFORE,\n MIDDLE,\n AFTER,\n}\n\nexport type ToInjectItem = {\n type: 'file' | 'code';\n value: InjectedValue;\n fallback?: ToInjectItem;\n} & (\n | { position?: InjectPosition.BEFORE | InjectPosition.AFTER; injectIntoAllChunks?: boolean }\n | { position: InjectPosition.MIDDLE }\n);\n\nexport type TimeLogger = {\n timer: Timer;\n resume: (startTime?: number) => void;\n end: (endTime?: number) => void;\n pause: (pauseTime?: number, warn?: boolean) => void;\n tag: (tags: LogTags, opts?: { span?: boolean }) => void;\n};\n\n// The rest parameter is a LogLevel or a boolean to auto start the timer.\nexport type TimeLog = (\n label: string,\n opts?: { level?: LogLevel; start?: boolean | number; log?: boolean; tags?: LogTags },\n) => TimeLogger;\nexport type GetLogger = (name: string) => Logger;\nexport type LogOptions = { forward?: boolean; context?: LogData };\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 addMetric: (metric: Metric) => void;\n artifactsPending: boolean;\n artifactsReady: Promise<void>;\n asyncHook: TriggerHook<Promise<void[]>>;\n auth: AuthOptionsWithDefaults;\n build: BuildReport;\n bundler: BundlerReport;\n buildRoot: string;\n env: GlobalData['env'];\n getLogger: GetLogger;\n git?: RepositoryData;\n hook: TriggerHook<void>;\n inject: (item: ToInjectItem) => void;\n markArtifactsPending: () => void;\n markArtifactsReady: (error?: unknown) => void;\n pluginNames: string[];\n plugins: (PluginOptions | CustomPluginOptions)[];\n queue: (promise: Promise<any>) => void;\n sendLog: (args: DdLogOptions) => Promise<void>;\n start: number;\n version: GlobalData['version'];\n};\n\nexport type FactoryMeta = {\n bundler: any;\n version: string;\n};\n\nexport type HookFn<T extends Array<any>> = (...args: T) => void;\nexport type AsyncHookFn<T extends Array<any>> = (...args: T) => Promise<void> | void;\nexport type CustomHooks = {\n asyncTrueEnd?: () => Promise<void> | void;\n buildRoot?: HookFn<[string]>;\n flush?: () => Promise<void> | void;\n init?: HookFn<[GlobalContext]>;\n buildReport?: AsyncHookFn<[BuildReport]>;\n bundlerReport?: HookFn<[BundlerReport]>;\n git?: AsyncHookFn<[RepositoryData]>;\n metrics?: AsyncHookFn<[Set<Metric>]>;\n syncTrueEnd?: () => void;\n timings?: AsyncHookFn<[TimingsReport]>;\n};\n\nexport type PluginOptions = Assign<\n UnpluginOptions & CustomHooks,\n {\n name: PluginName;\n }\n>;\n\nexport type CustomPluginOptions = Assign<\n PluginOptions,\n {\n name: string;\n }\n>;\n\nexport type GetPluginsArg = {\n bundler: any;\n context: GlobalContext;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n};\nexport type GetPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetCustomPlugins = (arg: GetPluginsArg) => CustomPluginOptions[];\nexport type GetInternalPlugins = (arg: GetPluginsArg) => PluginOptions[];\nexport type GetWrappedPlugins = (arg: GetPluginsArg) => (PluginOptions | CustomPluginOptions)[];\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\nexport type Site = (typeof SITES)[number];\nexport type AuthOptions = {\n apiKey?: string;\n appKey?: string;\n site?: string;\n};\n\nexport type AuthOptionsWithDefaults = Omit<AuthOptions, 'site'> & {\n site: Site;\n};\n\nexport interface BaseOptions {\n auth?: AuthOptions;\n metadata?: BuildMetadata;\n enableGit?: boolean;\n logLevel?: LogLevel;\n}\n\ntype SourcemapsUploadEnabledOptions = {\n upload: true;\n bailOnError?: boolean;\n dryRun?: boolean;\n maxConcurrency?: number;\n};\n\ntype SourcemapsInjectionOnlyOptions = {\n upload?: false;\n bailOnError?: never;\n dryRun?: never;\n maxConcurrency?: never;\n};\n\nexport type SourcemapsOptions = {\n debugId: true;\n} & (SourcemapsUploadEnabledOptions | SourcemapsInjectionOnlyOptions);\n\nexport interface Options extends BaseOptions {\n // Each product should have a unique entry.\n // #types-injection-marker\n [apps.CONFIG_KEY]?: AppsOptions;\n [errorTracking.CONFIG_KEY]?: ErrorTrackingOptions;\n [liveDebugger.CONFIG_KEY]?: LiveDebuggerOptions;\n [metrics.CONFIG_KEY]?: MetricsOptions;\n [output.CONFIG_KEY]?: OutputOptions;\n [rum.CONFIG_KEY]?: RumOptions;\n // #types-injection-marker\n sourcemaps?: SourcemapsOptions;\n /** Repository URL used in Git metadata instead of the detected remote URL. */\n gitRepositoryUrl?: string;\n customPlugins?: GetCustomPlugins;\n}\n\nexport type OptionsWithDefaults = Assign<\n Assign<Options, Required<BaseOptions>>,\n { auth: AuthOptionsWithDefaults }\n>;\n\nexport type PluginName = `datadog-${Lowercase<string>}-plugin`;\n\nexport type ApiKeyRequestAuthOptions = {\n apiKey?: string;\n appKey?: string;\n};\n\nexport type OAuthRequestAuthOptions = {\n accessToken: string;\n};\n\n// Request-local auth. OAuth callers must resolve tokens before calling doRequest.\nexport type RequestAuthOptions = ApiKeyRequestAuthOptions | OAuthRequestAuthOptions;\n\ntype Data = { data?: BodyInit; headers?: Record<string, string> };\nexport type RequestOpts = {\n url: string;\n auth?: RequestAuthOptions;\n method?: string;\n getData?: () => Promise<Data> | Data;\n type?: 'json' | 'text';\n onRetry?: (error: Error, attempt: number) => void;\n // Invoked with the raw response of each successful (HTTP-ok) attempt, before the\n // body is consumed. Useful to read response headers (e.g. ETag, Last-Modified).\n onResponse?: (response: Response) => void;\n retries?: number;\n minTimeout?: number;\n maxTimeout?: number;\n signal?: AbortSignal;\n // Defaults to a fresh `globalThis.fetch` lookup at call time (so tests can keep mocking the\n // global). Callers that must be immune to the global being reassigned at runtime (e.g. the apps\n // plugin's authenticated dev-server transport) pass a reference captured before that could happen.\n fetchImpl?: typeof fetch;\n};\n\nexport type ResolvedEntry = { name?: string; resolved: string; original: string };\n\nexport interface LocalAppendOptions {\n contentType: string;\n filename: string;\n}\n\nexport type FileValidity = {\n empty: boolean;\n exists: boolean;\n};\n\nexport type GlobalData = {\n bundler: {\n name: BundlerName;\n version: string;\n };\n env: Env;\n metadata: BuildMetadata;\n packageName: string;\n version: string;\n};\n\nexport type GlobalStores = {\n errors: string[];\n logs: Log[];\n metrics: Set<Metric>;\n queue: Promise<any>[];\n timings: Timer[];\n warnings: string[];\n};\n\n/* Legacy Telemetry types */\nexport type TAP_TYPES = 'default' | 'async' | 'promise';\n\nexport interface ValueContext {\n type: string;\n name: string;\n value?: string;\n}\n\nexport interface Value {\n start: number;\n end: number;\n duration: number;\n context?: ValueContext[];\n type?: TAP_TYPES; // Only for webpack.\n}\n\nexport interface Timing {\n name: string;\n duration: number;\n increment: number;\n events: {\n [key: string]: {\n name: string;\n values: Value[];\n };\n };\n}\nexport type TimingsMap = Map<string, Timing>;\n\nexport interface TimingsReport {\n tapables?: TimingsMap;\n loaders?: TimingsMap;\n modules?: TimingsMap;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getDDEnvValue } from '@dd/core/helpers/env';\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { RequestOpts } from '@dd/core/types';\n\n// Lazy, same reasoning as local-execution.ts's getNetworkGuard(): importing network-guard.ts\n// installs its monkeypatches at module-load time, and this module is only ever used by the Vite\n// dev server (see getAuthenticatedRequest's callers), so deferring the import keeps that install\n// confined to Vite instead of triggering for every bundler that transitively imports this file.\nlet networkGuardModule: Promise<typeof import('./vite/network-guard')> | undefined;\nfunction getNetworkGuard(): Promise<typeof import('./vite/network-guard')> {\n networkGuardModule ??= import('./vite/network-guard').catch((err: unknown) => {\n networkGuardModule = undefined;\n throw err;\n });\n return networkGuardModule;\n}\n\nexport const AUTH_GUIDANCE =\n 'Set DD_API_KEY and DD_APP_KEY for API-key auth, or set DD_OAUTH_ACCESS_TOKEN ' +\n '(or DATADOG_OAUTH_ACCESS_TOKEN) — e.g. by starting the dev server with `datadog-apps dev`.';\n\nexport type DoAuthenticatedRequest = <T>(opts: Omit<RequestOpts, 'auth'>) => Promise<T>;\n\nexport class MissingAuthenticationError extends Error {\n public statusCode = 400;\n\n constructor() {\n super(`Missing authentication. ${AUTH_GUIDANCE}`);\n this.name = 'MissingAuthenticationError';\n }\n}\n\n// Build the dev-server request authenticator. API-key auth (DD_API_KEY +\n// DD_APP_KEY) takes precedence; otherwise the OAuth access token that\n// @datadog/apps-cli passes via DD_OAUTH_ACCESS_TOKEN is used.\nexport const getAuthenticatedRequest = (): DoAuthenticatedRequest => {\n const apiKey = getDDEnvValue('API_KEY');\n const appKey = getDDEnvValue('APP_KEY');\n if (apiKey && appKey) {\n return async (opts) => {\n const { trustedFetch } = await getNetworkGuard();\n return doRequest({\n ...opts,\n auth: {\n apiKey,\n appKey,\n },\n fetchImpl: trustedFetch,\n });\n };\n }\n\n const accessToken = getDDEnvValue('OAUTH_ACCESS_TOKEN');\n if (accessToken) {\n return async (opts) => {\n const { trustedFetch } = await getNetworkGuard();\n return doRequest({\n ...opts,\n auth: {\n accessToken,\n },\n fetchImpl: trustedFetch,\n });\n };\n }\n\n throw new MissingAuthenticationError();\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 { BaseNode, Program, SimpleLiteral, TemplateLiteral, VariableDeclarator } from 'estree';\n\nexport type StringLiteral = SimpleLiteral & { value: string };\n\nexport interface TypeScriptImportExportMetadata {\n importKind?: 'type' | 'value';\n exportKind?: 'type' | 'value';\n}\n\ntype TypeOnlyAwareNode = BaseNode & TypeScriptImportExportMetadata;\n\nexport function ensureProgram(node: BaseNode, filePath: string): Program {\n if (!isProgramNode(node)) {\n throw new Error(\n `Expected a Program node from this.parse() for ${filePath}, got ${node.type}`,\n );\n }\n return node;\n}\n\nexport function isProgramNode(node: BaseNode): node is Program {\n return node.type === 'Program';\n}\n\n// Shared by every guard below: narrows an `unknown` AST value to \"a non-null object carrying this specific `type` tag\" before any type-specific field is checked.\nfunction hasNodeType<T extends string>(node: unknown, type: T): node is { type: T } {\n return typeof node === 'object' && node !== null && 'type' in node && node.type === type;\n}\n\nexport function isStringLiteral(node: unknown): node is StringLiteral {\n return hasNodeType(node, 'Literal') && 'value' in node && typeof node.value === 'string';\n}\n\nexport function isTypeOnly(node: TypeOnlyAwareNode): boolean {\n return node.importKind === 'type' || node.exportKind === 'type';\n}\n\nexport function isVariableDeclaratorNode(node: unknown): node is VariableDeclarator {\n return hasNodeType(node, 'VariableDeclarator');\n}\n\nfunction isNoSubstitutionTemplateLiteral(node: unknown): node is TemplateLiteral {\n if (!hasNodeType(node, 'TemplateLiteral') || !('expressions' in node) || !('quasis' in node)) {\n return false;\n }\n return (\n Array.isArray(node.expressions) &&\n node.expressions.length === 0 &&\n Array.isArray(node.quasis) &&\n node.quasis.length === 1\n );\n}\n\n// Resolves the static string value of a `Literal` or no-substitution template literal — the only two forms knowable without evaluation.\nexport function staticStringValue(node: unknown): string | undefined {\n if (isStringLiteral(node)) {\n return node.value;\n }\n if (isNoSubstitutionTemplateLiteral(node)) {\n return node.quasis[0].value.cooked ?? undefined;\n }\n return undefined;\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 { BaseNode, Declaration, Expression, Program } from 'estree';\n\nimport { ensureProgram } from './type-guards';\nimport type { BackendExport } from './types';\n\n/**\n * Extract exported value (non-type) symbols from an ESTree AST.\n * Expects plain JavaScript — TypeScript types must already be stripped\n * (e.g. by Vite's built-in esbuild transform that runs before our hook).\n *\n * Throws on invalid exports (e.g. default exports) and unexpected AST shapes.\n * Returns an empty array when the file has no named exports.\n *\n * @param ast - ESTree node from `this.parse()` in unplugin's transform hook\n * @param filePath - Path to the source file (used in error messages)\n */\nexport function extractExportedFunctions(ast: BaseNode, filePath: string): string[] {\n return enumerateBackendExports(ast, filePath).map((backendExport) => backendExport.name);\n}\n\nexport function enumerateBackendExports(ast: BaseNode, filePath: string): BackendExport[] {\n const program = ensureProgram(ast, filePath);\n\n // Build a map of top-level declarations so we can validate export specifiers.\n const declarations = buildDeclarationMap(program);\n\n const backendExports: BackendExport[] = [];\n for (const node of program.body) {\n // handles: export default ...\n if (node.type === 'ExportDefaultDeclaration') {\n throw new Error(\n `Default exports are not supported in .backend.ts files. Use a named export instead: ${filePath}`,\n );\n }\n // handles: export * from '...'\n if (node.type === 'ExportAllDeclaration') {\n throw new Error(\n `\"export *\" is not supported in .backend.ts files. Use explicit named exports instead: ${filePath}`,\n );\n }\n if (node.type !== 'ExportNamedDeclaration') {\n continue;\n }\n\n // handles: export function add() {} / export const add = ...\n if (node.declaration) {\n backendExports.push(\n ...namesFromDeclaration(node.declaration, filePath).map((name) => ({\n kind: 'local' as const,\n name,\n localName: name,\n })),\n );\n }\n\n const source = typeof node.source?.value === 'string' ? node.source.value : null;\n for (const spec of node.specifiers) {\n if (spec.exported.type !== 'Identifier') {\n continue;\n }\n // handles: export { add as default }\n if (spec.exported.name === 'default') {\n throw new Error(\n `Default exports are not supported in .backend.ts files. Use a named export instead: ${filePath}`,\n );\n }\n // Validate specifier binding is callable when we can resolve it.\n // e.g. `const VERSION = '1.0'; export { VERSION };` — rejected\n // e.g. `function add() {}; export { add };` — allowed\n const localName =\n spec.local.type === 'Identifier'\n ? spec.local.name\n : typeof spec.local.value === 'string'\n ? spec.local.value\n : null;\n if (!localName) {\n continue;\n }\n\n if (source) {\n backendExports.push({\n kind: 're-export',\n name: spec.exported.name,\n localName,\n source,\n });\n continue;\n }\n\n if (spec.local.type === 'Identifier') {\n validateSpecifierBinding(localName, declarations, filePath);\n }\n backendExports.push({\n kind: 'local',\n name: spec.exported.name,\n localName,\n });\n }\n }\n return backendExports;\n}\n\n/** Init types that are definitively non-callable at runtime. */\nconst NON_CALLABLE_INIT_TYPES = new Set([\n 'ArrayExpression',\n 'Literal',\n 'ObjectExpression',\n 'TemplateLiteral',\n]);\n\n/**\n * Return `true` when the initializer is known to be non-callable.\n * `ArrowFunctionExpression` / `FunctionExpression` are clearly callable.\n * Ambiguous forms (`Identifier`, `CallExpression`, …) are allowed — the\n * user may legitimately re-export an imported function or a factory result.\n */\nfunction isNonCallableInit(init: Expression | null | undefined): boolean {\n return init === null || init === undefined || NON_CALLABLE_INIT_TYPES.has(init.type);\n}\n\n/**\n * Extract identifier names from an exported declaration node.\n * Handles `export function foo()` and `export const foo = ...` forms.\n * Throws when a variable export has a non-callable initializer.\n */\nfunction namesFromDeclaration(decl: Declaration, filePath: string): string[] {\n // export function add(a, b) { return a + b; }\n if (decl.type === 'FunctionDeclaration' && decl.id) {\n return [decl.id.name];\n }\n // export class MyClass {} — classes are not callable as RPC endpoints\n if (decl.type === 'ClassDeclaration') {\n throw new Error(\n `Class exports are not supported in .backend.ts files. Only function exports are allowed: ${filePath}`,\n );\n }\n if (decl.type === 'VariableDeclaration') {\n return decl.declarations.flatMap((d) => {\n // export const { a, b } = obj;\n // export const [a, b] = arr;\n if (d.id.type !== 'Identifier') {\n throw new Error(\n `Destructured exports are not supported in backend files. Use individual named exports instead: ${filePath}`,\n );\n }\n // export const VERSION = '1.0'; — non-callable, throws\n // export const config = { ... }; — non-callable, throws\n if (isNonCallableInit(d.init)) {\n throw new Error(\n `Non-function export \"${d.id.name}\" in backend file ${filePath}. Only function exports are supported — use \"export function ${d.id.name}(…) { }\" instead.`,\n );\n }\n // export const add = (a, b) => a + b;\n // export const handler = importedFn; — ambiguous, allowed\n return [d.id.name];\n });\n }\n throw new Error(\n `Unsupported export declaration type \"${decl.type}\" in backend file ${filePath}. Only function and variable exports are allowed.`,\n );\n}\n\n/**\n * Describes a top-level declaration for specifier validation.\n * 'function' and 'import' are always allowed (callable or ambiguous).\n * 'class' is rejected. 'variable' is checked via its initializer.\n */\ntype DeclInfo =\n | { kind: 'function' | 'import' | 'class' }\n | { kind: 'variable'; init: Expression | null | undefined };\n\n/**\n * Build a map from identifier name → declaration info for all top-level\n * statements. Used to validate `export { name }` specifiers.\n */\nfunction buildDeclarationMap(ast: Program): Map<string, DeclInfo> {\n const map = new Map<string, DeclInfo>();\n for (const node of ast.body) {\n if (node.type === 'FunctionDeclaration' && node.id) {\n // handles: function add(a, b) { return a + b; }\n map.set(node.id.name, { kind: 'function' });\n } else if (node.type === 'ClassDeclaration' && node.id) {\n // handles: class MyService {}\n map.set(node.id.name, { kind: 'class' });\n } else if (node.type === 'VariableDeclaration') {\n // handles: const add = (a, b) => a + b; / const VERSION = '1.0';\n for (const d of node.declarations) {\n if (d.id.type === 'Identifier') {\n map.set(d.id.name, { kind: 'variable', init: d.init });\n }\n }\n } else if (node.type === 'ImportDeclaration') {\n // handles: import { handler } from './other';\n // For this case, we allow exporting handler and accept that it may not be a function.\n for (const spec of node.specifiers) {\n map.set(spec.local.name, { kind: 'import' });\n }\n }\n }\n return map;\n}\n\n/**\n * Validate that an export specifier's local binding is callable.\n * Throws for known non-callable bindings (classes, non-callable variables).\n * Allows unresolved bindings (e.g. from other export patterns) and imports.\n */\nfunction validateSpecifierBinding(\n localName: string,\n declarations: Map<string, DeclInfo>,\n filePath: string,\n): void {\n const info = declarations.get(localName);\n if (!info) {\n // Unresolved — could come from a pattern we don't track. Allow it.\n return;\n }\n if (info.kind === 'class') {\n throw new Error(\n `Class exports are not supported in .backend.ts files. Only function exports are allowed: ${filePath}`,\n );\n }\n if (info.kind === 'variable' && isNonCallableInit(info.init)) {\n throw new Error(\n `Non-function export \"${localName}\" in backend file ${filePath}. Only function exports are supported — use \"export function ${localName}(…) { }\" instead.`,\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 { BaseNode, Node as EstreeNode } from 'estree';\n\n/**\n * Object passed to every visitor.\n *\n * `state` is shared for the whole walk. This helper intentionally does not\n * thread child-specific state because current AST analysis only needs one\n * shared collection/lookup object.\n */\nexport interface WalkAstContext<State> {\n state: State;\n}\n\n/**\n * Function called when the walker reaches a matching node.\n *\n * `Node` is the broad tree type passed to `walkAst`, while `CurrentNode` is the\n * narrowed node type for a specialized visitor such as `CallExpression`.\n */\nexport type WalkAstVisitor<Node extends BaseNode, State, CurrentNode extends BaseNode = Node> = (\n node: CurrentNode,\n context: WalkAstContext<State>,\n) => void;\n\n/**\n * Visitor map for concrete ESTree node types.\n *\n * The runtime walker is generic and does not special-case ESTree types. This\n * mapped type only exists to make visitor callbacks typed when users write\n * keys like `CallExpression` or `VariableDeclarator`.\n */\ntype SpecializedWalkAstVisitors<Node extends BaseNode, State> = {\n [Type in EstreeNode['type']]?: WalkAstVisitor<Node, State, Extract<EstreeNode, { type: Type }>>;\n};\n\n/**\n * Visitors accepted by `walkAst`.\n *\n * `_` is a universal visitor that runs for every node. Keys matching concrete\n * ESTree node types run only for nodes with that `type`.\n */\nexport type WalkAstVisitors<Node extends BaseNode, State> = SpecializedWalkAstVisitors<\n Node,\n State\n> & {\n _?: WalkAstVisitor<Node, State>;\n};\n\n/**\n * Walks an ESTree-shaped AST without maintaining a hardcoded visitor-key table.\n *\n * Any object with a string `type` property is treated as a child node. Primitive\n * values, arrays entries without `type`, and metadata objects such as `loc` are\n * ignored.\n */\nexport function walkAst<Node extends BaseNode, State>(\n node: Node,\n state: State,\n visitors: WalkAstVisitors<Node, State>,\n): void {\n const context: WalkAstContext<State> = { state };\n\n const visit = (currentNode: Node): void => {\n visitors._?.(currentNode, context);\n getSpecializedVisitor(currentNode, visitors)?.(currentNode, context);\n\n for (const key of Object.keys(currentNode)) {\n if (key === 'type') {\n continue;\n }\n\n visitChildren((currentNode as Record<string, unknown>)[key]);\n }\n };\n\n const visitChildren = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isAstNode(item)) {\n visit(item as Node);\n }\n }\n return;\n }\n\n if (isAstNode(value)) {\n visit(value as Node);\n }\n };\n\n visit(node);\n}\n\nfunction isAstNode(value: unknown): value is BaseNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n typeof value.type === 'string'\n );\n}\n\nfunction getSpecializedVisitor<Node extends BaseNode, State>(\n node: Node,\n visitors: WalkAstVisitors<Node, State>,\n): WalkAstVisitor<BaseNode, State> | undefined {\n return (visitors as Record<string, WalkAstVisitor<BaseNode, State> | undefined>)[node.type];\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 * as eslintScope from 'eslint-scope';\nimport type { Identifier, Node, Program } from 'estree';\n\nimport { walkAst } from './walk-ast';\n\n/**\n * Generic eslint-scope facts for one parsed ES module.\n *\n * This intentionally has no action-catalog or connection ID concepts. Consumers\n * can use it to resolve an identifier node back to the declaration variable\n * eslint-scope found for that exact source location.\n */\nexport interface ModuleScopeAnalysis {\n scopeManager: eslintScope.ScopeManager;\n referencesByIdentifier: Map<Identifier, eslintScope.Reference>;\n moduleScope: eslintScope.Scope;\n}\n\ntype NodeWithRange = Node & { start?: number; end?: number; range?: [number, number] };\n\nexport function analyzeModuleScope(ast: Program): ModuleScopeAnalysis {\n ensureRanges(ast);\n const scopeManager = eslintScope.analyze(ast, {\n ecmaVersion: 2022,\n ignoreEval: true,\n sourceType: 'module',\n });\n\n const referencesByIdentifier = new Map<Identifier, eslintScope.Reference>();\n for (const scope of scopeManager.scopes) {\n for (const reference of scope.references) {\n referencesByIdentifier.set(reference.identifier, reference);\n }\n }\n\n return {\n scopeManager,\n referencesByIdentifier,\n moduleScope: getModuleScope(scopeManager),\n };\n}\n\nexport function resolveIdentifier(\n identifier: Identifier,\n scopeAnalysis: ModuleScopeAnalysis,\n): eslintScope.Variable | undefined {\n return scopeAnalysis.referencesByIdentifier.get(identifier)?.resolved ?? undefined;\n}\n\nexport function resolvesTo(\n identifier: Identifier,\n variables: ReadonlySet<eslintScope.Variable>,\n scopeAnalysis: ModuleScopeAnalysis,\n): boolean {\n const variable = resolveIdentifier(identifier, scopeAnalysis);\n return !!variable && variables.has(variable);\n}\n\nexport function isImportVariable(variable: eslintScope.Variable): boolean {\n return variable.defs.some((definition) => definition.type === 'ImportBinding');\n}\n\nexport function getModuleVariable(\n name: string,\n scopeAnalysis: ModuleScopeAnalysis,\n): eslintScope.Variable | undefined {\n return scopeAnalysis.moduleScope.set.get(name);\n}\n\nfunction getModuleScope(scopeManager: eslintScope.ScopeManager): eslintScope.Scope {\n return scopeManager.scopes.find((scope) => scope.type === 'module') ?? scopeManager.globalScope;\n}\n\nfunction ensureRanges(node: Node): void {\n walkAst(node, null, {\n _(child) {\n const nodeWithRange = child as NodeWithRange;\n if (\n !nodeWithRange.range &&\n typeof nodeWithRange.start === 'number' &&\n typeof nodeWithRange.end === 'number'\n ) {\n nodeWithRange.range = [nodeWithRange.start, nodeWithRange.end];\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 * as eslintScope from 'eslint-scope';\nimport type {\n AssignmentExpression,\n Identifier,\n MemberExpression,\n Node,\n Pattern,\n Program,\n SimpleCallExpression,\n VariableDeclarator,\n} from 'estree';\n\nimport type { ActionCatalogImports } from './action-catalog-imports';\nimport {\n isImportVariable,\n type ModuleScopeAnalysis,\n resolveIdentifier,\n resolvesTo as resolvesToModuleVariable,\n} from './module-scope';\nimport { walkAst } from './walk-ast';\n\n// Do not trust names alone when deciding whether `request(...)` is an\n// action-catalog call. A local parameter or variable can reuse the same name:\n//\n// import { request } from '@datadog/action-catalog/http/http';\n// request({ connectionId: 'real' });\n//\n// function run(request) {\n// request({ connectionId: 'local' });\n// }\n//\n// Both calls use the text `request`, but only the first one refers to the\n// imported action-catalog function. eslint-scope tells us which declaration\n// each identifier refers to; this analysis adds action-catalog-specific import\n// sets on top of the generic module scope facts.\nexport interface ActionCatalogScopeAnalysis {\n moduleScope: ModuleScopeAnalysis;\n actionFunctions: Set<eslintScope.Variable>;\n actionNamespaces: Set<eslintScope.Variable>;\n}\n\ninterface ActionCatalogCallState {\n scopeAnalysis: ActionCatalogScopeAnalysis;\n unsupportedAliases: Set<eslintScope.Variable>;\n}\n\nexport function analyzeActionCatalogScopes(\n moduleScope: ModuleScopeAnalysis,\n imports: ActionCatalogImports,\n): ActionCatalogScopeAnalysis {\n const actionFunctions = new Set<eslintScope.Variable>();\n const actionNamespaces = new Set<eslintScope.Variable>();\n\n for (const scope of moduleScope.scopeManager.scopes) {\n // Save the actual import declarations that came from action-catalog.\n // Later, when we see `request(...)`, we check whether that `request`\n // points back to one of these declarations instead of to a local\n // parameter or variable with the same name.\n for (const variable of scope.variables) {\n if (!isImportVariable(variable)) {\n continue;\n }\n if (imports.functions.has(variable.name)) {\n actionFunctions.add(variable);\n }\n if (imports.namespaces.has(variable.name)) {\n actionNamespaces.add(variable);\n }\n }\n }\n\n return { moduleScope, actionFunctions, actionNamespaces };\n}\n\nexport function findActionCatalogCallSites(\n ast: Program,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n filePath: string,\n): SimpleCallExpression[] {\n const callState: ActionCatalogCallState = {\n scopeAnalysis,\n unsupportedAliases: collectUnsupportedActionCatalogAliases(ast, scopeAnalysis),\n };\n const callSites: SimpleCallExpression[] = [];\n\n walkAst(ast, callState, {\n CallExpression(node, { state }) {\n if (classifyActionCatalogCall(node, state, filePath)) {\n callSites.push(node);\n }\n },\n });\n\n return callSites;\n}\n\nfunction classifyActionCatalogCall(\n node: SimpleCallExpression,\n state: ActionCatalogCallState,\n filePath: string,\n): boolean {\n const callee = node.callee;\n\n if (callee.type === 'Identifier') {\n if (resolvesTo(callee, state.unsupportedAliases, state.scopeAnalysis)) {\n throw unsupportedActionCatalogCall(filePath, 'action-catalog call aliases');\n }\n if (resolvesTo(callee, state.scopeAnalysis.actionFunctions, state.scopeAnalysis)) {\n if (node.optional) {\n throw unsupportedActionCatalogCall(filePath, 'optional action-catalog calls');\n }\n return true;\n }\n return false;\n }\n\n if (callee.type !== 'MemberExpression') {\n return false;\n }\n\n if (!isNamespaceMember(callee, state.scopeAnalysis)) {\n return false;\n }\n\n if (node.optional || hasUnsupportedMemberAccess(callee)) {\n throw unsupportedActionCatalogCall(\n filePath,\n 'optional or computed action-catalog namespace calls',\n );\n }\n return true;\n}\n\nfunction collectUnsupportedActionCatalogAliases(\n ast: Program,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): Set<eslintScope.Variable> {\n const unsupportedAliases = new Set<eslintScope.Variable>();\n\n walkAst(ast, scopeAnalysis, {\n VariableDeclarator(node, { state }) {\n for (const aliasVariable of getActionCatalogAliasVariables(node, state)) {\n unsupportedAliases.add(aliasVariable);\n }\n },\n AssignmentExpression(node, { state }) {\n for (const aliasVariable of getAssignedActionCatalogAliasVariables(node, state)) {\n unsupportedAliases.add(aliasVariable);\n }\n },\n });\n\n return unsupportedAliases;\n}\n\n/**\n * Finds variables declared as aliases of an action-catalog function.\n *\n * Examples this catches:\n * - `const action = request`\n * - `const action = http.request`\n * - `const { request: action } = http`\n *\n * We do not try to follow these aliases. Instead, we mark them as unsupported\n * so a later `action(...)` call fails closed instead of silently missing a\n * `connectionId`.\n */\nfunction getActionCatalogAliasVariables(\n node: VariableDeclarator,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n // `const action = request`\n if (\n node.id.type === 'Identifier' &&\n node.init?.type === 'Identifier' &&\n resolvesTo(node.init, scopeAnalysis.actionFunctions, scopeAnalysis)\n ) {\n return getDeclaredVariables(node, scopeAnalysis, [node.id.name]);\n }\n\n // `const action = http.request`\n if (\n node.id.type === 'Identifier' &&\n node.init?.type === 'MemberExpression' &&\n isNamespaceMember(node.init, scopeAnalysis)\n ) {\n return getDeclaredVariables(node, scopeAnalysis, [node.id.name]);\n }\n\n // Ignore declarations that are not destructuring an action-catalog namespace,\n // then handle `const { request: action } = http` below.\n if (\n node.id.type !== 'ObjectPattern' ||\n node.init?.type !== 'Identifier' ||\n !resolvesTo(node.init, scopeAnalysis.actionNamespaces, scopeAnalysis)\n ) {\n return [];\n }\n\n // In a declaration, eslint-scope can give us declared variables from the\n // whole `const { request: action } = http` node. We only need identifier\n // names to pick the alias variables out of that declaration result.\n const aliasNames = node.id.properties\n .flatMap((property) => {\n if (property.type === 'RestElement' || property.computed) {\n return [];\n }\n return collectPatternIdentifiers(property.value);\n })\n .map((identifier) => identifier.name);\n return getDeclaredVariables(node, scopeAnalysis, aliasNames);\n}\n\n/**\n * Finds existing variables that are assigned an action-catalog function after\n * they have already been declared.\n *\n * Examples this catches:\n * - `let action; action = request`\n * - `let action; action = http.request`\n * - `let action; ({ request: action } = http)`\n *\n * These are the assignment-expression versions of the declarations handled by\n * `getActionCatalogAliasVariables`.\n */\nfunction getAssignedActionCatalogAliasVariables(\n node: AssignmentExpression,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n // `let action; action = request`\n if (\n node.left.type === 'Identifier' &&\n node.right.type === 'Identifier' &&\n resolvesTo(node.right, scopeAnalysis.actionFunctions, scopeAnalysis)\n ) {\n return getResolvedVariables([node.left], scopeAnalysis);\n }\n\n // `let action; action = http.request`\n if (\n node.left.type === 'Identifier' &&\n node.right.type === 'MemberExpression' &&\n isNamespaceMember(node.right, scopeAnalysis)\n ) {\n return getResolvedVariables([node.left], scopeAnalysis);\n }\n\n // Ignore assignments that are not destructuring an action-catalog namespace,\n // then handle `let action; ({ request: action } = http)` below.\n if (\n node.left.type !== 'ObjectPattern' ||\n node.right.type !== 'Identifier' ||\n !resolvesTo(node.right, scopeAnalysis.actionNamespaces, scopeAnalysis)\n ) {\n return [];\n }\n\n // In an assignment, the variables already exist. Keep the actual identifier\n // nodes so eslint-scope can resolve each one back to the existing variable.\n const aliasIdentifiers = node.left.properties.flatMap((property) => {\n if (property.type === 'RestElement' || property.computed) {\n return [];\n }\n return collectPatternIdentifiers(property.value);\n });\n return getResolvedVariables(aliasIdentifiers, scopeAnalysis);\n}\n\n/**\n * Returns true when a property access starts from an imported action-catalog\n * namespace.\n *\n * For `http.request(...)`, this checks that `http` is the namespace imported by\n * `import * as http from '@datadog/action-catalog/...'`, not a local variable\n * that happens to be named `http`.\n */\nfunction isNamespaceMember(\n node: MemberExpression,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): boolean {\n const root = getMemberExpressionRoot(node);\n return !!root && resolvesTo(root, scopeAnalysis.actionNamespaces, scopeAnalysis);\n}\n\n/**\n * Returns the left-most identifier in a property access chain.\n *\n * Examples:\n * - `http.request` -> `http`\n * - `catalog.http.request` -> `catalog`\n *\n * The root name is what scope analysis can resolve back to an import or local\n * declaration.\n */\nfunction getMemberExpressionRoot(node: MemberExpression): Identifier | undefined {\n if (node.object.type === 'Identifier') {\n return node.object;\n }\n if (node.object.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\n/**\n * Detects namespace call shapes we intentionally do not support.\n *\n * We only support direct, non-optional property access like `http.request(...)`.\n * Computed or optional forms such as `http['request'](...)` and\n * `http?.request(...)` could hide what action is called, so they fail closed.\n */\nfunction hasUnsupportedMemberAccess(node: MemberExpression): boolean {\n if (node.optional || node.computed) {\n return true;\n }\n return node.object.type === 'MemberExpression' && hasUnsupportedMemberAccess(node.object);\n}\n\n/**\n * Checks whether an identifier points to one of the exact variables we care\n * about.\n *\n * This is the shadowing-safe comparison. For example, a local function\n * parameter named `request` has the same text as an imported `request`, but\n * eslint-scope resolves it to a different variable.\n *\n * @param identifier - The exact identifier node from the AST, such as the\n * `request` in `request(...)`.\n * @param variables - The set of allowed target variables, such as the imported\n * action-catalog function declarations.\n * @param scopeAnalysis - The precomputed eslint-scope lookup tables that map\n * identifier nodes back to the variables they reference.\n */\nfunction resolvesTo(\n identifier: Identifier,\n variables: ReadonlySet<eslintScope.Variable>,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): boolean {\n return resolvesToModuleVariable(identifier, variables, scopeAnalysis.moduleScope);\n}\n\n/**\n * Converts identifier nodes into the variables they refer to.\n *\n * This is used for assignment aliases because the variable already exists:\n * `action = request` does not declare `action`, it only assigns to it. We ask\n * eslint-scope which existing variable that `action` identifier points to.\n */\nfunction getResolvedVariables(\n identifiers: Identifier[],\n scopeAnalysis: ActionCatalogScopeAnalysis,\n): eslintScope.Variable[] {\n return identifiers.flatMap((identifier) => {\n const variable = resolveIdentifier(identifier, scopeAnalysis.moduleScope);\n return variable ? [variable] : [];\n });\n}\n\n/**\n * Returns variables created by a declaration node, limited to the names we\n * extracted from the declaration pattern.\n *\n * This is used for alias declarations like `const action = request`, where the\n * declaration itself creates the `action` variable we need to remember.\n */\nfunction getDeclaredVariables(\n node: Node,\n scopeAnalysis: ActionCatalogScopeAnalysis,\n names: string[],\n): eslintScope.Variable[] {\n // Alias declarations are tracked as Variables too, so later `action(...)`\n // calls can fail closed only when they resolve to the alias we identified.\n const wantedNames = new Set(names);\n return scopeAnalysis.moduleScope.scopeManager\n .getDeclaredVariables(node)\n .filter((variable) => wantedNames.has(variable.name));\n}\n\n/**\n * Pulls identifier nodes out of a declaration or assignment pattern.\n *\n * Patterns are the left side of declarations or assignments, such as:\n * - `const action = ...`\n * - `const { request: action } = ...`\n * - `({ request: action } = ...)`\n *\n * Declarations use the identifier names to filter variables created by the\n * declaration. Assignments use the identifier nodes directly, because\n * eslint-scope resolves those nodes to existing variables.\n */\nfunction collectPatternIdentifiers(pattern: Pattern): Identifier[] {\n switch (pattern.type) {\n case 'Identifier':\n return [pattern];\n case 'ObjectPattern':\n return pattern.properties.flatMap((property) => {\n if (property.type === 'RestElement') {\n return collectPatternIdentifiers(property.argument);\n }\n return collectPatternIdentifiers(property.value);\n });\n case 'ArrayPattern':\n return pattern.elements.flatMap((element) =>\n element ? collectPatternIdentifiers(element) : [],\n );\n case 'RestElement':\n return collectPatternIdentifiers(pattern.argument);\n case 'AssignmentPattern':\n return collectPatternIdentifiers(pattern.left);\n case 'MemberExpression':\n return [];\n }\n}\n\nfunction unsupportedActionCatalogCall(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported action-catalog call in ${filePath}: ${unsupported} could hide a connectionId.`,\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 { Program } from 'estree';\n\nimport { isTypeOnly } from './type-guards';\n\nconst ACTION_CATALOG_PACKAGE = '@datadog/action-catalog';\n\nexport interface ActionCatalogImports {\n functions: Set<string>;\n namespaces: Set<string>;\n}\n\nexport function collectActionCatalogImports(ast: Program): ActionCatalogImports {\n const functions = new Set<string>();\n const namespaces = new Set<string>();\n\n for (const node of ast.body) {\n if (node.type !== 'ImportDeclaration' || !isActionCatalogSource(node.source.value)) {\n continue;\n }\n if (isTypeOnly(node)) {\n continue;\n }\n\n for (const specifier of node.specifiers) {\n if (isTypeOnly(specifier)) {\n continue;\n }\n\n if (specifier.type === 'ImportNamespaceSpecifier') {\n namespaces.add(specifier.local.name);\n } else {\n functions.add(specifier.local.name);\n }\n }\n }\n\n return { functions, namespaces };\n}\n\nfunction isActionCatalogSource(source: unknown): boolean {\n return (\n typeof source === 'string' &&\n (source === ACTION_CATALOG_PACKAGE || source.startsWith(`${ACTION_CATALOG_PACKAGE}/`))\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 * as eslintScope from 'eslint-scope';\nimport type { Identifier } from 'estree';\n\nimport type {\n ConstStaticBinding,\n ExportBinding,\n ImportBinding,\n MutableStaticBinding,\n ParsedModuleRecord,\n} from './module-graph';\nimport { resolveIdentifier } from './module-scope';\n\nexport type StaticDefinition = LocalStaticDefinition | UnsupportedStaticDefinition;\n\nexport interface LocalStaticDefinition {\n kind: 'local';\n moduleId: string;\n variable: eslintScope.Variable;\n binding: ConstStaticBinding;\n hops: StaticDefinitionHop[];\n}\n\nexport type UnsupportedStaticDefinition =\n | AmbiguousStarExportStaticDefinition\n | CycleStaticDefinition\n | DefaultExportStaticDefinition\n | DefaultImportStaticDefinition\n | MissingExportStaticDefinition\n | MissingModuleRecordForExportStaticDefinition\n | MissingModuleRecordForVariableStaticDefinition\n | MissingStaticBindingStaticDefinition\n | MutableBindingStaticDefinition\n | NamespaceImportStaticDefinition\n | UnresolvedIdentifierStaticDefinition\n | UnsupportedBindingStaticDefinition\n | UnsupportedExportStaticDefinition;\n\ninterface UnsupportedStaticDefinitionBase {\n kind: 'unsupported';\n moduleId: string;\n message: string;\n hops: StaticDefinitionHop[];\n}\n\nexport interface AmbiguousStarExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'ambiguous-star-export';\n exportName: string;\n}\n\nexport interface CycleStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'cycle';\n exportName: string;\n}\n\nexport interface DefaultExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'default-export';\n exportName: string;\n}\n\nexport interface DefaultImportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'default-import';\n variableName: string;\n}\n\nexport interface MissingExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'missing-export';\n exportName: string;\n}\n\nexport interface MissingModuleRecordForExportStaticDefinition\n extends UnsupportedStaticDefinitionBase {\n reason: 'missing-module-record';\n requestKind: 'export';\n exportName: string;\n}\n\nexport interface MissingModuleRecordForVariableStaticDefinition\n extends UnsupportedStaticDefinitionBase {\n reason: 'missing-module-record';\n requestKind: 'variable';\n variableName: string;\n}\n\nexport interface MissingStaticBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'missing-static-binding';\n variableName: string;\n}\n\nexport interface MutableBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'mutable-binding';\n variableName: string;\n declarationKind: MutableStaticBinding['declarationKind'];\n}\n\nexport interface NamespaceImportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'namespace-import';\n variableName: string;\n}\n\nexport interface UnresolvedIdentifierStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unresolved-identifier';\n variableName: string;\n}\n\nexport interface UnsupportedBindingStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unsupported-binding';\n variableName: string;\n bindingReason: string;\n}\n\nexport interface UnsupportedExportStaticDefinition extends UnsupportedStaticDefinitionBase {\n reason: 'unsupported-export';\n exportName: string;\n exportReason: string;\n}\n\nexport type StaticDefinitionHop =\n | ImportStaticDefinitionHop\n | LocalExportStaticDefinitionHop\n | ReExportStaticDefinitionHop\n | StarExportStaticDefinitionHop;\n\nexport interface ImportStaticDefinitionHop {\n kind: 'import';\n moduleId: string;\n localName: string;\n exportName: string;\n sourceModuleId: string;\n}\n\nexport interface LocalExportStaticDefinitionHop {\n kind: 'local-export';\n moduleId: string;\n exportName: string;\n localName: string;\n}\n\nexport interface ReExportStaticDefinitionHop {\n kind: 're-export';\n moduleId: string;\n exportName: string;\n sourceModuleId: string;\n sourceExportName: string;\n}\n\nexport interface StarExportStaticDefinitionHop {\n kind: 'star-export';\n moduleId: string;\n exportName: string;\n sourceModuleId: string;\n}\n\ninterface ResolverState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n visitedExports: Set<string>;\n}\n\nexport function resolveStaticDefinitionForIdentifier(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n moduleId: string,\n identifier: Identifier,\n): StaticDefinition {\n const record = modules.get(moduleId);\n if (!record) {\n return unsupportedMissingModuleRecordForVariable(moduleId, [], identifier.name);\n }\n\n const variable = resolveIdentifier(identifier, record.scopeAnalysis);\n if (!variable) {\n // Example: request({ connectionId: HTTP_ID }); when HTTP_ID is not in scope.\n return unsupportedUnresolvedIdentifier(moduleId, [], identifier.name);\n }\n if (isDefinitionIdentifier(identifier, variable)) {\n // Example: const HTTP_ID = 'conn-http'; when HTTP_ID is the declaration itself.\n return unsupportedUnresolvedIdentifier(moduleId, [], identifier.name);\n }\n\n return resolveVariable({ modules, visitedExports: new Set() }, moduleId, variable, []);\n}\n\nfunction isDefinitionIdentifier(identifier: Identifier, variable: eslintScope.Variable): boolean {\n return variable.defs.some((definition) => definition.name === identifier);\n}\n\nfunction resolveExport(\n state: ResolverState,\n moduleId: string,\n exportName: string,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n const record = state.modules.get(moduleId);\n if (!record) {\n return unsupportedMissingModuleRecordForExport(moduleId, hops, exportName);\n }\n\n if (exportName === 'default') {\n // Example: export { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultExport(moduleId, hops, exportName);\n }\n\n const visitKey = `${moduleId}\\0${exportName}`;\n if (state.visitedExports.has(visitKey)) {\n // Example: export * from './index.js'; when index.js eventually points back here.\n return unsupportedCycle(moduleId, hops, exportName);\n }\n\n state.visitedExports.add(visitKey);\n try {\n const explicitExport = record.exportsByName.get(exportName);\n if (explicitExport) {\n return resolveExplicitExport(state, record, exportName, explicitExport, hops);\n }\n\n return resolveStarExport(state, record, exportName, hops);\n } finally {\n state.visitedExports.delete(visitKey);\n }\n}\n\nfunction resolveExplicitExport(\n state: ResolverState,\n record: ParsedModuleRecord,\n exportName: string,\n binding: ExportBinding,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n if (binding.kind === 'unsupported') {\n // Example: export * as ids from './ids.js';\n return unsupportedExport(record.id, hops, exportName, binding.reason);\n }\n\n if (binding.kind === 're-export') {\n if (binding.importedName === 'default') {\n // Example: export { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultExport(record.id, hops, exportName);\n }\n\n return resolveExport(state, binding.resolvedId, binding.importedName, [\n ...hops,\n {\n kind: 're-export',\n moduleId: record.id,\n exportName,\n sourceModuleId: binding.resolvedId,\n sourceExportName: binding.importedName,\n },\n ]);\n }\n\n return resolveVariable(state, record.id, binding.variable, [\n ...hops,\n {\n kind: 'local-export',\n moduleId: record.id,\n exportName,\n localName: binding.variable.name,\n },\n ]);\n}\n\nfunction resolveStarExport(\n state: ResolverState,\n record: ParsedModuleRecord,\n exportName: string,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n let candidate: LocalStaticDefinition | undefined;\n\n for (const starExport of record.starExports) {\n const result = resolveExport(state, starExport.resolvedId, exportName, [\n ...hops,\n {\n kind: 'star-export',\n moduleId: record.id,\n exportName,\n sourceModuleId: starExport.resolvedId,\n },\n ]);\n\n if (result.kind === 'unsupported') {\n if (result.reason === 'missing-export') {\n continue;\n }\n\n return result;\n }\n\n if (candidate && isSameLocalDefinition(candidate, result)) {\n continue;\n }\n\n if (candidate) {\n // Example: export * from './one.js'; export * from './two.js';\n return unsupportedAmbiguousStarExport(record.id, hops, exportName);\n }\n candidate = result;\n }\n\n // Example: export * from './ids.js'; when ids.js does not export HTTP_ID.\n return candidate ?? unsupportedMissingExport(record.id, hops, exportName);\n}\n\nfunction isSameLocalDefinition(left: LocalStaticDefinition, right: LocalStaticDefinition): boolean {\n return left.moduleId === right.moduleId && left.variable === right.variable;\n}\n\nfunction resolveVariable(\n state: ResolverState,\n moduleId: string,\n variable: eslintScope.Variable,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n const record = state.modules.get(moduleId);\n if (!record) {\n // Example: resolving HTTP_ID after following an import to a module that was not collected.\n return unsupportedMissingModuleRecordForVariable(moduleId, hops, variable.name);\n }\n\n const importBinding = record.importsByVariable.get(variable);\n if (importBinding) {\n return resolveImportBinding(state, record.id, variable.name, importBinding, hops);\n }\n\n const binding = record.topLevelBindingsByVariable.get(variable);\n if (!binding) {\n // Example: export { HTTP_ID }; when HTTP_ID is not a recorded top-level binding.\n return unsupportedMissingStaticBinding(record.id, hops, variable.name);\n }\n\n if (binding.kind === 'const') {\n return { kind: 'local', moduleId: record.id, variable, binding, hops };\n }\n\n if (binding.kind === 'mutable') {\n // Example: export let HTTP_ID = 'conn-http';\n return unsupportedMutableBinding(record.id, hops, variable.name, binding.declarationKind);\n }\n\n // Example: export function getId() { return 'conn-http'; }\n return unsupportedBinding(record.id, hops, variable.name, binding.reason);\n}\n\nfunction resolveImportBinding(\n state: ResolverState,\n moduleId: string,\n localName: string,\n binding: ImportBinding,\n hops: StaticDefinitionHop[],\n): StaticDefinition {\n if (binding.kind === 'default') {\n // Example: import HTTP_ID from './ids.js';\n return unsupportedDefaultImport(moduleId, hops, localName);\n }\n\n if (binding.kind === 'namespace') {\n // Example: import * as ids from './ids.js';\n return unsupportedNamespaceImport(moduleId, hops, localName);\n }\n\n if (binding.importedName === 'default') {\n // Example: import { default as HTTP_ID } from './ids.js';\n return unsupportedDefaultImport(moduleId, hops, localName);\n }\n\n return resolveExport(state, binding.resolvedId, binding.importedName, [\n ...hops,\n {\n kind: 'import',\n moduleId,\n localName,\n exportName: binding.importedName,\n sourceModuleId: binding.resolvedId,\n },\n ]);\n}\n\nfunction unsupportedAmbiguousStarExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): AmbiguousStarExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'ambiguous-star-export',\n exportName,\n message: `Module '${moduleId}' exposes ambiguous star exports for '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedCycle(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): CycleStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'cycle',\n exportName,\n message: `Resolving export '${exportName}' from module '${moduleId}' would cycle through the module graph.`,\n hops,\n };\n}\n\nfunction unsupportedDefaultExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): DefaultExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'default-export',\n exportName,\n message: `Export '${exportName}' from module '${moduleId}' resolves through an unsupported default export.`,\n hops,\n };\n}\n\nfunction unsupportedDefaultImport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): DefaultImportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'default-import',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' is an unsupported default import.`,\n hops,\n };\n}\n\nfunction unsupportedMissingExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): MissingExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-export',\n exportName,\n message: `Module '${moduleId}' does not expose export '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingModuleRecordForExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n): MissingModuleRecordForExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-module-record',\n requestKind: 'export',\n exportName,\n message: `Module '${moduleId}' was not collected while resolving export '${exportName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingModuleRecordForVariable(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): MissingModuleRecordForVariableStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-module-record',\n requestKind: 'variable',\n variableName,\n message: `Module '${moduleId}' was not collected while resolving variable '${variableName}'.`,\n hops,\n };\n}\n\nfunction unsupportedMissingStaticBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): MissingStaticBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-static-binding',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' does not have a recorded top-level static binding.`,\n hops,\n };\n}\n\nfunction unsupportedMutableBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n declarationKind: MutableStaticBinding['declarationKind'],\n): MutableBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'mutable-binding',\n variableName,\n declarationKind,\n message: `Variable '${variableName}' in module '${moduleId}' is declared with mutable '${declarationKind}'.`,\n hops,\n };\n}\n\nfunction unsupportedNamespaceImport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): NamespaceImportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'namespace-import',\n variableName,\n message: `Variable '${variableName}' in module '${moduleId}' is an unsupported namespace import.`,\n hops,\n };\n}\n\nfunction unsupportedUnresolvedIdentifier(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n): UnresolvedIdentifierStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unresolved-identifier',\n variableName,\n message: `Identifier '${variableName}' in module '${moduleId}' is not a resolvable reference.`,\n hops,\n };\n}\n\nfunction unsupportedBinding(\n moduleId: string,\n hops: StaticDefinitionHop[],\n variableName: string,\n bindingReason: string,\n): UnsupportedBindingStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-binding',\n variableName,\n bindingReason,\n message: `Variable '${variableName}' in module '${moduleId}' has unsupported binding: ${bindingReason}.`,\n hops,\n };\n}\n\nfunction unsupportedExport(\n moduleId: string,\n hops: StaticDefinitionHop[],\n exportName: string,\n exportReason: string,\n): UnsupportedExportStaticDefinition {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-export',\n exportName,\n exportReason,\n message: `Export '${exportName}' from module '${moduleId}' is unsupported: ${exportReason}.`,\n hops,\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 * as eslintScope from 'eslint-scope';\nimport type {\n Expression,\n Identifier,\n Literal,\n MemberExpression,\n ObjectExpression,\n Pattern,\n Property,\n Super,\n TemplateLiteral,\n VariableDeclaration,\n VariableDeclarator,\n} from 'estree';\n\nimport type { ParsedModuleRecord } from './module-graph';\nimport { isImportVariable, resolveIdentifier } from './module-scope';\nimport {\n resolveStaticDefinitionForIdentifier,\n type UnsupportedStaticDefinition,\n} from './static-definition-resolution';\nimport { walkAst } from './walk-ast';\n\nexport type StaticStringValueResolution = ResolvedStaticStringValue | UnsupportedStaticStringValue;\n\nexport interface ResolvedStaticStringValue {\n kind: 'resolved';\n moduleId: string;\n value: string;\n}\n\nexport type UnsupportedStaticStringValue =\n | AccessorObjectPropertyStaticStringValue\n | ComputedMemberExpressionStaticStringValue\n | ComputedObjectPropertyStaticStringValue\n | CycleStaticStringValue\n | DuplicateObjectPropertyStaticStringValue\n | DynamicTemplateLiteralStaticStringValue\n | ImportedObjectMutationStaticStringValue\n | MissingObjectPropertyStaticStringValue\n | NonObjectMemberValueStaticStringValue\n | NonStaticMemberPropertyStaticStringValue\n | NonStringLiteralStaticStringValue\n | ObjectSpreadStaticStringValue\n | OptionalMemberExpressionStaticStringValue\n | StaticDefinitionUnsupportedStaticStringValue\n | UninitializedConstStaticStringValue\n | UnsupportedExpressionStaticStringValue\n | UnsupportedObjectPropertyValueStaticStringValue;\n\ninterface UnsupportedStaticStringValueBase {\n kind: 'unsupported';\n moduleId: string;\n message: string;\n}\n\n// Example: const CONNECTIONS = { get HTTP() { return 'conn-http'; } };\nexport interface AccessorObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'accessor-object-property';\n propertyName: string;\n}\n\n// Example: CONNECTIONS[key]\nexport interface ComputedMemberExpressionStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'computed-member-expression';\n}\n\n// Example: const CONNECTIONS = { [key]: 'conn-http' };\nexport interface ComputedObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'computed-object-property';\n}\n\n// Example: const A = B; const B = A;\nexport interface CycleStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'cycle';\n variableName: string;\n}\n\n// Example: const CONNECTIONS = { HTTP: 'a', HTTP: 'b' };\nexport interface DuplicateObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'duplicate-object-property';\n propertyName: string;\n}\n\n// Example: const VALUE = `${prefix}-http`;\nexport interface DynamicTemplateLiteralStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'dynamic-template-literal';\n}\n\n// Example: import { CONNECTIONS } from './ids.js'; CONNECTIONS.HTTP = 'conn-b';\nexport interface ImportedObjectMutationStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'imported-object-mutation';\n variableName: string;\n}\n\n// Example: const CONNECTIONS = { SLACK: 'conn-slack' }; CONNECTIONS.HTTP\nexport interface MissingObjectPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'missing-object-property';\n propertyName: string;\n}\n\n// Example: const CONNECTIONS = { HTTP: 'conn-http' }; CONNECTIONS.HTTP.PROD\nexport interface NonObjectMemberValueStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-object-member-value';\n expressionType: string;\n}\n\n// Example: object.#privateValue\nexport interface NonStaticMemberPropertyStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-static-member-property';\n propertyType: string;\n}\n\n// Example: const VALUE = 123;\nexport interface NonStringLiteralStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'non-string-literal';\n valueType: string;\n}\n\n// Example: const CONNECTIONS = { ...baseConnections };\nexport interface ObjectSpreadStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'object-spread';\n}\n\n// Example: CONNECTIONS?.HTTP\nexport interface OptionalMemberExpressionStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'optional-member-expression';\n}\n\n// Example: import HTTP_ID from './ids.js';\nexport interface StaticDefinitionUnsupportedStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'static-definition-unsupported';\n variableName: string;\n definition: UnsupportedStaticDefinition;\n}\n\n// Defensive parser edge: a const binding exists without an initializer expression.\nexport interface UninitializedConstStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'uninitialized-const';\n variableName: string;\n}\n\n// Example: getConnectionId()\nexport interface UnsupportedExpressionStaticStringValue extends UnsupportedStaticStringValueBase {\n reason: 'unsupported-expression';\n expressionType: string;\n}\n\n// Defensive parser edge: an object property value is a pattern instead of an expression.\nexport interface UnsupportedObjectPropertyValueStaticStringValue\n extends UnsupportedStaticStringValueBase {\n reason: 'unsupported-object-property-value';\n propertyName: string;\n valueType: string;\n}\n\ninterface ResolverState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n mutatedImportedObjectVariables: ReadonlySet<eslintScope.Variable>;\n seenVariables: Set<eslintScope.Variable>;\n}\n\ninterface ImportedObjectMutationState {\n modules: ReadonlyMap<string, ParsedModuleRecord>;\n mutatedVariables: Set<eslintScope.Variable>;\n record: ParsedModuleRecord;\n}\n\ninterface ResolvedStaticExpression {\n kind: 'resolved';\n moduleId: string;\n expression: Expression;\n}\n\ntype StaticExpressionResolution = ResolvedStaticExpression | UnsupportedStaticStringValue;\n\ninterface ResolvedStaticObjectExpression {\n kind: 'resolved';\n moduleId: string;\n expression: ObjectExpression;\n}\n\ntype StaticObjectExpressionResolution =\n | ResolvedStaticObjectExpression\n | UnsupportedStaticStringValue;\n\ntype StaticObjectProperty = Property & { value: Expression };\n\ntype TypeScriptExpressionWrapper = Expression & {\n expression?: Expression;\n};\n\nexport function resolveStaticStringValue(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n moduleId: string,\n expression: Expression,\n): StaticStringValueResolution {\n return resolveExpression(\n {\n modules,\n mutatedImportedObjectVariables: collectMutatedImportedObjectVariables(modules),\n seenVariables: new Set(),\n },\n moduleId,\n expression,\n );\n}\n\nfunction resolveExpression(\n state: ResolverState,\n moduleId: string,\n rawExpression: Expression,\n): StaticStringValueResolution {\n const expression = unwrapStaticExpression(rawExpression);\n\n switch (expression.type) {\n case 'Literal':\n return resolveLiteral(moduleId, expression);\n case 'TemplateLiteral':\n return resolveTemplateLiteral(moduleId, expression);\n case 'Identifier':\n return resolveIdentifierValue(state, moduleId, expression);\n case 'MemberExpression':\n return resolveMemberExpressionValue(state, moduleId, expression);\n default:\n return unsupportedExpression(moduleId, expression.type);\n }\n}\n\nfunction resolveLiteral(moduleId: string, expression: Literal): StaticStringValueResolution {\n if (typeof expression.value === 'string') {\n return {\n kind: 'resolved',\n moduleId,\n value: expression.value,\n };\n }\n\n return unsupportedNonStringLiteral(moduleId, typeof expression.value);\n}\n\nfunction resolveTemplateLiteral(\n moduleId: string,\n expression: TemplateLiteral,\n): StaticStringValueResolution {\n if (expression.expressions.length > 0) {\n return unsupportedDynamicTemplateLiteral(moduleId);\n }\n\n return {\n kind: 'resolved',\n moduleId,\n value: expression.quasis.map((quasi) => quasi.value.cooked ?? quasi.value.raw).join(''),\n };\n}\n\nfunction resolveIdentifierValue(\n state: ResolverState,\n moduleId: string,\n identifier: Identifier,\n): StaticStringValueResolution {\n // Follow local bindings, imports, and exports to the const definition that owns the value.\n const definition = resolveStaticDefinitionForIdentifier(state.modules, moduleId, identifier);\n\n if (definition.kind === 'unsupported') {\n return unsupportedStaticDefinition(definition, identifier.name);\n }\n\n if (!definition.binding.expression) {\n return unsupportedUninitializedConst(definition.moduleId, definition.variable.name);\n }\n\n // Track the resolved variable so aliases and reexports share the same cycle guard.\n if (state.seenVariables.has(definition.variable)) {\n return unsupportedCycle(definition.moduleId, definition.variable.name);\n }\n\n state.seenVariables.add(definition.variable);\n try {\n return resolveExpression(state, definition.moduleId, definition.binding.expression);\n } finally {\n state.seenVariables.delete(definition.variable);\n }\n}\n\nfunction resolveMemberExpressionValue(\n state: ResolverState,\n moduleId: string,\n expression: MemberExpression,\n): StaticStringValueResolution {\n const resolvedExpression = resolveObjectMemberExpression(state, moduleId, expression);\n if (resolvedExpression.kind === 'unsupported') {\n return resolvedExpression;\n }\n\n return resolveExpression(state, resolvedExpression.moduleId, resolvedExpression.expression);\n}\n\nfunction resolveObjectMemberExpression(\n state: ResolverState,\n moduleId: string,\n expression: MemberExpression,\n): StaticExpressionResolution {\n if (expression.optional) {\n // Example: CONNECTIONS?.HTTP\n return unsupportedOptionalMemberExpression(moduleId);\n }\n if (expression.computed) {\n // Example: CONNECTIONS[key]\n return unsupportedComputedMemberExpression(moduleId);\n }\n if (expression.property.type !== 'Identifier') {\n return unsupportedNonStaticMemberProperty(moduleId, expression.property.type);\n }\n\n const objectExpression = resolveObjectExpressionValue(state, moduleId, expression.object);\n if (objectExpression.kind === 'unsupported') {\n return objectExpression;\n }\n\n return resolveObjectPropertyExpression(\n objectExpression.moduleId,\n objectExpression.expression,\n expression.property.name,\n );\n}\n\nfunction resolveObjectExpressionValue(\n state: ResolverState,\n moduleId: string,\n rawExpression: Expression | Super,\n): StaticObjectExpressionResolution {\n if (rawExpression.type === 'Super') {\n return unsupportedNonObjectMemberValue(moduleId, rawExpression.type);\n }\n\n const expression = unwrapStaticExpression(rawExpression);\n\n if (expression.type === 'ObjectExpression') {\n return {\n kind: 'resolved',\n moduleId,\n expression,\n };\n }\n\n if (expression.type === 'MemberExpression') {\n const memberExpression = resolveObjectMemberExpression(state, moduleId, expression);\n if (memberExpression.kind === 'unsupported') {\n return memberExpression;\n }\n\n return resolveObjectExpressionValue(\n state,\n memberExpression.moduleId,\n memberExpression.expression,\n );\n }\n\n if (expression.type !== 'Identifier') {\n return unsupportedNonObjectMemberValue(moduleId, expression.type);\n }\n\n const definition = resolveStaticDefinitionForIdentifier(state.modules, moduleId, expression);\n\n if (definition.kind === 'unsupported') {\n return unsupportedStaticDefinition(definition, expression.name);\n }\n\n if (!definition.binding.expression) {\n return unsupportedUninitializedConst(definition.moduleId, definition.variable.name);\n }\n\n if (state.mutatedImportedObjectVariables.has(definition.variable)) {\n return unsupportedImportedObjectMutation(definition.moduleId, definition.variable.name);\n }\n\n if (state.seenVariables.has(definition.variable)) {\n return unsupportedCycle(definition.moduleId, definition.variable.name);\n }\n\n state.seenVariables.add(definition.variable);\n try {\n return resolveObjectExpressionValue(\n state,\n definition.moduleId,\n definition.binding.expression,\n );\n } finally {\n state.seenVariables.delete(definition.variable);\n }\n}\n\nfunction resolveObjectPropertyExpression(\n moduleId: string,\n objectExpression: ObjectExpression,\n propertyName: string,\n): StaticExpressionResolution {\n let match: StaticObjectProperty | undefined;\n\n for (const property of objectExpression.properties) {\n if (property.type === 'SpreadElement') {\n // Example: const CONNECTIONS = { ...baseConnections };\n return unsupportedObjectSpread(moduleId);\n }\n if (property.computed) {\n // Example: const CONNECTIONS = { [key]: 'conn-http' };\n return unsupportedComputedObjectProperty(moduleId);\n }\n\n const key = getStaticPropertyKey(property);\n if (key !== propertyName) {\n continue;\n }\n\n if (match) {\n // Example: const CONNECTIONS = { HTTP: 'a', HTTP: 'b' };\n return unsupportedDuplicateObjectProperty(moduleId, propertyName);\n }\n if (property.kind !== 'init') {\n // Example: const CONNECTIONS = { get HTTP() { return 'conn-http'; } };\n return unsupportedAccessorObjectProperty(moduleId, propertyName);\n }\n if (!hasExpressionValue(property)) {\n return unsupportedObjectPropertyValue(moduleId, propertyName, property.value.type);\n }\n\n match = property;\n }\n\n if (!match) {\n return unsupportedMissingObjectProperty(moduleId, propertyName);\n }\n\n return {\n kind: 'resolved',\n moduleId,\n expression: match.value,\n };\n}\n\nfunction hasExpressionValue(property: Property): property is Property & { value: Expression } {\n const { value } = property;\n return (\n value.type !== 'ObjectPattern' &&\n value.type !== 'ArrayPattern' &&\n value.type !== 'RestElement' &&\n value.type !== 'AssignmentPattern'\n );\n}\n\nfunction collectMutatedImportedObjectVariables(\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n): Set<eslintScope.Variable> {\n const mutatedVariables = new Set<eslintScope.Variable>();\n\n for (const record of modules.values()) {\n walkAst(\n record.ast,\n { modules, mutatedVariables, record },\n {\n AssignmentExpression(node, { state }) {\n markMutatedImportedPattern(node.left, state);\n },\n UpdateExpression(node, { state }) {\n markMutatedImportedPattern(node.argument, state);\n },\n UnaryExpression(node, { state }) {\n if (node.operator === 'delete') {\n markMutatedImportedPattern(node.argument, state);\n }\n },\n ForInStatement(node, { state }) {\n markMutatedImportedForIterationTarget(node.left, state);\n },\n ForOfStatement(node, { state }) {\n markMutatedImportedForIterationTarget(node.left, state);\n },\n },\n );\n }\n\n return mutatedVariables;\n}\n\nfunction markMutatedImportedForIterationTarget(\n left: Pattern | VariableDeclaration,\n state: ImportedObjectMutationState,\n): void {\n if (left.type !== 'VariableDeclaration') {\n markMutatedImportedPattern(left, state);\n }\n}\n\nfunction markMutatedImportedPattern(\n pattern: Pattern | Expression,\n state: ImportedObjectMutationState,\n): void {\n if (pattern.type === 'Identifier') {\n markMutatedImportedIdentifier(pattern, state);\n return;\n }\n\n if (pattern.type === 'MemberExpression') {\n const root = getMemberExpressionRoot(pattern);\n if (root) {\n markMutatedImportedIdentifier(root, state);\n }\n return;\n }\n\n if (pattern.type === 'ObjectPattern') {\n for (const property of pattern.properties) {\n markMutatedImportedPattern(\n property.type === 'RestElement' ? property.argument : property.value,\n state,\n );\n }\n return;\n }\n\n if (pattern.type === 'ArrayPattern') {\n for (const element of pattern.elements) {\n if (element) {\n markMutatedImportedPattern(element, state);\n }\n }\n return;\n }\n\n if (pattern.type === 'RestElement') {\n markMutatedImportedPattern(pattern.argument, state);\n return;\n }\n\n if (pattern.type === 'AssignmentPattern') {\n markMutatedImportedPattern(pattern.left, state);\n }\n}\n\nfunction markMutatedImportedIdentifier(\n identifier: Identifier,\n state: ImportedObjectMutationState,\n): void {\n const variable = resolveImportedObjectAlias(state, identifier, new Set());\n if (variable) {\n state.mutatedVariables.add(variable);\n }\n}\n\nfunction resolveImportedObjectAlias(\n state: ImportedObjectMutationState,\n identifier: Identifier,\n seenVariables: Set<eslintScope.Variable>,\n): eslintScope.Variable | undefined {\n const variable = resolveIdentifier(identifier, state.record.scopeAnalysis);\n if (!variable || seenVariables.has(variable)) {\n return undefined;\n }\n seenVariables.add(variable);\n\n if (isImportVariable(variable)) {\n const definition = resolveStaticDefinitionForIdentifier(\n state.modules,\n state.record.id,\n identifier,\n );\n return definition.kind === 'local' ? definition.variable : undefined;\n }\n\n const initializer = getVariableInitializer(variable);\n if (!initializer) {\n return undefined;\n }\n\n const root = getImportedObjectAliasRoot(initializer);\n if (!root) {\n return undefined;\n }\n\n return resolveImportedObjectAlias(state, root, seenVariables);\n}\n\nfunction getVariableInitializer(variable: eslintScope.Variable): Expression | undefined {\n for (const definition of variable.defs) {\n const node = definition.node as VariableDeclarator;\n if (node.type === 'VariableDeclarator' && node.init) {\n return node.init;\n }\n }\n\n return undefined;\n}\n\nfunction getImportedObjectAliasRoot(rawExpression: Expression): Identifier | undefined {\n const expression = unwrapStaticExpression(rawExpression);\n if (expression.type === 'Identifier') {\n return expression;\n }\n if (expression.type === 'MemberExpression') {\n return getMemberExpressionRoot(expression);\n }\n return undefined;\n}\n\nfunction getMemberExpressionRoot(node: Expression | Super): Identifier | undefined {\n if (node.type === 'Identifier') {\n return node;\n }\n if (node.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\nfunction getStaticPropertyKey(property: Property): string | undefined {\n if (property.key.type === 'Identifier') {\n return property.key.name;\n }\n if (property.key.type === 'Literal' && typeof property.key.value === 'string') {\n return property.key.value;\n }\n return undefined;\n}\n\nfunction unwrapStaticExpression(expression: Expression): Expression {\n let current = expression;\n\n while (isTypeScriptExpressionWrapper(current)) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction isTypeScriptExpressionWrapper(\n expression: Expression,\n): expression is TypeScriptExpressionWrapper & { expression: Expression } {\n const type = (expression as { type: string }).type;\n return (\n (type === 'TSAsExpression' ||\n type === 'TSSatisfiesExpression' ||\n type === 'TSNonNullExpression' ||\n type === 'TSTypeAssertion') &&\n !!(expression as TypeScriptExpressionWrapper).expression\n );\n}\n\nfunction unsupportedAccessorObjectProperty(\n moduleId: string,\n propertyName: string,\n): AccessorObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'accessor-object-property',\n propertyName,\n message: `Static object property '${propertyName}' in module '${moduleId}' is an accessor.`,\n };\n}\n\nfunction unsupportedComputedMemberExpression(\n moduleId: string,\n): ComputedMemberExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'computed-member-expression',\n message: `Computed member expressions in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedComputedObjectProperty(\n moduleId: string,\n): ComputedObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'computed-object-property',\n message: `Computed object properties in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedCycle(moduleId: string, variableName: string): CycleStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'cycle',\n variableName,\n message: `Resolving variable '${variableName}' in module '${moduleId}' would cycle through static string values.`,\n };\n}\n\nfunction unsupportedDuplicateObjectProperty(\n moduleId: string,\n propertyName: string,\n): DuplicateObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'duplicate-object-property',\n propertyName,\n message: `Static object in module '${moduleId}' has duplicate property '${propertyName}'.`,\n };\n}\n\nfunction unsupportedDynamicTemplateLiteral(\n moduleId: string,\n): DynamicTemplateLiteralStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'dynamic-template-literal',\n message: `Dynamic template literals in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedImportedObjectMutation(\n moduleId: string,\n variableName: string,\n): ImportedObjectMutationStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'imported-object-mutation',\n variableName,\n message: `Imported object '${variableName}' from module '${moduleId}' is mutated in the module graph.`,\n };\n}\n\nfunction unsupportedMissingObjectProperty(\n moduleId: string,\n propertyName: string,\n): MissingObjectPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'missing-object-property',\n propertyName,\n message: `Static object in module '${moduleId}' does not have property '${propertyName}'.`,\n };\n}\n\nfunction unsupportedNonObjectMemberValue(\n moduleId: string,\n expressionType: string,\n): NonObjectMemberValueStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-object-member-value',\n expressionType,\n message: `Expression type '${expressionType}' in module '${moduleId}' is not a static object value.`,\n };\n}\n\nfunction unsupportedNonStaticMemberProperty(\n moduleId: string,\n propertyType: string,\n): NonStaticMemberPropertyStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-static-member-property',\n propertyType,\n message: `Member property type '${propertyType}' in module '${moduleId}' is not statically named.`,\n };\n}\n\nfunction unsupportedNonStringLiteral(\n moduleId: string,\n valueType: string,\n): NonStringLiteralStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'non-string-literal',\n valueType,\n message: `Literal value type '${valueType}' in module '${moduleId}' is not a string.`,\n };\n}\n\nfunction unsupportedObjectPropertyValue(\n moduleId: string,\n propertyName: string,\n valueType: string,\n): UnsupportedObjectPropertyValueStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-object-property-value',\n propertyName,\n valueType,\n message: `Static object property '${propertyName}' in module '${moduleId}' has unsupported value type '${valueType}'.`,\n };\n}\n\nfunction unsupportedObjectSpread(moduleId: string): ObjectSpreadStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'object-spread',\n message: `Object spreads in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedOptionalMemberExpression(\n moduleId: string,\n): OptionalMemberExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'optional-member-expression',\n message: `Optional member expressions in module '${moduleId}' cannot be resolved to static strings.`,\n };\n}\n\nfunction unsupportedStaticDefinition(\n definition: UnsupportedStaticDefinition,\n variableName: string,\n): StaticDefinitionUnsupportedStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId: definition.moduleId,\n reason: 'static-definition-unsupported',\n variableName,\n definition,\n message: `Variable '${variableName}' could not be resolved to a static definition: ${definition.message}`,\n };\n}\n\nfunction unsupportedUninitializedConst(\n moduleId: string,\n variableName: string,\n): UninitializedConstStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'uninitialized-const',\n variableName,\n message: `Const variable '${variableName}' in module '${moduleId}' does not have an initializer.`,\n };\n}\n\nfunction unsupportedExpression(\n moduleId: string,\n expressionType: string,\n): UnsupportedExpressionStaticStringValue {\n return {\n kind: 'unsupported',\n moduleId,\n reason: 'unsupported-expression',\n expressionType,\n message: `Expression type '${expressionType}' in module '${moduleId}' cannot be resolved to a static string.`,\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 * as eslintScope from 'eslint-scope';\nimport type {\n BaseNode,\n ExportAllDeclaration,\n ExportNamedDeclaration,\n Expression,\n Identifier,\n ImportExpression,\n Literal,\n ModuleDeclaration,\n Pattern,\n Program,\n SimpleCallExpression,\n Super,\n VariableDeclaration,\n} from 'estree';\nimport path from 'path';\n\nimport { BACKEND_CODE_EXTENSIONS } from '../../constants';\n\nimport {\n analyzeModuleScope,\n getModuleVariable,\n isImportVariable,\n type ModuleScopeAnalysis,\n resolveIdentifier,\n} from './module-scope';\nimport { ensureProgram, isStringLiteral } from './type-guards';\nimport { walkAst } from './walk-ast';\n\n/**\n * Parsed app-local backend module plus reusable static facts about its module\n * boundary and top-level declarations. These facts are intentionally\n * domain-neutral: action-catalog and connection ID logic consume them later,\n * but they are not encoded into the record itself.\n */\nexport interface ParsedModuleRecord {\n id: string;\n ast: Program;\n scopeAnalysis: ModuleScopeAnalysis;\n staticDependencies: StaticModuleDependency[];\n unsupportedDependencies: ModuleDependency[];\n importsByVariable: Map<eslintScope.Variable, ImportBinding>;\n /**\n * Export names that can be answered directly by this module. Bare\n * `export *` edges stay in `starExports` because they must be probed by\n * requested export name during resolution.\n */\n exportsByName: Map<string, ExportBinding>;\n starExports: StarExport[];\n topLevelBindingsByVariable: Map<eslintScope.Variable, StaticBinding>;\n}\n\nexport interface StaticModuleDependency {\n source: string;\n resolvedId: string;\n}\n\nexport interface ModuleDependency {\n specifier: string;\n kind: 'dynamic-import' | 'require';\n}\n\n/**\n * Import binding keyed by the local eslint-scope variable, not the local text\n * name, so later lookups remain safe when names are shadowed.\n */\nexport type ImportBinding = NamedImportBinding | DefaultImportBinding | NamespaceImportBinding;\n\nexport interface NamedImportBinding {\n kind: 'named';\n importedName: string;\n resolvedId: string;\n}\n\nexport interface DefaultImportBinding {\n kind: 'default';\n resolvedId: string;\n}\n\nexport interface NamespaceImportBinding {\n kind: 'namespace';\n resolvedId: string;\n}\n\n/**\n * Export binding for names this module can answer without probing star\n * exports. Unsupported records preserve the fact that an export name exists\n * even when later static definition resolution will reject its form.\n */\nexport type ExportBinding = LocalExportBinding | ReExportBinding | UnsupportedExportBinding;\n\nexport interface LocalExportBinding {\n kind: 'local';\n variable: eslintScope.Variable;\n}\n\nexport interface ReExportBinding {\n kind: 're-export';\n importedName: string;\n resolvedId: string;\n}\n\nexport interface UnsupportedExportBinding {\n kind: 'unsupported';\n reason: string;\n resolvedId?: string;\n}\n\nexport interface StarExport {\n resolvedId: string;\n}\n\n/**\n * Top-level declaration summary. This records whether a local variable has a\n * static expression later resolvers can inspect, without deciding whether that\n * expression is meaningful for any particular domain.\n */\nexport type StaticBinding = ConstStaticBinding | MutableStaticBinding | UnsupportedStaticBinding;\n\nexport interface ConstStaticBinding {\n kind: 'const';\n expression: Expression | null;\n}\n\nexport interface MutableStaticBinding {\n kind: 'mutable';\n declarationKind: Exclude<VariableDeclaration['kind'], 'const'>;\n}\n\nexport interface UnsupportedStaticBinding {\n kind: 'unsupported';\n reason: string;\n}\n\ntype ImportCallExpression = SimpleCallExpression & { callee: { type: 'Import' } };\ntype ModuleExportName = Identifier | Literal;\n\nconst PACKAGE_MANAGER_DIRS = new Set(['node_modules', '.yarn']);\n\n/**\n * Creates the per-module analysis record consumed by backend-entry reachability\n * analysis. The caller supplies canonical module IDs and already-resolved\n * static dependency IDs instead of asking this module to resolve/load files.\n *\n * Returns null when the module is outside the analyzable app-local backend\n * graph, allowing build collectors to skip package/generated modules without\n * duplicating graph filtering rules.\n */\nexport function createParsedModuleRecord(\n moduleId: string,\n buildRoot: string,\n ast: BaseNode,\n staticDependencies: string[] = [],\n): ParsedModuleRecord | null {\n if (!shouldTraverseCollectedModule(moduleId, buildRoot)) {\n return null;\n }\n\n const program = ensureProgram(ast, moduleId);\n const scopeAnalysis = analyzeModuleScope(program);\n const staticModuleDependencies = collectStaticModuleDependencies(program, staticDependencies);\n\n return {\n id: moduleId,\n ast: program,\n scopeAnalysis,\n staticDependencies: staticModuleDependencies,\n unsupportedDependencies: collectUnsupportedModuleDependencies(program),\n importsByVariable: collectImportBindings(program, scopeAnalysis, staticModuleDependencies),\n exportsByName: collectExportBindings(program, scopeAnalysis, staticModuleDependencies),\n starExports: collectStarExports(program, staticModuleDependencies),\n topLevelBindingsByVariable: collectTopLevelBindings(program, scopeAnalysis),\n };\n}\n\nfunction collectStaticModuleDependencies(\n ast: Program,\n staticDependencyIds: string[],\n): StaticModuleDependency[] {\n const staticModuleSources = getStaticModuleSources(ast);\n\n return staticDependencyIds.map((resolvedId, index) => ({\n source: staticModuleSources[index] ?? resolvedId,\n resolvedId,\n }));\n}\n\n// Exported so a caller without build-time Rollup ModuleInfo (the dev server) can resolve each\n// specifier against this same list instead of a second AST walk that could drift from it.\nexport function getStaticModuleSources(ast: Program): string[] {\n return ast.body.flatMap((node) => {\n if (\n (node.type === 'ImportDeclaration' ||\n node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportAllDeclaration') &&\n node.source &&\n isStringLiteral(node.source)\n ) {\n return [node.source.value];\n }\n\n return [];\n });\n}\n\nfunction collectImportBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n): Map<eslintScope.Variable, ImportBinding> {\n const importsByVariable = new Map<eslintScope.Variable, ImportBinding>();\n\n for (const node of ast.body) {\n if (node.type !== 'ImportDeclaration' || !isStringLiteral(node.source)) {\n continue;\n }\n\n const resolvedId = getResolvedSource(staticDependencies, node.source.value);\n for (const specifier of node.specifiers) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(specifier);\n if (!variable) {\n continue;\n }\n\n if (specifier.type === 'ImportSpecifier') {\n importsByVariable.set(variable, {\n kind: 'named',\n importedName: getModuleExportName(specifier.imported),\n resolvedId,\n });\n continue;\n }\n\n importsByVariable.set(variable, {\n kind: specifier.type === 'ImportDefaultSpecifier' ? 'default' : 'namespace',\n resolvedId,\n });\n }\n }\n\n return importsByVariable;\n}\n\nfunction collectExportBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n): Map<string, ExportBinding> {\n const exportsByName = new Map<string, ExportBinding>();\n\n for (const node of ast.body) {\n if (node.type === 'ExportNamedDeclaration') {\n collectNamedExportBindings(node, scopeAnalysis, staticDependencies, exportsByName);\n continue;\n }\n\n if (node.type === 'ExportDefaultDeclaration') {\n exportsByName.set('default', { kind: 'unsupported', reason: 'default export' });\n continue;\n }\n\n if (node.type === 'ExportAllDeclaration') {\n collectNamespaceExportBinding(node, staticDependencies, exportsByName);\n }\n }\n\n return exportsByName;\n}\n\nfunction collectNamedExportBindings(\n node: ExportNamedDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n staticDependencies: StaticModuleDependency[],\n exportsByName: Map<string, ExportBinding>,\n): void {\n if (node.declaration) {\n collectDeclarationExportBindings(node.declaration, scopeAnalysis, exportsByName);\n return;\n }\n\n if (node.source && isStringLiteral(node.source)) {\n const resolvedId = getResolvedSource(staticDependencies, node.source.value);\n for (const specifier of node.specifiers) {\n if (specifier.type !== 'ExportSpecifier') {\n continue;\n }\n const exportedName = getModuleExportName(specifier.exported);\n if (exportedName === 'default') {\n exportsByName.set(exportedName, {\n kind: 'unsupported',\n reason: 'default re-export',\n resolvedId,\n });\n continue;\n }\n exportsByName.set(exportedName, {\n kind: 're-export',\n importedName: getModuleExportName(specifier.local),\n resolvedId,\n });\n }\n return;\n }\n\n for (const specifier of node.specifiers) {\n if (specifier.type !== 'ExportSpecifier') {\n continue;\n }\n const exportedName = getModuleExportName(specifier.exported);\n if (exportedName === 'default') {\n exportsByName.set(exportedName, {\n kind: 'unsupported',\n reason: 'default export',\n });\n continue;\n }\n const variable = getModuleVariable(getModuleExportName(specifier.local), scopeAnalysis);\n exportsByName.set(\n exportedName,\n variable\n ? { kind: 'local', variable }\n : { kind: 'unsupported', reason: 'unresolved local export' },\n );\n }\n}\n\nfunction collectDeclarationExportBindings(\n declaration: ExportNamedDeclaration['declaration'],\n scopeAnalysis: ModuleScopeAnalysis,\n exportsByName: Map<string, ExportBinding>,\n): void {\n if (!declaration) {\n return;\n }\n\n if (declaration.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations) {\n const variables = scopeAnalysis.scopeManager.getDeclaredVariables(declarator);\n if (declarator.id.type !== 'Identifier') {\n for (const variable of variables) {\n exportsByName.set(variable.name, {\n kind: 'unsupported',\n reason: 'binding pattern export',\n });\n }\n continue;\n }\n\n const [variable] = variables;\n if (variable) {\n exportsByName.set(declarator.id.name, { kind: 'local', variable });\n }\n }\n return;\n }\n\n if (\n (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&\n declaration.id\n ) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(declaration);\n if (variable) {\n exportsByName.set(declaration.id.name, { kind: 'local', variable });\n }\n }\n}\n\nfunction collectNamespaceExportBinding(\n node: ExportAllDeclaration,\n staticDependencies: StaticModuleDependency[],\n exportsByName: Map<string, ExportBinding>,\n): void {\n const exported = getExportAllExportedName(node);\n if (!exported || !isStringLiteral(node.source)) {\n return;\n }\n\n exportsByName.set(exported, {\n kind: 'unsupported',\n reason: 'namespace re-export',\n resolvedId: getResolvedSource(staticDependencies, node.source.value),\n });\n}\n\nfunction collectStarExports(\n ast: Program,\n staticDependencies: StaticModuleDependency[],\n): StarExport[] {\n return ast.body.flatMap((node) => {\n if (\n node.type !== 'ExportAllDeclaration' ||\n getExportAllExportedName(node) ||\n !isStringLiteral(node.source)\n ) {\n return [];\n }\n\n return [{ resolvedId: getResolvedSource(staticDependencies, node.source.value) }];\n });\n}\n\nfunction collectTopLevelBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n): Map<eslintScope.Variable, StaticBinding> {\n const bindings = new Map<eslintScope.Variable, StaticBinding>();\n\n for (const node of ast.body) {\n collectTopLevelNodeBindings(node, scopeAnalysis, bindings);\n }\n\n markReassignedTopLevelBindings(ast, scopeAnalysis, bindings);\n return bindings;\n}\n\nfunction collectTopLevelNodeBindings(\n node: ModuleDeclaration | Program['body'][number],\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (node.type === 'VariableDeclaration') {\n collectVariableDeclarationBindings(node, scopeAnalysis, bindings);\n return;\n }\n\n if (\n node.type === 'ExportNamedDeclaration' &&\n node.declaration?.type === 'VariableDeclaration'\n ) {\n collectVariableDeclarationBindings(node.declaration, scopeAnalysis, bindings);\n return;\n }\n\n const declaration =\n node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration'\n ? node.declaration\n : node;\n if (\n declaration &&\n (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&\n declaration.id\n ) {\n const [variable] = scopeAnalysis.scopeManager.getDeclaredVariables(declaration);\n if (variable) {\n bindings.set(variable, {\n kind: 'unsupported',\n reason: `${declaration.type} binding`,\n });\n }\n }\n}\n\nfunction collectVariableDeclarationBindings(\n declaration: VariableDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n for (const declarator of declaration.declarations) {\n const variables = scopeAnalysis.scopeManager.getDeclaredVariables(declarator);\n if (declarator.id.type !== 'Identifier') {\n for (const variable of variables) {\n bindings.set(variable, { kind: 'unsupported', reason: 'binding pattern' });\n }\n continue;\n }\n\n const [variable] = variables;\n if (!variable) {\n continue;\n }\n if (declaration.kind === 'const') {\n bindings.set(variable, { kind: 'const', expression: declarator.init ?? null });\n } else {\n bindings.set(variable, {\n kind: 'mutable',\n declarationKind: declaration.kind,\n });\n }\n }\n}\n\nfunction markReassignedTopLevelBindings(\n ast: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n walkAst(\n ast,\n { scopeAnalysis, bindings },\n {\n AssignmentExpression(node, { state }) {\n markAssignedPattern(node.left, state.scopeAnalysis, state.bindings);\n },\n UpdateExpression(node, { state }) {\n markAssignedPattern(node.argument, state.scopeAnalysis, state.bindings);\n },\n UnaryExpression(node, { state }) {\n if (node.operator === 'delete') {\n markAssignedPattern(node.argument, state.scopeAnalysis, state.bindings);\n }\n },\n ForInStatement(node, { state }) {\n markForIterationTarget(node.left, state.scopeAnalysis, state.bindings);\n },\n ForOfStatement(node, { state }) {\n markForIterationTarget(node.left, state.scopeAnalysis, state.bindings);\n },\n },\n );\n}\n\nfunction markForIterationTarget(\n left: Pattern | VariableDeclaration,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (left.type !== 'VariableDeclaration') {\n markAssignedPattern(left, scopeAnalysis, bindings);\n }\n}\n\nfunction markAssignedPattern(\n pattern: Pattern | Expression,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n): void {\n if (pattern.type === 'Identifier') {\n markAssignedVariable(pattern, scopeAnalysis, bindings, 'reassigned binding');\n return;\n }\n\n if (pattern.type === 'MemberExpression') {\n const root = getMemberExpressionRoot(pattern);\n if (root) {\n markAssignedVariable(root, scopeAnalysis, bindings, 'mutated object binding');\n }\n return;\n }\n\n if (pattern.type === 'ObjectPattern') {\n for (const property of pattern.properties) {\n markAssignedPattern(\n property.type === 'RestElement' ? property.argument : property.value,\n scopeAnalysis,\n bindings,\n );\n }\n return;\n }\n\n if (pattern.type === 'ArrayPattern') {\n for (const element of pattern.elements) {\n if (element) {\n markAssignedPattern(element, scopeAnalysis, bindings);\n }\n }\n return;\n }\n\n if (pattern.type === 'RestElement') {\n markAssignedPattern(pattern.argument, scopeAnalysis, bindings);\n return;\n }\n\n if (pattern.type === 'AssignmentPattern') {\n markAssignedPattern(pattern.left, scopeAnalysis, bindings);\n }\n}\n\nfunction markAssignedVariable(\n identifier: Identifier,\n scopeAnalysis: ModuleScopeAnalysis,\n bindings: Map<eslintScope.Variable, StaticBinding>,\n reason: string,\n): void {\n const variable = resolveIdentifier(identifier, scopeAnalysis);\n if (!variable || isImportVariable(variable) || !bindings.has(variable)) {\n return;\n }\n\n const binding = bindings.get(variable);\n if (binding?.kind === 'mutable') {\n return;\n }\n bindings.set(variable, { kind: 'unsupported', reason });\n}\n\nfunction getMemberExpressionRoot(node: Expression | Super): Identifier | undefined {\n if (node.type === 'Identifier') {\n return node;\n }\n if (node.type === 'MemberExpression') {\n return getMemberExpressionRoot(node.object);\n }\n return undefined;\n}\n\nfunction getModuleExportName(node: ModuleExportName): string {\n if (node.type === 'Identifier') {\n return node.name;\n }\n return String(node.value);\n}\n\nfunction getExportAllExportedName(node: ExportAllDeclaration): string | undefined {\n const exported = (node as ExportAllDeclaration & { exported?: ModuleExportName | null })\n .exported;\n return exported ? getModuleExportName(exported) : undefined;\n}\n\nfunction getResolvedSource(staticDependencies: StaticModuleDependency[], source: string): string {\n return (\n staticDependencies.find((dependency) => dependency.source === source)?.resolvedId ?? source\n );\n}\n\n/**\n * Finds dependency forms that cannot be represented by the static dependency\n * IDs supplied by the backend build collector.\n */\nfunction collectUnsupportedModuleDependencies(ast: Program): ModuleDependency[] {\n const dependencies: ModuleDependency[] = [];\n\n walkAst(ast, dependencies, {\n ImportExpression(node, { state }) {\n const specifier = getImportExpressionSpecifier(node);\n if (shouldFailDynamicImport(specifier)) {\n state.push({ specifier, kind: 'dynamic-import' });\n }\n },\n CallExpression(node, { state }) {\n if (isImportCallExpression(node)) {\n const specifier = getImportCallSpecifier(node);\n if (shouldFailDynamicImport(specifier)) {\n state.push({ specifier, kind: 'dynamic-import' });\n }\n return;\n }\n\n if (isLocalRequireCall(node)) {\n state.push({\n specifier: getRequireSpecifier(node),\n kind: 'require',\n });\n }\n },\n });\n\n return dependencies;\n}\n\n/**\n * Dynamic package imports are skipped, but local or non-literal dynamic imports\n * could hide app-local action-catalog calls and must fail closed.\n */\nfunction shouldFailDynamicImport(specifier: string): boolean {\n return specifier === 'non-literal dynamic import' || isLocalSpecifier(specifier);\n}\n\n/**\n * Keeps reachability traversal scoped to app-local JavaScript/TypeScript source\n * modules that the backend build collector can safely analyze.\n */\nexport function shouldTraverseCollectedModule(moduleId: string, buildRoot: string): boolean {\n if (!BACKEND_CODE_EXTENSIONS.some((extension) => moduleId.endsWith(extension))) {\n return false;\n }\n\n const relativePath = path.relative(path.resolve(buildRoot), moduleId);\n if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n return false;\n }\n\n return !relativePath.split(path.sep).some((segment) => PACKAGE_MANAGER_DIRS.has(segment));\n}\n\n/**\n * Reads the static string specifier from an ESTree dynamic import expression.\n */\nfunction getImportExpressionSpecifier(node: ImportExpression): string {\n return getLiteralSpecifier(node.source, 'non-literal dynamic import');\n}\n\n/**\n * Reads the static string specifier from Rollup's call-expression form for\n * dynamic import.\n */\nfunction getImportCallSpecifier(node: ImportCallExpression): string {\n return getLiteralSpecifier(node.arguments[0], 'non-literal dynamic import');\n}\n\n/**\n * Reads the static string specifier from a CommonJS require call.\n */\nfunction getRequireSpecifier(node: SimpleCallExpression): string {\n return getLiteralSpecifier(node.arguments[0], 'local require');\n}\n\n/**\n * Returns a literal string value when available, otherwise a diagnostic label\n * used in fail-closed error messages.\n */\nfunction getLiteralSpecifier(node: unknown, fallback: string): string {\n if (isStringLiteral(node)) {\n return node.value;\n }\n return fallback;\n}\n\n/**\n * Narrows Rollup's dynamic import call-expression representation.\n */\nfunction isImportCallExpression(node: SimpleCallExpression): node is ImportCallExpression {\n return (node.callee as { type: string }).type === 'Import';\n}\n\n/**\n * Detects local CommonJS require calls. Package require calls are ignored\n * because package modules are outside the app-local backend graph.\n */\nfunction isLocalRequireCall(node: SimpleCallExpression): boolean {\n if (node.callee.type !== 'Identifier' || node.callee.name !== 'require') {\n return false;\n }\n const [source] = node.arguments;\n return !source || !isStringLiteral(source) || isLocalSpecifier(source.value);\n}\n\n/**\n * Returns whether an import specifier points at an app-local path.\n */\nfunction isLocalSpecifier(specifier: string): boolean {\n return specifier.startsWith('.') || specifier.startsWith('/');\n}\n\n/**\n * Builds the common fail-closed error for graph shapes that could hide an\n * action-catalog connection ID.\n */\nexport function unsupportedModuleGraphDependency(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported local module graph for ${filePath}: ${unsupported} could hide an action-catalog connectionId.`,\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 { Expression, ObjectExpression, Property, SimpleCallExpression } from 'estree';\n\nimport {\n analyzeActionCatalogScopes,\n findActionCatalogCallSites,\n} from './action-catalog-call-sites';\nimport { collectActionCatalogImports } from './action-catalog-imports';\nimport type { ParsedModuleRecord } from './module-graph';\nimport { resolveStaticStringValue } from './static-string-resolution';\nimport { walkModuleGraph } from './walk-module-graph';\n\nconst CONNECTION_ID_PROPERTY = 'connectionId';\n\ntype ConnectionIdProperty = Property & { value: Expression };\n\n/**\n * Extracts the conservative backend-file connection ID union from module records\n * collected while the backend bundler walked the real execution graph.\n */\nexport function extractConnectionIdsFromModuleGraph(\n entryId: string,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n buildRoot: string,\n): string[] {\n const connectionIds = new Set<string>();\n\n // Walk the already-parsed records from this backend entry's build. The\n // extraction cost is linear in reachable app-local modules, without\n // reparsing source files here.\n walkModuleGraph(entryId, modules, buildRoot, ({ record }) => {\n const imports = collectActionCatalogImports(record.ast);\n const scopeAnalysis = analyzeActionCatalogScopes(record.scopeAnalysis, imports);\n\n for (const callSite of findActionCatalogCallSites(record.ast, scopeAnalysis, record.id)) {\n const connectionId = extractConnectionIdFromActionCall(callSite, modules, record);\n // `''` is a valid declared connectionId, not \"none\" — only the absence of a\n // `connectionId` property (`undefined`) means no restriction to record.\n if (connectionId !== undefined) {\n connectionIds.add(connectionId);\n }\n }\n });\n\n return [...connectionIds].sort();\n}\n\nfunction extractConnectionIdFromActionCall(\n node: SimpleCallExpression,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n record: ParsedModuleRecord,\n): string | undefined {\n const [firstArg] = node.arguments;\n if (!firstArg || firstArg.type !== 'ObjectExpression') {\n throw unsupportedActionCatalogCall(record.id, 'non-object action-catalog call arguments');\n }\n\n const connectionIdProperty = findConnectionIdProperty(firstArg, record.id);\n if (!connectionIdProperty) {\n return undefined;\n }\n\n const result = resolveStaticStringValue(modules, record.id, connectionIdProperty.value);\n if (result.kind === 'resolved') {\n return result.value;\n }\n\n throw unsupportedConnectionId(\n record.id,\n `static string resolution ${getStaticStringUnsupportedReason(result)}: ${result.message}`,\n );\n}\n\nfunction getStaticStringUnsupportedReason(\n result: Exclude<ReturnType<typeof resolveStaticStringValue>, { kind: 'resolved' }>,\n): string {\n if (result.reason === 'static-definition-unsupported') {\n return `${result.reason}/${result.definition.reason}`;\n }\n\n return result.reason;\n}\n\n/**\n * Finds the `connectionId` property in an action-catalog call's options object.\n *\n * This rejects spreads, computed keys, duplicate `connectionId` keys, and\n * accessor properties because those shapes can hide or change the actual value.\n */\nfunction findConnectionIdProperty(\n objectExpression: ObjectExpression,\n filePath: string,\n): ConnectionIdProperty | undefined {\n let connectionIdProperty: ConnectionIdProperty | undefined;\n for (const property of objectExpression.properties) {\n if (property.type === 'SpreadElement') {\n throw unsupportedActionCatalogCall(filePath, 'spread object arguments');\n }\n if (property.computed) {\n throw unsupportedActionCatalogCall(filePath, 'computed object property keys');\n }\n if (isConnectionIdKey(property)) {\n if (connectionIdProperty) {\n throw unsupportedActionCatalogCall(filePath, 'multiple connectionId properties');\n }\n if (property.kind !== 'init') {\n throw unsupportedActionCatalogCall(filePath, 'accessor connectionId properties');\n }\n if (!hasExpressionValue(property)) {\n throw unsupportedActionCatalogCall(\n filePath,\n 'destructuring pattern in connectionId value',\n );\n }\n connectionIdProperty = property;\n }\n }\n return connectionIdProperty;\n}\n\nfunction hasExpressionValue(property: Property): property is ConnectionIdProperty {\n const { value } = property;\n return (\n value.type !== 'ObjectPattern' &&\n value.type !== 'ArrayPattern' &&\n value.type !== 'RestElement' &&\n value.type !== 'AssignmentPattern'\n );\n}\n\nfunction isConnectionIdKey(property: Property): boolean {\n return getStaticPropertyKey(property) === CONNECTION_ID_PROPERTY;\n}\n\nfunction getStaticPropertyKey(property: Property): string | undefined {\n if (property.key.type === 'Identifier') {\n return property.key.name;\n }\n if (property.key.type === 'Literal' && typeof property.key.value === 'string') {\n return property.key.value;\n }\n return undefined;\n}\n\nfunction unsupportedActionCatalogCall(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported action-catalog call in ${filePath}: ${unsupported} could hide a connectionId.`,\n );\n}\n\nfunction unsupportedConnectionId(filePath: string, unsupported: string): Error {\n return new Error(`Unsupported action-catalog connectionId in ${filePath}: ${unsupported}.`);\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 type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n unsupportedModuleGraphDependency,\n} from './module-graph';\n\nexport interface ModuleGraphWalkContext {\n entryId: string;\n moduleId: string;\n record: ParsedModuleRecord;\n}\n\n/**\n * Walks every collected app-local module statically reachable from a backend\n * entry and applies fail-closed graph validation before following dependency\n * edges.\n */\nexport function walkModuleGraph(\n entryId: string,\n modules: ReadonlyMap<string, ParsedModuleRecord>,\n buildRoot: string,\n visit: (context: ModuleGraphWalkContext) => void,\n): void {\n // Traverse from the real backend entry, not the virtual wrapper used by\n // the backend build. Every backend export in this file receives this same\n // conservative file-level allowlist.\n const pending = [entryId];\n const visited = new Set<string>();\n\n while (pending.length > 0) {\n // Process each collected module at most once so local cycles cannot\n // loop forever.\n const moduleId = pending.shift()!;\n if (visited.has(moduleId)) {\n continue;\n }\n visited.add(moduleId);\n\n // A reachable local module that Rollup did not parse means the\n // collected graph is incomplete, so fail closed instead of silently\n // omitting a possible connection ID.\n const record = modules.get(moduleId);\n if (!record) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `missing module record for ${moduleId}`,\n );\n }\n\n visit({ entryId, moduleId, record });\n\n // Dynamic local imports and local require calls can hide reachable\n // action-catalog calls from static traversal. Treat them as unsupported\n // graph shapes for this PR.\n for (const dependency of record.unsupportedDependencies) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `${dependency.kind} ${dependency.specifier}`,\n );\n }\n\n // Follow only collected local source modules. Package imports, virtual\n // entries, generated files, and files outside buildRoot are ignored by\n // design because they are outside the app-local backend graph.\n for (const dependency of record.staticDependencies) {\n const dependencyId = dependency.resolvedId;\n if (!shouldTraverseCollectedModule(dependencyId, buildRoot)) {\n continue;\n }\n\n // A local dependency can be statically reachable but absent from\n // the collector if Rollup did not parse it. Fail closed rather than\n // trusting an incomplete allowlist.\n if (!modules.has(dependencyId)) {\n throw unsupportedModuleGraphDependency(\n entryId,\n `uncollected local import ${dependencyId} from ${record.id}`,\n );\n }\n\n pending.push(dependencyId);\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 { BaseNode, Expression } from 'estree';\nimport { builtinModules } from 'node:module';\n\nimport { ensureProgram, isTypeOnly, staticStringValue } from './type-guards';\nimport { walkAst } from './walk-ast';\n\nconst RESTRICTED_MODULES = new Set<string>(builtinModules);\n\nfunction isRestrictedSource(source: string): boolean {\n return source.startsWith('node:') || RESTRICTED_MODULES.has(source);\n}\n\n// A declaration with no specifiers still evaluates the module for its side effects, so only a specifier list that's entirely type-only is safe to skip.\nfunction hasRuntimeSpecifier(specifiers: readonly BaseNode[]): boolean {\n return specifiers.length === 0 || specifiers.some((specifier) => !isTypeOnly(specifier));\n}\n\n// Rejects static/dynamic imports of Node built-ins in `.backend.ts` files, which run in a restricted environment. Best-effort — doesn't catch `require()` or a runtime-computed specifier (see `rejectRestrictedGlobals` for bare network globals like `fetch`).\nexport function rejectNodeBuiltinImports(ast: BaseNode, filePath: string): void {\n const program = ensureProgram(ast, filePath);\n for (const node of program.body) {\n if (\n node.type === 'ImportDeclaration' &&\n !isTypeOnly(node) &&\n hasRuntimeSpecifier(node.specifiers)\n ) {\n rejectIfRestrictedSource(node.source, filePath);\n continue;\n }\n\n // A named re-export from a source loads the built-in module just like a regular import does.\n if (\n node.type === 'ExportNamedDeclaration' &&\n node.source &&\n !isTypeOnly(node) &&\n hasRuntimeSpecifier(node.specifiers)\n ) {\n rejectIfRestrictedSource(node.source, filePath);\n continue;\n }\n\n // `export * from` is its own Rollup node type, not an ExportNamedDeclaration, so it needs its own check.\n if (node.type === 'ExportAllDeclaration' && !isTypeOnly(node)) {\n rejectIfRestrictedSource(node.source, filePath);\n }\n }\n\n // A dynamic `import()` is an ImportExpression that can appear anywhere in the tree, not just program.body, so it needs its own walk.\n walkAst(program, null, {\n ImportExpression(node) {\n rejectIfRestrictedSource(node.source, filePath);\n },\n });\n}\n\nfunction rejectIfRestrictedSource(source: Expression, filePath: string): void {\n const value = staticStringValue(source);\n if (value === undefined || !isRestrictedSource(value)) {\n return;\n }\n\n throw new Error(\n `Importing Node built-in module \"${value}\" is not supported in backend function code. ` +\n `Backend functions run in a restricted environment: for networking, filesystem, or ` +\n `process access, use an Action Platform action ($.Actions or an @datadog/action-catalog ` +\n `typed wrapper) instead; for pure utility modules (e.g. path, url, util), use a ` +\n `runtime-independent package instead: ${filePath}`,\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 * as eslintScope from 'eslint-scope';\nimport type {\n Expression,\n MemberExpression,\n ObjectExpression,\n ObjectPattern,\n PrivateIdentifier,\n Program,\n Property,\n Super,\n VariableDeclarator,\n} from 'estree';\n\nimport { resolveIdentifier } from './module-scope';\nimport type { ModuleScopeAnalysis } from './module-scope';\nimport { isVariableDeclaratorNode, staticStringValue } from './type-guards';\nimport { walkAst } from './walk-ast';\n\nconst GLOBAL_THIS_NAME = 'globalThis';\nconst NODE_GLOBAL_ALIAS_NAME = 'global';\n\n// `global` is Node's own alias for the ambient global object.\nfunction isAmbientGlobalReceiverName(name: string): boolean {\n return name === GLOBAL_THIS_NAME || name === NODE_GLOBAL_ALIAS_NAME;\n}\n\n// Tracks a for-of loop's ambient-global binding (see the ForOfStatement visitor below) — a loop variable has no `.init` for resolvesToAmbientGlobal's normal alias-chain check to inspect. Reset per forEachAmbientGlobalAccess call.\nlet forOfAmbientAliases = new Set<eslintScope.Variable>();\n\n// Only an unresolved `globalThis`/`global` identifier or a chain of single-`const` aliases counts — a `let`, parameter, or other ambiguous binding is treated as opaque.\nfunction resolvesToAmbientGlobal(\n node: Expression | Super,\n scopeAnalysis: ModuleScopeAnalysis,\n visited: Set<eslintScope.Variable> = new Set(),\n): boolean {\n // `globalThis.globalThis`/`global.global` is a real self-reference — recurse through it before treating other receiver shapes as opaque.\n if (node.type === 'MemberExpression') {\n const propertyName = staticMemberName(node, scopeAnalysis);\n if (!propertyName || !isAmbientGlobalReceiverName(propertyName)) {\n return false;\n }\n return resolvesToAmbientGlobal(node.object, scopeAnalysis, visited);\n }\n\n if (node.type !== 'Identifier') {\n return false;\n }\n\n const variable = resolveIdentifier(node, scopeAnalysis);\n if (!variable) {\n return isAmbientGlobalReceiverName(node.name);\n }\n\n if (forOfAmbientAliases.has(variable)) {\n return true;\n }\n\n if (visited.has(variable) || variable.defs.length !== 1) {\n return false;\n }\n visited.add(variable);\n\n const [definition] = variable.defs;\n if (definition.type !== 'Variable' || definition.parent.kind !== 'const') {\n return false;\n }\n\n // `definition.node` is typed against eslint-scope's bundled (structurally identical) `estree` types — narrowed via a type guard rather than asserted.\n if (!isVariableDeclaratorNode(definition.node)) {\n return false;\n }\n const { id, init } = definition.node;\n if (!init) {\n return false;\n }\n\n if (id.type === 'Identifier') {\n return resolvesToAmbientGlobal(init, scopeAnalysis, visited);\n }\n // A destructure normally names a property of `y`, not `y` itself — unless every key on the\n // path down to this binding is a `globalThis`/`global` self-reference (`const { globalThis:\n // { globalThis: g } } = globalThis`), since `y.globalThis === y` holds at any depth of\n // repeated self-reference, not just one level.\n if (id.type === 'ObjectPattern') {\n const reachesSelfReference = (pattern: ObjectPattern): boolean =>\n pattern.properties.some((property) => {\n if (property.type !== 'Property') {\n return false;\n }\n const propertyName = staticPropertyName(property, scopeAnalysis) ?? '';\n if (!isAmbientGlobalReceiverName(propertyName)) {\n return false;\n }\n const value = unwrapDefaultValue(property.value);\n return (\n value === definition.name ||\n (value.type === 'ObjectPattern' && reachesSelfReference(value))\n );\n });\n if (reachesSelfReference(id)) {\n return resolvesToAmbientGlobal(init, scopeAnalysis, visited);\n }\n }\n\n return false;\n}\n\nfunction staticMemberName(\n node: MemberExpression,\n scopeAnalysis: ModuleScopeAnalysis,\n): string | undefined {\n if (!node.computed) {\n return node.property.type === 'Identifier' ? node.property.name : undefined;\n }\n return resolveStaticPropertyName(node.property, scopeAnalysis);\n}\n\n// A defaulted property value (`{ x = fallback }`) is an AssignmentPattern wrapping the real binding — unwrap it so a defaulted alias is treated the same as a bare one.\nfunction unwrapDefaultValue(value: Property['value']): Property['value'] {\n return value.type === 'AssignmentPattern' ? value.left : value;\n}\n\nfunction staticPropertyName(\n property: Property,\n scopeAnalysis: ModuleScopeAnalysis,\n): string | undefined {\n // A non-computed key can still be a quoted string literal (`{ 'fetch': f }`) — fall through to resolveStaticPropertyName for that shape.\n if (!property.computed && property.key.type === 'Identifier') {\n return property.key.name;\n }\n return resolveStaticPropertyName(property.key, scopeAnalysis);\n}\n\n// A computed key (`globalThis[f]`, `const { [key]: r } = globalThis`) is just as knowable as a\n// literal when it traces back to one through a chain of `const` aliases — the same reasoning\n// resolvesToAmbientGlobal applies to the object side of a member expression applies here to the\n// property side, since neither shape evaluates anything dynamic. `visited` is independent of\n// resolvesToAmbientGlobal's own set: it walks a different alias chain (the key's value, not the\n// receiver object), and guards the same way against a self-referential `const` cycle hanging the\n// linter instead of just failing to resolve.\nfunction resolveStaticPropertyName(\n node: Expression | PrivateIdentifier,\n scopeAnalysis: ModuleScopeAnalysis,\n visited: Set<eslintScope.Variable> = new Set(),\n): string | undefined {\n const direct = staticStringValue(node);\n if (direct !== undefined) {\n return direct;\n }\n if (node.type !== 'Identifier') {\n return undefined;\n }\n\n const variable = resolveIdentifier(node, scopeAnalysis);\n if (!variable || visited.has(variable) || variable.defs.length !== 1) {\n return undefined;\n }\n visited.add(variable);\n\n const [definition] = variable.defs;\n if (definition.type !== 'Variable' || definition.parent.kind !== 'const') {\n return undefined;\n }\n if (!isVariableDeclaratorNode(definition.node)) {\n return undefined;\n }\n const { id, init } = definition.node;\n if (id.type !== 'Identifier' || !init) {\n return undefined;\n }\n return resolveStaticPropertyName(init, scopeAnalysis, visited);\n}\n\n// A for-of binding identifier is a declaration site, not a reference, so `resolveIdentifier` (which only resolves references) can't find it — look it up via eslint-scope's declarator-to-Variable index instead.\nfunction findDeclaredVariable(\n declarator: VariableDeclarator,\n scopeAnalysis: ModuleScopeAnalysis,\n): eslintScope.Variable | undefined {\n return scopeAnalysis.scopeManager.getDeclaredVariables(declarator)[0];\n}\n\n// Standard-library statics that reify every property VALUE of their argument at once (see the CallExpression visitor below). `Object.keys`/`Reflect.ownKeys` are excluded since they return only name strings, not values. Matched by identifier name only — a locally-shadowed `Object`/`Reflect` is an accepted gap.\nconst BULK_COPY_CALLS: ReadonlyArray<{ readonly object: string; readonly property: string }> = [\n { object: 'Object', property: 'assign' },\n { object: 'Object', property: 'values' },\n { object: 'Object', property: 'entries' },\n { object: 'Object', property: 'getOwnPropertyDescriptors' },\n];\n\nfunction matchBulkCopyCall(\n callee: Expression | Super,\n scopeAnalysis: ModuleScopeAnalysis,\n): { readonly object: string; readonly property: string } | undefined {\n if (callee.type !== 'MemberExpression' || callee.object.type !== 'Identifier') {\n return undefined;\n }\n // staticMemberName already handles both a plain identifier property (`.assign`) and a\n // computed access resolving to a static string (`[\"assign\"]`) — reusing it here (instead of\n // requiring callee.property.type === 'Identifier') closes a gap where `Object[\"assign\"](...)`\n // evaded detection entirely.\n const propertyName = staticMemberName(callee, scopeAnalysis);\n if (!propertyName) {\n return undefined;\n }\n const objectName = callee.object.name;\n return BULK_COPY_CALLS.find(\n (candidate) => candidate.object === objectName && candidate.property === propertyName,\n );\n}\n\nexport interface AmbientGlobalAccessHandlers {\n /** A specific restricted/divergent name was reached by name. */\n onNamedAccess(name: string): void;\n /** Every ambient global was copied at once (a rest destructure, an object spread, or a bulk-copy call like `Object.assign`/`Object.values`), with no specific name to report. */\n onBulkCopy(): void;\n}\n\n// Walks every syntactic form that can reach the ambient global object and reports matching names; shared by `rejectRestrictedGlobals` and `warnAboutDivergentGlobals`.\nexport function forEachAmbientGlobalAccess(\n program: Program,\n scopeAnalysis: ModuleScopeAnalysis,\n names: ReadonlySet<string>,\n handlers: AmbientGlobalAccessHandlers,\n): void {\n forOfAmbientAliases = new Set();\n\n for (const [identifier, reference] of scopeAnalysis.referencesByIdentifier) {\n if (!names.has(identifier.name) || reference.resolved) {\n continue;\n }\n handlers.onNamedAccess(identifier.name);\n }\n\n // Shared by both `const { x } = globalThis`-style destructures and a for-of loop's inline destructure below — the per-property checking is identical once the source is known to be the ambient global.\n const checkDestructuredPattern = (pattern: ObjectPattern) => {\n for (const property of pattern.properties) {\n if (property.type === 'RestElement') {\n handlers.onBulkCopy();\n continue;\n }\n const name = staticPropertyName(property, scopeAnalysis);\n if (name && names.has(name)) {\n handlers.onNamedAccess(name);\n }\n // `const { globalThis: { fetch } } = globalThis` is a real self-reference, so recurse the same way resolvesToAmbientGlobal's MemberExpression case does — otherwise a name nested inside a `globalThis`/`global` key escapes detection.\n const nestedPattern = unwrapDefaultValue(property.value);\n if (\n name &&\n isAmbientGlobalReceiverName(name) &&\n nestedPattern.type === 'ObjectPattern'\n ) {\n checkDestructuredPattern(nestedPattern);\n }\n }\n };\n\n const checkDestructure = (pattern: ObjectPattern, init: Expression | null | undefined) => {\n if (!init || !resolvesToAmbientGlobal(init, scopeAnalysis)) {\n return;\n }\n checkDestructuredPattern(pattern);\n };\n\n walkAst(program, null, {\n MemberExpression(node) {\n if (!resolvesToAmbientGlobal(node.object, scopeAnalysis)) {\n return;\n }\n const name = staticMemberName(node, scopeAnalysis);\n if (name && names.has(name)) {\n handlers.onNamedAccess(name);\n }\n },\n VariableDeclarator(node) {\n if (node.id.type === 'ObjectPattern') {\n checkDestructure(node.id, node.init);\n }\n },\n AssignmentExpression(node) {\n if (node.left.type === 'ObjectPattern') {\n checkDestructure(node.left, node.right);\n }\n },\n // A destructuring default value (`function run({ fetch } = globalThis)`) is an AssignmentPattern, unreached by the visitors above.\n AssignmentPattern(node) {\n if (node.left.type === 'ObjectPattern') {\n checkDestructure(node.left, node.right);\n }\n },\n // A for-of binding has no `.init` for the normal alias-chain check to read, so it needs its own handling — scoped to an inline array literal in the loop head, not full data-flow through an intermediate variable. ArrayPattern bindings (`for (const [x] of ...)`) aren't handled, same opacity tier as other unhandled cases.\n ForOfStatement(node) {\n if (node.right.type !== 'ArrayExpression') {\n return;\n }\n\n let bindingPattern: ObjectPattern | undefined;\n let bindingIdentifierVariable: eslintScope.Variable | undefined;\n\n if (node.left.type === 'VariableDeclaration') {\n if (node.left.declarations.length !== 1) {\n return;\n }\n const [declarator] = node.left.declarations;\n if (declarator.id.type === 'ObjectPattern') {\n bindingPattern = declarator.id;\n } else if (declarator.id.type === 'Identifier' && node.left.kind === 'const') {\n bindingIdentifierVariable = findDeclaredVariable(declarator, scopeAnalysis);\n } else {\n // A `let` binding can be reassigned in the loop body, so unlike the ObjectPattern\n // case above it isn't provably still the ambient global — same opacity rule as a\n // `let` alias chain.\n return;\n }\n } else if (node.left.type === 'ObjectPattern') {\n bindingPattern = node.left;\n } else {\n // A bare-identifier target (`for (x of ...)`) always reuses an existing, reassignable\n // binding — never provably const — so it's opaque too.\n return;\n }\n\n const hasAmbientElement = node.right.elements.some(\n (element) =>\n element !== null &&\n element.type !== 'SpreadElement' &&\n resolvesToAmbientGlobal(element, scopeAnalysis),\n );\n if (!hasAmbientElement) {\n return;\n }\n\n if (bindingPattern) {\n checkDestructuredPattern(bindingPattern);\n } else if (bindingIdentifierVariable) {\n forOfAmbientAliases.add(bindingIdentifierVariable);\n }\n },\n // Mirrors a rest-destructure — `{ ...globalThis }` copies every ambient global just as `const { ...x } = globalThis` does.\n ObjectExpression(node: ObjectExpression) {\n for (const property of node.properties) {\n if (\n property.type === 'SpreadElement' &&\n resolvesToAmbientGlobal(property.argument, scopeAnalysis)\n ) {\n handlers.onBulkCopy();\n }\n }\n },\n // Built-in statics like `Object.assign({}, globalThis)` reify every property at once — the same threat as a rest-destructure or spread, but with no named-property access for the visitors above to see. Scoped to this known list, not a user-defined equivalent or an aliased `Object`/`Reflect`.\n CallExpression(node) {\n const match = matchBulkCopyCall(node.callee, scopeAnalysis);\n if (!match) {\n return;\n }\n // Object.assign's first argument is the write target, not a source — checking it would\n // reject harmless calls like Object.assign(globalThis, { marker: true }).\n const sourceArguments =\n match.property === 'assign' ? node.arguments.slice(1) : node.arguments;\n const hasAmbientArgument = sourceArguments.some(\n (arg) =>\n arg.type !== 'SpreadElement' && resolvesToAmbientGlobal(arg, scopeAnalysis),\n );\n if (hasAmbientArgument) {\n handlers.onBulkCopy();\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 { BaseNode } from 'estree';\n\nimport { forEachAmbientGlobalAccess } from './ambient-global-access';\nimport { analyzeModuleScope } from './module-scope';\nimport type { ModuleScopeAnalysis } from './module-scope';\nimport { ensureProgram } from './type-guards';\n\nconst RESTRICTED_GLOBALS = new Set(['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource']);\n\n// Rejects network-capable globals (fetch, etc.) in `.backend.ts` files — backend functions have no raw network access in production and must go through an Action Platform action instead. Only pre-v2 (legacy) apps need this; the planned Terrapin-based v2 sandbox lifts the restriction.\nexport function rejectRestrictedGlobals(\n ast: BaseNode,\n filePath: string,\n precomputedScopeAnalysis?: ModuleScopeAnalysis,\n): void {\n const program = ensureProgram(ast, filePath);\n const scopeAnalysis = precomputedScopeAnalysis ?? analyzeModuleScope(program);\n\n forEachAmbientGlobalAccess(program, scopeAnalysis, RESTRICTED_GLOBALS, {\n onNamedAccess(name) {\n throwRestrictedGlobalError(name, filePath);\n },\n onBulkCopy() {\n throw new Error(\n `Copying every property of \"globalThis\"/\"global\" at once (a rest destructure, ` +\n `an object spread, or a call like Object.assign/Object.values) is not ` +\n `supported in backend function code — it copies every ambient global, ` +\n `including network-capable ones (${Array.from(RESTRICTED_GLOBALS).join(', ')}), ` +\n `into a plain object: ${filePath}`,\n );\n },\n });\n}\n\nfunction throwRestrictedGlobalError(name: string, filePath: string): never {\n throw new Error(\n `Using \"${name}\" is not supported in backend function code. ` +\n `Backend functions cannot make raw network requests in production — ` +\n `use an Action Platform action ($.Actions or an @datadog/action-catalog ` +\n `typed wrapper) instead: ${filePath}`,\n );\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport type { BaseNode } from 'estree';\n\nimport { forEachAmbientGlobalAccess } from './ambient-global-access';\nimport { analyzeModuleScope } from './module-scope';\nimport type { ModuleScopeAnalysis } from './module-scope';\nimport { ensureProgram } from './type-guards';\n\nconst DIVERGENT_GLOBALS = new Set(['crypto', 'Intl']);\n\n// Cross-call cache since the same backend entry file is transformed multiple times per build; bounded and cleared wholesale once too large, trading an occasional re-warn for capped memory in long dev-server sessions.\nconst MAX_TRACKED_FILES = 500;\nconst warnedGlobalsByFile = new Map<string, Set<string>>();\n\n// Test-only escape hatch: clears the cross-call dedup cache between test cases that reuse the same file path.\nexport function resetDivergentGlobalWarnings(): void {\n warnedGlobalsByFile.clear();\n}\n\n// Warns (never rejects) on `crypto`/`Intl` references in `.backend.ts` files, since their behavior can differ between local Node and production Deno. Editor-time guidance only — `npm run dev:verify`'s real cloud round trip is the actual parity gate.\nexport function warnAboutDivergentGlobals(\n ast: BaseNode,\n filePath: string,\n log: Logger,\n precomputedScopeAnalysis?: ModuleScopeAnalysis,\n): void {\n const program = ensureProgram(ast, filePath);\n const scopeAnalysis = precomputedScopeAnalysis ?? analyzeModuleScope(program);\n\n let warned = warnedGlobalsByFile.get(filePath);\n if (!warned) {\n if (warnedGlobalsByFile.size >= MAX_TRACKED_FILES) {\n warnedGlobalsByFile.clear();\n }\n warned = new Set<string>();\n warnedGlobalsByFile.set(filePath, warned);\n }\n\n const warnOnce = (name: string) => {\n if (warned.has(name)) {\n return;\n }\n warned.add(name);\n warnDivergentGlobal(name, filePath, log);\n };\n\n forEachAmbientGlobalAccess(program, scopeAnalysis, DIVERGENT_GLOBALS, {\n onNamedAccess: warnOnce,\n onBulkCopy() {\n // No specific property to point at, so warn about every divergent global rather than staying silent.\n for (const name of DIVERGENT_GLOBALS) {\n warnOnce(name);\n }\n },\n });\n}\n\nfunction warnDivergentGlobal(name: string, filePath: string, log: Logger): void {\n log.warn(\n `\"${name}\" is used in ${filePath}. Its exact behavior can differ between local ` +\n `execution (Node) and production (Deno) — verify locale-/implementation-sensitive ` +\n `results with \"npm run dev:verify\" before publishing.`,\n );\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport type { BaseNode } from 'estree';\n\nimport type { ModuleScopeAnalysis } from './module-scope';\nimport { rejectNodeBuiltinImports } from './reject-node-builtin-imports';\nimport { rejectRestrictedGlobals } from './reject-restricted-globals';\nimport { warnAboutDivergentGlobals } from './warn-divergent-globals';\n\n/** Runs every static check (banned Node built-ins, restricted globals, divergent-global warnings) against a single module; shared by index.ts and backend-static-checks-plugin.ts so the two call sites can't drift. */\nexport function runBackendStaticChecks(\n ast: BaseNode,\n filePath: string,\n log: Logger,\n scopeAnalysis: ModuleScopeAnalysis,\n): void {\n rejectNodeBuiltinImports(ast, filePath);\n rejectRestrictedGlobals(ast, filePath, scopeAnalysis);\n warnAboutDivergentGlobals(ast, filePath, log, scopeAnalysis);\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 { createHash } from 'crypto';\nimport path from 'path';\n\nimport type { BackendFunction } from './types';\n\n/**\n * Encode a BackendFunction into an opaque query name string.\n * Uses the full SHA-256 hash of the path so that backend file structure\n * is never leaked into frontend assets.\n *\n * This is the single source of truth for query name encoding — used by\n * proxy codegen, the production build, and the dev server.\n */\nexport function encodeQueryName(ref: Pick<BackendFunction, 'relativePath' | 'name'>): string {\n // Normalize to forward slashes so the hash is consistent across platforms.\n const posixPath = ref.relativePath.split(path.sep).join('/');\n const pathHash = createHash('sha256').update(posixPath).digest('hex');\n return `${pathHash}.${ref.name}`;\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\ninterface ProxyExport {\n /** The JS export name (e.g. \"add\") */\n exportName: string;\n /** The pre-computed opaque query name (e.g. \"a1b2c3d4e5f6.add\") */\n queryName: string;\n}\n\n/**\n * Generate a proxy module for a `.backend.ts` file. Each exported function\n * is replaced with a wrapper that calls `executeBackendFunction` from the\n * runtime exposed on `globalThis.DD_APPS_RUNTIME` by the apps plugin's\n * injection (see packages/plugins/apps/src/built/apps-runtime.ts).\n *\n * The raw backend file path is never present in the generated code — only\n * the hashed query name appears, preventing backend file structure from\n * leaking into frontend bundles.\n *\n * @param exports - The export name + pre-computed query name for each export\n * @returns Generated proxy module source code\n */\nexport function generateProxyModule(exports: ProxyExport[]): string {\n const lines: string[] = [];\n\n for (const { exportName, queryName } of exports) {\n lines.push(`export async function ${exportName}(...args) {`);\n lines.push(\n ` return globalThis.DD_APPS_RUNTIME.executeBackendFunction(${JSON.stringify(queryName)}, args);`,\n );\n lines.push('}');\n lines.push('');\n }\n\n return lines.join('\\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\nfunction isPackageExportInstalled(packageExport: string, fromDir: string): boolean {\n try {\n require.resolve(packageExport, { paths: [fromDir] });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if @datadog/action-catalog is installed using Node's module resolution.\n * Resolves from the given directory so the check works even when the plugin\n * itself is loaded from a different location (e.g. linked).\n */\nexport function isActionCatalogInstalled(fromDir: string): boolean {\n return isPackageExportInstalled('@datadog/action-catalog/action-execution', fromDir);\n}\n\n/** Check if the @datadog/apps-backend \"JS Function with Actions\" runtime factory is installed. */\nexport function isDatadogAppsBackendInstalled(fromDir: string): boolean {\n return isPackageExportInstalled('@datadog/apps-backend/runtime/jsFunctionWithActions', fromDir);\n}\n\n/** The import line to pull action-catalog's setExecuteActionImplementation into bundles. */\nexport const ACTION_CATALOG_IMPORT =\n \"import { setExecuteActionImplementation } from '@datadog/action-catalog/action-execution';\";\n\n/** The import line that exposes @datadog/apps-backend backend context initialization. */\nexport const DATADOG_APPS_BACKEND_IMPORT = `\\\nimport { buildRuntimeFromJsFunctionWithActions } from '@datadog/apps-backend/runtime/jsFunctionWithActions';\nimport { setBackend } from '@datadog/apps-backend/runtime';`;\n\n/** Script snippet that supplies the backend runtime context to @datadog/apps. */\nexport const SET_BACKEND_CONTEXT_SNIPPET = `\\\n if (typeof buildRuntimeFromJsFunctionWithActions === 'function' && typeof setBackend === 'function') {\n setBackend(buildRuntimeFromJsFunctionWithActions($));\n }`;\n\n/** Script snippet that registers the $.Actions-based executeAction implementation at runtime. */\nexport const SET_EXECUTE_ACTION_SNIPPET = `\\\n if (typeof setExecuteActionImplementation === 'function') {\n setExecuteActionImplementation(async (actionId, request) => {\n const actionPath = actionId.replace(/^com\\\\.datadoghq\\\\./, '');\n const pathParts = actionPath.split('.');\n let actionFn = $.Actions;\n for (const part of pathParts) {\n if (!actionFn) throw new Error('Action not found: ' + actionId);\n actionFn = actionFn[part];\n }\n if (typeof actionFn !== 'function') throw new Error('Action is not a function: ' + actionId);\n return actionFn(request);\n });\n }`;\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 ACTION_CATALOG_IMPORT,\n DATADOG_APPS_BACKEND_IMPORT,\n SET_BACKEND_CONTEXT_SNIPPET,\n SET_EXECUTE_ACTION_SNIPPET,\n isActionCatalogInstalled,\n isDatadogAppsBackendInstalled,\n} from './shared';\n\n/**\n * Generate the virtual entry source for a backend function.\n * The host bundler resolves imports, so no export-stripping is needed.\n */\nexport function generateVirtualEntryContent(\n functionName: string,\n entryPath: string,\n projectRoot: string,\n): string {\n const lines: string[] = [];\n const hasDatadogAppsBackendRuntime = isDatadogAppsBackendInstalled(projectRoot);\n\n lines.push(`import { ${functionName} } from ${JSON.stringify(entryPath)};`);\n\n if (hasDatadogAppsBackendRuntime) {\n lines.push(DATADOG_APPS_BACKEND_IMPORT);\n }\n\n if (isActionCatalogInstalled(projectRoot)) {\n lines.push(ACTION_CATALOG_IMPORT);\n }\n\n lines.push('');\n lines.push('/** @param {import(\"./context.types\").Context} $ */');\n lines.push('export async function main($) {');\n lines.push(' globalThis.$ = $;');\n lines.push('');\n if (hasDatadogAppsBackendRuntime) {\n lines.push(' // Supply the backend runtime context');\n lines.push(SET_BACKEND_CONTEXT_SNIPPET);\n lines.push('');\n }\n lines.push(` // Register the $.Actions-based implementation for executeAction`);\n lines.push(SET_EXECUTE_ACTION_SNIPPET);\n lines.push('');\n lines.push(' const args = $.backendFunctionArgs ?? [];');\n lines.push(` const result = await ${functionName}(...args);`);\n lines.push(' return result;');\n lines.push('}');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the virtual entry source for a backend function (dev server).\n * Identical to production: args are read from $.backendFunctionArgs at runtime.\n */\nexport function generateDevVirtualEntryContent(\n functionName: string,\n entryPath: string,\n projectRoot?: string,\n): string {\n return generateVirtualEntryContent(functionName, entryPath, projectRoot ?? process.cwd());\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 { ModuleInfo } from 'rollup';\nimport type { Plugin } from 'vite';\n\nimport {\n createParsedModuleRecord,\n type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n unsupportedModuleGraphDependency,\n} from '../backend/ast-parsing/module-graph';\n\nconst VIRTUAL_MODULE_ID_RE = /^(?:\\0|virtual:)/;\n\nexport interface BackendModuleGraphCollector {\n plugin: Plugin;\n getModuleRecords: () => ReadonlyMap<string, ParsedModuleRecord>;\n}\n\nexport function createBackendModuleGraphCollector(buildRoot: string): BackendModuleGraphCollector {\n const records = new Map<string, ParsedModuleRecord>();\n\n return {\n plugin: {\n name: 'dd-backend-module-graph-collector',\n moduleParsed(moduleInfo: ModuleInfo) {\n const moduleId = normalizeViteModuleId(moduleInfo.id);\n if (isViteVirtualModuleId(moduleId)) {\n return;\n }\n\n // `createParsedModuleRecord` applies this same predicate, but\n // only after the AST exists. Checking it here keeps us from\n // parsing every `node_modules` module just to discard it.\n if (!shouldTraverseCollectedModule(moduleId, buildRoot)) {\n return;\n }\n\n // External and synthetic modules have no source to parse.\n if (typeof moduleInfo.code !== 'string') {\n return;\n }\n\n // Parse the source instead of reading `moduleInfo.ast`: Rolldown,\n // the bundler Vite 8 uses by default, stubs that getter to throw\n // `UNSUPPORTED: ModuleInfo#ast`.\n //\n // No TypeScript-capable parser is needed because `moduleParsed`\n // runs after `transform`, so types and JSX are already compiled\n // away. Note that `this.parse` is the bundler's parser but not\n // its parser *configuration* — Rollup binds no options to it,\n // while its own module parse passes `{ jsx }`. Our nested build\n // never enables `jsx`, so the two agree today; fail closed rather\n // than silently if they ever diverge, since a module we cannot\n // parse may hide a connection ID.\n let parsed;\n try {\n parsed = this.parse(moduleInfo.code);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw unsupportedModuleGraphDependency(\n moduleId,\n `unparseable module source (${reason})`,\n );\n }\n\n const record = createParsedModuleRecord(\n moduleId,\n buildRoot,\n parsed,\n getStaticDependencyIds(moduleInfo).map(normalizeViteModuleId),\n );\n // Only null when the traversal predicate rejects, which the guard\n // above already covered; kept to narrow the nullable return type.\n if (!record) {\n return;\n }\n\n records.set(record.id, record);\n },\n },\n getModuleRecords() {\n return records;\n },\n };\n}\n\nexport function normalizeViteModuleId(id: string): string {\n return id.split('?')[0];\n}\n\nfunction getStaticDependencyIds(moduleInfo: ModuleInfo): string[] {\n return moduleInfo.importedIdResolutions?.map(({ id }) => id) ?? [...moduleInfo.importedIds];\n}\n\nexport function isViteVirtualModuleId(id: string): boolean {\n return VIRTUAL_MODULE_ID_RE.test(id);\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 { Plugin } from 'vite';\n\nimport { extractConnectionIdsFromModuleGraph } from '../backend/ast-parsing/extract-connection-ids-from-module-graph';\nimport type { ParsedModuleRecord } from '../backend/ast-parsing/module-graph';\n\nimport { createBackendModuleGraphCollector } from './backend-module-graph-collector';\n\nexport interface BackendConnectionIdCollector {\n plugin: Plugin;\n getAllowedConnectionIds: () => string[];\n /** Exposed so a plugin sharing this build (e.g. the static-checks plugin) can reuse these records instead of re-parsing every module. */\n getModuleRecords: () => ReadonlyMap<string, ParsedModuleRecord>;\n}\n\nexport function createBackendConnectionIdCollector(\n entryId: string,\n buildRoot: string,\n): BackendConnectionIdCollector {\n const moduleGraphCollector = createBackendModuleGraphCollector(buildRoot);\n\n return {\n plugin: moduleGraphCollector.plugin,\n getAllowedConnectionIds() {\n return extractConnectionIdsFromModuleGraph(\n entryId,\n moduleGraphCollector.getModuleRecords(),\n buildRoot,\n );\n },\n getModuleRecords: moduleGraphCollector.getModuleRecords,\n };\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\nimport type { BaseNode } from 'estree';\nimport type { ModuleInfo } from 'rollup';\nimport type { Plugin } from 'vite';\n\nimport {\n type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n} from '../backend/ast-parsing/module-graph';\nimport { analyzeModuleScope } from '../backend/ast-parsing/module-scope';\nimport { runBackendStaticChecks } from '../backend/ast-parsing/run-backend-static-checks';\nimport { ensureProgram } from '../backend/ast-parsing/type-guards';\n\nimport { isViteVirtualModuleId, normalizeViteModuleId } from './backend-module-graph-collector';\n\n// Distinct from module-graph.ts's `unsupportedModuleGraphDependency` — that message is specific to connection-ID collection, unrelated to this plugin's fallback parse.\nfunction unsupportedStaticChecksSource(filePath: string, unsupported: string): Error {\n return new Error(\n `Unsupported module source for ${filePath}: ${unsupported} could hide a Node-builtin import or restricted-global access.`,\n );\n}\n\n// Re-runs the static checks against every app-local module the nested backend build resolves, not just the `.backend.ts` entry, so an imported helper module is also checked. MUST be registered after the connection-ID collector's plugin so `getModuleRecords` is populated (falls back to a local parse if a module is missing from it).\nexport function createBackendStaticChecksPlugin(\n buildRoot: string,\n log: Logger,\n getModuleRecords: () => ReadonlyMap<string, ParsedModuleRecord>,\n): Plugin {\n return {\n name: 'dd-backend-static-checks',\n moduleParsed(moduleInfo: ModuleInfo) {\n const moduleId = normalizeViteModuleId(moduleInfo.id);\n if (\n isViteVirtualModuleId(moduleId) ||\n !shouldTraverseCollectedModule(moduleId, buildRoot)\n ) {\n return;\n }\n\n const existingRecord = getModuleRecords().get(moduleId);\n let ast: BaseNode;\n let scopeAnalysis: ReturnType<typeof analyzeModuleScope>;\n\n if (existingRecord) {\n ast = existingRecord.ast;\n scopeAnalysis = existingRecord.scopeAnalysis;\n } else {\n if (typeof moduleInfo.code !== 'string') {\n return;\n }\n try {\n ast = this.parse(moduleInfo.code);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw unsupportedStaticChecksSource(\n moduleId,\n `unparseable module source (${reason})`,\n );\n }\n // Shared so the checks below don't each independently re-walk this fallback-parsed AST to build the same scope graph.\n const program = ensureProgram(ast, moduleId);\n scopeAnalysis = analyzeModuleScope(program);\n }\n\n runBackendStaticChecks(ast, moduleId, log, scopeAnalysis);\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 { BuildOptions, InlineConfig, Plugin } from 'vite';\n\nimport { BACKEND_CODE_EXTENSIONS } from '../constants';\n\n/**\n * Create the virtual module resolver plugin used by both production and dev builds.\n * Maps virtual IDs to their generated source content.\n */\nexport function createVirtualPlugin(name: string, virtualEntries: Record<string, string>): Plugin {\n return {\n name,\n enforce: 'pre',\n resolveId(id: string) {\n if (virtualEntries[id]) {\n return { id, moduleSideEffects: true };\n }\n return null;\n },\n load(id: string) {\n if (virtualEntries[id]) {\n return virtualEntries[id];\n }\n return null;\n },\n };\n}\n\n/**\n * Shared Vite/Rollup config for building backend functions.\n * Both the production build (write to disk) and dev build (in-memory)\n * use this as a base, overriding only what differs.\n */\nexport function getBaseBackendBuildConfig(\n root: string,\n virtualEntries: Record<string, string>,\n plugins: Plugin[] = [],\n): InlineConfig & {\n build: BuildOptions & { rollupOptions: NonNullable<BuildOptions['rollupOptions']> };\n} {\n return {\n configFile: false,\n // configFile: false only skips loading a vite.config.js — it does not disable Vite's\n // separate .env-file/import.meta.env machinery, which otherwise copies any VITE_-prefixed\n // key straight out of the real process.env and statically inlines it into the built\n // backend function. envPrefix: [] blocks that copy; envFile: false additionally stops a\n // secret set only in the build root's own .env file from being read at all.\n envFile: false,\n envPrefix: [],\n root,\n logLevel: 'silent',\n build: {\n minify: false,\n target: 'esnext',\n // Backend functions run server-side. Without this, Vite's default\n // browser-target build externalizes Node builtins (node:crypto, fs)\n // to a stub with no real exports.\n ssr: true,\n rollupOptions: {\n output: { format: 'es', exports: 'named', inlineDynamicImports: true },\n preserveEntrySignatures: 'exports-only',\n // Each exported function is bundled separately, so without tree-shaking every\n // bundle carries the whole import graph of its `.backend.ts` file, including code\n // only sibling exports use. Standard tree-shaking keeps modules' top-level side\n // effects, honoring packages' `\"sideEffects\"` field like the frontend build does.\n treeshake: true,\n onwarn(warning, defaultHandler) {\n if (warning.code === 'MODULE_LEVEL_DIRECTIVE') {\n return;\n }\n defaultHandler(warning);\n },\n },\n },\n resolve: {\n extensions: [...BACKEND_CODE_EXTENSIONS, '.json'],\n },\n // SSR mode externalizes node_modules deps by default, assuming a\n // server runtime can require() them at runtime. Backend bundles have\n // no such runtime available (sent in-memory or uploaded standalone),\n // so every dependency must be inlined instead.\n ssr: {\n noExternal: true,\n },\n plugins: [createVirtualPlugin('dd-backend-resolve', virtualEntries), ...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\nimport fsp from 'fs/promises';\nimport fs from 'fs';\nimport JSZip from 'jszip';\n\nimport type { Asset } from './assets';\n\nexport type Archive = {\n archivePath: string;\n size: number;\n assets: Asset[];\n};\n\nexport const createArchive = async (assets: Asset[], archivePath: string): Promise<Archive> => {\n const zip = new JSZip();\n for (const asset of assets) {\n zip.file(asset.relativePath, fs.createReadStream(asset.absolutePath), {\n binary: true,\n compression: 'DEFLATE',\n compressionOptions: { level: 9 },\n });\n }\n\n await new Promise<void>((resolve, reject) => {\n const output = fs.createWriteStream(archivePath);\n const stream = zip.generateNodeStream({\n type: 'nodebuffer',\n streamFiles: true,\n compression: 'DEFLATE',\n compressionOptions: { level: 9 },\n });\n stream.on('error', reject);\n output.on('error', reject);\n output.on('close', resolve);\n stream.pipe(output);\n });\n\n // Compute the size for logging purpose.\n const { size } = await fsp.stat(archivePath);\n\n return {\n archivePath,\n size,\n assets,\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 { glob } from 'glob';\nimport path from 'path';\n\nexport type Asset = {\n absolutePath: string;\n relativePath: string;\n};\n\n/**\n * Finds the common directory prefix across all paths.\n * Returns the longest common directory path that all paths share.\n * @param paths - Array of relative paths\n * @returns Common directory prefix (without trailing separator), or empty string if no common prefix\n */\nexport const findCommonPrefix = (paths: string[]): string => {\n if (paths.length === 0) {\n return '';\n }\n\n const segments = paths[0].split(path.sep);\n let commonPrefix = '';\n\n for (let i = 0; i < segments.length - 1; i++) {\n const prefix = segments.slice(0, i + 1).join(path.sep);\n const allMatch = paths.every((p) => p.startsWith(`${prefix}${path.sep}`));\n if (allMatch) {\n commonPrefix = prefix;\n } else {\n break;\n }\n }\n\n return commonPrefix;\n};\n\nexport const collectAssets = async (patterns: string[], cwd: string): Promise<Asset[]> => {\n const matches = (\n await Promise.all(\n patterns.map((pattern) => {\n return glob(pattern, { absolute: true, cwd, nodir: true });\n }),\n )\n ).flat();\n\n // Compute relative paths from cwd\n const relativePaths = Array.from(new Set(matches)).map((match) => path.relative(cwd, match));\n\n // Find common directory prefix across all paths\n const commonPrefix = findCommonPrefix(relativePaths);\n\n const assets: Asset[] = relativePaths.map((relativePath, index) => {\n // Strip common prefix to get paths relative to the common directory\n const strippedPath = commonPrefix\n ? relativePath.slice(commonPrefix.length + 1)\n : relativePath;\n\n return {\n absolutePath: matches[index],\n // Normalize to forward slashes so archive entries are valid\n // on all platforms (ZIP spec requires POSIX separators).\n relativePath: strippedPath.split(path.sep).join('/'),\n };\n });\n\n return assets;\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/* global NodeJS */\n\nimport { readFile } from '@dd/core/helpers/fs';\nimport path from 'node:path';\n\n/** One process.env entry per secret the developer has supplied locally, keyed the same way production's resolved Custom Credentials env vars are (e.g. `STRIPE_API_KEY`). */\nexport type ResolvedCustomCredentials = Record<string, string>;\n\n/**\n * A git-ignored file the developer maintains themselves with real Custom Credentials values for\n * local execution — no server call, no new auth model, since no server-side resolution endpoint\n * exists for this. Same convention Rapid already documents for local secrets (`config/dev.json`,\n * gitignored), applied here to Custom Credentials.\n */\nexport const CUSTOM_CREDENTIALS_LOCAL_FILENAME = 'datadog-app.local.json';\n\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n/**\n * Resolves Custom Credentials for local execution by reading {@link CUSTOM_CREDENTIALS_LOCAL_FILENAME}\n * from the project root. A missing file resolves to `{}` — most projects won't have one — but a\n * present-and-malformed file throws, since silently ignoring a typo would make a declared secret\n * look identical to an undeclared one.\n */\nexport async function resolveCustomCredentials(\n projectRoot: string,\n): Promise<ResolvedCustomCredentials> {\n const filePath = path.join(projectRoot, CUSTOM_CREDENTIALS_LOCAL_FILENAME);\n let raw: string;\n try {\n raw = await readFile(filePath);\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // Never interpolate the underlying JSON.parse error: V8's message can embed a raw slice\n // of an unquoted value's source text, echoing a real secret into logs/HTTP responses.\n throw new Error(`${CUSTOM_CREDENTIALS_LOCAL_FILENAME} is not valid JSON.`);\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error(\n `${CUSTOM_CREDENTIALS_LOCAL_FILENAME} must be a flat JSON object mapping env var names to string values.`,\n );\n }\n\n // Object.create(null) rather than {} so a credential literally named \"__proto__\" round-trips\n // as a normal own property instead of silently no-op'ing against Object.prototype's setter.\n const resolved: ResolvedCustomCredentials = Object.create(null);\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value !== 'string') {\n throw new Error(\n `${CUSTOM_CREDENTIALS_LOCAL_FILENAME}'s \"${key}\" value must be a string, got ${typeof value}.`,\n );\n }\n resolved[key] = value;\n }\n return resolved;\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/* global NodeJS */\n\nimport { getDDEnvValue } from '@dd/core/helpers/env';\nimport { rm } from '@dd/core/helpers/fs';\nimport type { GlobalContext } from '@dd/core/types';\nimport fsp from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport { createArchive } from '../archive';\nimport type { Asset } from '../assets';\nimport { collectAssets } from '../assets';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { BackendFunction } from '../backend/types';\nimport { ARCHIVE_FILENAME, PLUGIN_NAME } from '../constants';\nimport type { AppsManifest, AppsOptionsWithDefaults } from '../types';\n\nimport { CUSTOM_CREDENTIALS_LOCAL_FILENAME } from './custom-credentials-resolver';\n\nexport interface BuildAppPackageOptions {\n backendOutputs: Map<string, string>;\n backendFunctions: BackendFunction[];\n context: GlobalContext;\n options: AppsOptionsWithDefaults;\n}\n\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\ntype FileIdentity = { dev: number; ino: number };\n\n/** Resolves the root credentials file's (device, inode) identity, or undefined if it doesn't exist. */\nasync function resolveCredentialsIdentity(buildRoot: string): Promise<FileIdentity | undefined> {\n try {\n const stats = await fsp.stat(path.join(buildRoot, CUSTOM_CREDENTIALS_LOCAL_FILENAME));\n return { dev: stats.dev, ino: stats.ino };\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n return undefined;\n }\n throw error;\n }\n}\n\n/**\n * Compares an asset's (device, inode) identity against the credentials file's, since fs.stat\n * follows symlinks either way and inode identity also catches a hardlink — cases a path-string\n * comparison alone can miss. A vanished asset has nothing left to leak; any other stat failure is\n * re-thrown rather than silently treated as safe to package.\n */\nasync function isCustomCredentialsAsset(\n absolutePath: string,\n credentialsIdentity: FileIdentity | undefined,\n): Promise<boolean> {\n if (path.basename(absolutePath).toLowerCase() === CUSTOM_CREDENTIALS_LOCAL_FILENAME) {\n return true;\n }\n if (!credentialsIdentity) {\n return false;\n }\n try {\n const stats = await fsp.stat(absolutePath);\n return stats.dev === credentialsIdentity.dev && stats.ino === credentialsIdentity.ino;\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n return false;\n }\n throw error;\n }\n}\n\nfunction buildManifest(backendFunctions: BackendFunction[]): AppsManifest {\n const functions: AppsManifest['backend']['functions'] = {};\n for (const func of backendFunctions) {\n functions[encodeQueryName(func)] = {\n allowedConnectionIds: [...func.allowedConnectionIds],\n };\n }\n\n return { backend: { functions } };\n}\n\nasync function writeManifestFile(\n backendFunctions: BackendFunction[],\n): Promise<{ manifestAsset: Asset; cleanup: () => Promise<void> }> {\n const manifestDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'dd-apps-manifest-'));\n const manifestPath = path.join(manifestDir, 'manifest.json');\n try {\n await fsp.writeFile(manifestPath, JSON.stringify(buildManifest(backendFunctions), null, 2));\n } catch (error) {\n await rm(manifestDir);\n throw error;\n }\n return {\n manifestAsset: { absolutePath: manifestPath, relativePath: 'manifest.json' },\n cleanup: () => rm(manifestDir),\n };\n}\n\nexport async function buildAppPackage({\n backendOutputs,\n backendFunctions,\n context,\n options,\n}: BuildAppPackageOptions): Promise<string | undefined> {\n const log = context.getLogger(PLUGIN_NAME);\n const {\n buildRoot,\n bundler: { outDir },\n } = context;\n const defaultArchivePath = path.join(outDir, ARCHIVE_FILENAME);\n const packageDirectory = path.resolve(getDDEnvValue('APPS_PACKAGE_DIR') || outDir);\n const archivePath = path.join(packageDirectory, ARCHIVE_FILENAME);\n\n // Remove stale package outputs before collecting assets so that previous\n // archive files don't alter the common-prefix computation used to strip\n // the output directory from asset paths.\n await Promise.all([\n fsp.rm(archivePath, { force: true }),\n fsp.rm(defaultArchivePath, { force: true }),\n ]);\n\n const relativeOutdir = path.relative(buildRoot, outDir);\n const assets = await collectAssets([...options.include, `${relativeOutdir}/**/*`], buildRoot);\n if (assets.length === 0 && backendOutputs.size === 0) {\n log.debug('No assets to package.');\n return undefined;\n }\n\n await fsp.mkdir(packageDirectory, { recursive: true });\n\n let cleanupManifest: (() => Promise<void>) | undefined;\n try {\n const generatedPaths = new Set([archivePath, defaultArchivePath]);\n const backendPaths = new Set(backendOutputs.values());\n const candidateAssets = assets\n .filter((asset) => !generatedPaths.has(path.resolve(asset.absolutePath)))\n .filter((asset) => !backendPaths.has(asset.absolutePath));\n const credentialsIdentity = await resolveCredentialsIdentity(buildRoot);\n const nonCredentialsAssets = (\n await Promise.all(\n candidateAssets.map(async (asset) => ({\n asset,\n isCredentialsAsset: await isCustomCredentialsAsset(\n asset.absolutePath,\n credentialsIdentity,\n ),\n })),\n )\n ).filter(({ isCredentialsAsset }) => !isCredentialsAsset);\n const frontendAssets = nonCredentialsAssets.map(({ asset }) => ({\n ...asset,\n relativePath: `frontend/${asset.relativePath}`,\n }));\n const packageAssets: Asset[] = [...frontendAssets];\n for (const [bundleName, absolutePath] of backendOutputs) {\n packageAssets.push({\n absolutePath,\n relativePath: `backend/${bundleName}.js`,\n });\n }\n const manifest = await writeManifestFile(backendFunctions);\n cleanupManifest = manifest.cleanup;\n packageAssets.push(manifest.manifestAsset);\n const archive = await createArchive(packageAssets, archivePath);\n log.info(`App package written to ${archive.archivePath}.`);\n return archive.archivePath;\n } finally {\n await cleanupManifest?.();\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 no-await-in-loop */\n\nimport { readFile } from '@dd/core/helpers/fs';\nimport type { Logger } from '@dd/core/types';\nimport { transform } from 'esbuild';\nimport { parseAst } from 'rollup/parseAst';\nimport type { ModuleNode, ViteDevServer } from 'vite';\n\nimport {\n createParsedModuleRecord,\n getStaticModuleSources,\n type ParsedModuleRecord,\n shouldTraverseCollectedModule,\n unsupportedModuleGraphDependency,\n} from '../backend/ast-parsing/module-graph';\nimport { runBackendStaticChecks } from '../backend/ast-parsing/run-backend-static-checks';\nimport { LOCAL_EXECUTION_LOAD_SUFFIX } from '../constants';\n\nimport { normalizeViteModuleId } from './backend-module-graph-collector';\n\n/**\n * Rebuilds `createBackendModuleGraphCollector`'s `ParsedModuleRecord` map for the dev server\n * (no `moduleParsed` hook here), re-parsing each module from disk via `esbuild.transform`.\n * Primes each node via `transformRequest` (resolve + transform, never executes) before running\n * static checks, so a module can't dodge them by having `ssrLoadModule` already run its code.\n */\nexport async function collectModuleGraphFromServer(\n server: ViteDevServer,\n bareEntryId: string,\n buildRoot: string,\n log: Logger,\n): Promise<ReadonlyMap<string, ParsedModuleRecord>> {\n const records = new Map<string, ParsedModuleRecord>();\n const visited = new Set<string>();\n const pending: ModuleNode[] = [];\n\n const entryUrl = bareEntryId + LOCAL_EXECUTION_LOAD_SUFFIX;\n await server.transformRequest(entryUrl, { ssr: true });\n const entryNode = server.moduleGraph.getModuleById(entryUrl);\n if (entryNode) {\n pending.push(entryNode);\n }\n\n while (pending.length > 0) {\n const node = pending.shift()!;\n\n const moduleId = node.id ? normalizeDevServerModuleId(node.id) : undefined;\n if (!moduleId || !node.file) {\n continue;\n }\n\n // Checked by normalized moduleId (extension-based), before the query check below, so a\n // non-traversable non-code import (e.g. `./template.html?raw`) is skipped like the\n // build-time collector skips it, regardless of its query.\n if (!shouldTraverseCollectedModule(moduleId, buildRoot)) {\n continue;\n }\n\n // Checked before the visited-set dedup below: a query'd id and its plain counterpart\n // normalize to the same moduleId, so deduping first would let a query'd form silently\n // skip this check once the plain form had already been visited.\n if (node.id && hasSemanticViteQuery(node.id)) {\n throw unsupportedModuleGraphDependency(\n moduleId,\n `Vite resource query on module id \"${node.id}\"`,\n );\n }\n\n if (visited.has(moduleId)) {\n continue;\n }\n visited.add(moduleId);\n\n // Known, accepted gap: reads straight from disk, so a project's own `load`/`transform`\n // hook rewriting this file is invisible here. `transformRequest`'s output isn't usable\n // instead — it already carries Vite's SSR import-rewrite, which our parser can't read.\n let source: string;\n try {\n source = await readFile(node.file);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw unsupportedModuleGraphDependency(\n moduleId,\n `unreadable module source (${reason})`,\n );\n }\n\n let ast;\n try {\n const stripped = await transform(source, {\n loader: loaderForModuleId(moduleId),\n format: 'esm',\n });\n ast = parseAst(stripped.code);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw unsupportedModuleGraphDependency(\n moduleId,\n `unparseable module source (${reason})`,\n );\n }\n\n // `createParsedModuleRecord` zips dependency ids positionally against the AST's static\n // imports, so this list must be static-only, same order — resolved individually since\n // the dev server has no Rollup-style `ModuleInfo.importedIds`.\n const staticModuleSources = getStaticModuleSources(ast);\n const importerFile = node.file;\n const resolutions = await Promise.all(\n staticModuleSources.map((moduleSource) =>\n server.pluginContainer.resolveId(moduleSource, importerFile ?? undefined, {\n ssr: true,\n }),\n ),\n );\n const staticDependencyIds = resolutions.map((resolved, index) => {\n if (!resolved) {\n // Fail closed — falling back to the raw specifier would let a connectionId\n // silently drop out of the allowlist instead of failing loudly.\n throw unsupportedModuleGraphDependency(\n moduleId,\n `unresolvable import specifier \"${staticModuleSources[index]}\"`,\n );\n }\n return normalizeDevServerModuleId(resolved.id);\n });\n\n const record = createParsedModuleRecord(moduleId, buildRoot, ast, staticDependencyIds);\n if (record) {\n // No build-time moduleParsed hook here (Rollup-only), so this is what catches a\n // banned import or restricted global locally instead of only at publish time.\n runBackendStaticChecks(record.ast, record.id, log, record.scopeAnalysis);\n records.set(record.id, record);\n }\n\n for (const dependencyNode of node.importedModules) {\n // Primes this dependency's own `importedModules` before it's dequeued, the same\n // non-evaluating priming the entry got above — so no node in the traversal is ever\n // read before it has itself gone through this same transform-only step.\n if (dependencyNode.id) {\n await server.transformRequest(dependencyNode.id, { ssr: true });\n }\n pending.push(dependencyNode);\n }\n }\n\n return records;\n}\n\nfunction loaderForModuleId(moduleId: string): 'ts' | 'tsx' | 'jsx' | 'js' {\n if (moduleId.endsWith('.tsx')) {\n return 'tsx';\n }\n if (moduleId.endsWith('.ts') || moduleId.endsWith('.mts') || moduleId.endsWith('.cts')) {\n return 'ts';\n }\n if (moduleId.endsWith('.jsx')) {\n return 'jsx';\n }\n return 'js';\n}\n\n// The marker is always a literal trailing suffix, never combined with another query — exact\n// suffix match, not cutting at the first `?`, which would also discard a real resource query.\nfunction stripLocalExecutionMarker(id: string): string {\n return id.endsWith(LOCAL_EXECUTION_LOAD_SUFFIX)\n ? id.slice(0, -LOCAL_EXECUTION_LOAD_SUFFIX.length)\n : id;\n}\n\nfunction hasSemanticViteQuery(id: string): boolean {\n return stripLocalExecutionMarker(id).includes('?');\n}\n\n// Named distinctly from backend-module-graph-collector.ts's normalizeViteModuleId, which this\n// wraps, since same-named-different-behavior would invite editing the wrong copy.\nfunction normalizeDevServerModuleId(id: string): string {\n const unsuffixedId = stripLocalExecutionMarker(id);\n return normalizeViteModuleId(unsuffixedId);\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/** Generation-counter guard so an abandoned scope's late cleanup can't touch a shared resource a newer scope now owns (used by `local-execution.ts`). */\nexport interface EpochScope {\n /** True until a newer scope starts, or this scope is concluded or invalidated. */\n isCurrent(): boolean;\n /** Marks no scope active and returns true if still current, otherwise a no-op returning false — call in a `finally` to gate cleanup on still owning the resource. */\n concludeIfCurrent(): boolean;\n}\n\nexport interface EpochGuard {\n /** Starts a new scope, superseding whichever one was previously active. */\n start(): EpochScope;\n /** True if some started scope hasn't yet been concluded or superseded. */\n hasActiveScope(): boolean;\n /** Unconditionally invalidates the active scope without starting a new one — the backstop for a scope whose own `fn` never settles. */\n forceInvalidate(): void;\n}\n\nexport function createEpochGuard(): EpochGuard {\n let currentGeneration = 0;\n let activeGeneration: number | null = null;\n\n return {\n start() {\n const myGeneration = ++currentGeneration;\n activeGeneration = myGeneration;\n return {\n isCurrent: () => activeGeneration === myGeneration,\n concludeIfCurrent: () => {\n if (activeGeneration === myGeneration) {\n activeGeneration = null;\n return true;\n }\n return false;\n },\n };\n },\n hasActiveScope() {\n return activeGeneration !== null;\n },\n forceInvalidate() {\n activeGeneration = null;\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 { LongPollingOptions } from '../types';\n\ntype LongPollingConfig = Required<LongPollingOptions>;\n\n// Kept small: `done: false` is healthy, so this delay is dead time. It only\n// exists to de-synchronize concurrent pollers.\nexport const RETRY_BASE_DELAY_MS = 250;\nexport const RETRY_MAX_DELAY_MS = 2_000;\n\n/** Deterministic upper bound for one retry delay, ignoring jitter's random reduction — dev-server.ts's `getRetryDelay` only ever reduces toward this ceiling, never past it, so it also bounds the worst-case budget below. */\nexport function getMaxRetryDelayMs(attempt: number, exponentialBackoff: boolean): number {\n return exponentialBackoff\n ? Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS)\n : RETRY_BASE_DELAY_MS;\n}\n\n/** Worst-case total time `pollQueryExecution` spends waiting between attempts — shared so `deriveActionTimeouts`'s ceilings can't drift from the delays it actually waits out. */\nexport function getTotalRetryDelayBudgetMs(config: LongPollingConfig): number {\n let totalMs = 0;\n for (let attempt = 1; attempt < config.maxRetries; attempt++) {\n totalMs += getMaxRetryDelayMs(attempt, config.exponentialBackoff);\n }\n return totalMs;\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/* global Proxy, globalThis */\n\n/** Executes a backend function's file directly in-process inside the Vite dev server — a drop-in alternate to dev-server.ts's executeScriptViaDatadog, mirroring its `BackendOutputs` contract. */\n\nimport type { Logger } from '@dd/core/types';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { isActionCatalogInstalled, isDatadogAppsBackendInstalled } from '../backend/shared';\nimport type { BackendFunction, BackendOutputs } from '../backend/types';\nimport { LOCAL_EXECUTION_LOAD_SUFFIX } from '../constants';\nimport type { LongPollingOptions } from '../types';\nimport { resolveLongPolling } from '../validate';\n\nimport { resolveCustomCredentials } from './custom-credentials-resolver';\nimport type { EnvScopeHandle } from './env-guard';\nimport { createEpochGuard } from './execution-epoch';\nimport type { BlockedScopeHandle } from './network-guard';\nimport { getTotalRetryDelayBudgetMs } from './retry-delay';\n\n// Lazily imports and memoizes a guard module on first call, resetting the memo on a failed import\n// so a later call can retry rather than being stuck replaying the same rejection forever.\nfunction lazyImportOnce<T>(loader: () => Promise<T>): () => Promise<T> {\n let modulePromise: Promise<T> | undefined;\n return () => {\n modulePromise ??= loader().catch((err: unknown) => {\n modulePromise = undefined;\n throw err;\n });\n return modulePromise;\n };\n}\n\n// network-guard.ts installs process-wide monkeypatches (net.Socket, fetch, dgram, dns,\n// child_process, worker_threads.Worker) unconditionally at its own module-load time. A static\n// import here would trigger that install for every bundler that transitively imports this file via\n// index.ts (webpack/esbuild/rspack/rollup included), even though local execution is Vite-dev-only —\n// deferring the import until a local execution actually happens confines the install to Vite.\nconst getNetworkGuard = lazyImportOnce(() => import('./network-guard'));\n\n// Same reasoning as getNetworkGuard() just above: env-guard.ts installs process-wide monkeypatches\n// (fs.readFileSync/readFile/createReadStream/openSync/open and their promises variants,\n// process.report.getReport/writeReport) unconditionally at its own module-load time. A static\n// import here would trigger that install for every bundler, not just Vite.\nconst getEnvGuard = lazyImportOnce(() => import('./env-guard'));\n\ntype RuntimeUser = {\n id: string;\n orgId: string;\n email?: string | null;\n name?: string | null;\n};\n\nexport type RuntimeContext = Record<string, unknown> & {\n Source: {\n initiator: RuntimeUser;\n runAsUser: RuntimeUser;\n };\n};\n\ntype BackendGlobals = RuntimeContext & {\n backendFunctionArgs: unknown[];\n Actions: unknown;\n};\n\n/** Boxed so a customer module assigning to `globalThis.$` (e.g. `zx/globals`) mutates only its own execution's box, never a concurrent or zombie execution's. */\ntype BackendGlobalsBox = { value: unknown };\n\n/** Scopes `globalThis.$` per execution via AsyncLocalStorage so a zombie execution's late \"fresh\" read resolves to its own `$`, never a newer execution's identity. */\nconst backendGlobalsContext = new AsyncLocalStorage<BackendGlobalsBox>();\n\n/** Whether `$` was installed (e.g. by `zx/globals`) before this module's own accessor — distinguishes that legitimate passthrough from a customer module reaching for `$` with no prior value, which should fail like production does. */\nconst hadPreexistingDollar = Reflect.has(globalThis, '$');\n\n/** Marks the window where a customer module's own top-level code is loading (narrower than \"between executions,\" where the undefined-returning fallback below applies instead). Carries its own mutable box so a top-level `$` write (e.g. `zx/globals`) is scoped to this load, not the shared `globalDollarOutsideExecution` slot a later, unrelated load would also read. */\nconst customerModuleLoadContext = new AsyncLocalStorage<{ assigned: boolean; value: unknown }>();\n\n/** Scopes vite/index.ts's suffixed-subgraph tracking to one entry's own module-graph traversal — every caller funnels through `loadCustomerModuleEntry`, so scoping here reaches every path uniformly. Without this, a process-wide Set would let a helper module stay marked for the dev server's whole lifetime, so a later unrelated SSR resolution of that helper would inherit the marker and serve real backend code instead of the frontend RPC-proxy stub. */\nexport const localExecutionResolutionContext = new AsyncLocalStorage<Set<string>>();\n\n/** Backs `globalThis.$` outside any execution box; seeded from any `$` already installed before this module loaded so the accessor below doesn't discard a legitimate `zx/globals`-style passthrough. */\nlet globalDollarOutsideExecution: unknown = Reflect.get(globalThis, '$');\n\nfunction ensureDollarAccessorInstalled(): void {\n if (Object.getOwnPropertyDescriptor(globalThis, '$')?.get === dollarGetter) {\n return;\n }\n Object.defineProperty(globalThis, '$', {\n configurable: true,\n enumerable: true,\n get: dollarGetter,\n set: dollarSetter,\n });\n}\n\nfunction dollarGetter(): unknown {\n const box = backendGlobalsContext.getStore();\n if (box) {\n return box.value;\n }\n const loadBox = customerModuleLoadContext.getStore();\n if (loadBox) {\n if (loadBox.assigned) {\n return loadBox.value;\n }\n if (hadPreexistingDollar) {\n return globalDollarOutsideExecution;\n }\n // Matches production: $ isn't global until main() assigns it, so it reads as undefined\n // rather than throwing, even though it's a real accessor property here, not absent.\n return undefined;\n }\n return globalDollarOutsideExecution;\n}\n\nfunction dollarSetter(value: unknown): void {\n const box = backendGlobalsContext.getStore();\n if (box) {\n box.value = value;\n return;\n }\n const loadBox = customerModuleLoadContext.getStore();\n if (loadBox) {\n // Scoped to this load, not globalDollarOutsideExecution — otherwise a top-level write (e.g. zx/globals) would leak into every later, unrelated load.\n loadBox.assigned = true;\n loadBox.value = value;\n return;\n }\n globalDollarOutsideExecution = value;\n}\n\nensureDollarAccessorInstalled();\n\n/** What the stable, once-ever-registered adapters below need to dispatch a call to whichever execution is live on the AsyncLocalStorage stack — kept out of `BackendGlobals` since that's also `globalThis.$`, visible to customer code. */\ntype ExecutionDispatch = {\n executeAction: ExecuteAction;\n allowedConnectionIds: string[];\n isAbandoned: () => boolean;\n functionName: string;\n $: BackendGlobals;\n};\n\n/** Distinct from `backendGlobalsContext` so dispatch-only fields (the real `executeAction`, `allowedConnectionIds`) never leak onto `globalThis.$`. */\nconst executionDispatchContext = new AsyncLocalStorage<ExecutionDispatch>();\n\ninterface ActionCallArgs {\n inputs: Record<string, unknown>;\n connectionId?: string;\n}\n\n/** Narrows an unknown value enough to read named properties off it by key. */\nfunction isIndexableRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction assertRuntimeUser(value: unknown, label: string): asserts value is RuntimeUser {\n if (!isIndexableRecord(value) || Array.isArray(value)) {\n throw new Error(`The preview runtime context ${label} must be an object.`);\n }\n if (typeof value.id !== 'string' || value.id.length === 0) {\n throw new Error(\n `The preview runtime context ${label} must have a non-empty string \"id\" field.`,\n );\n }\n if (typeof value.orgId !== 'string' || value.orgId.length === 0) {\n throw new Error(\n `The preview runtime context ${label} must have a non-empty string \"orgId\" field.`,\n );\n }\n if (value.email !== undefined && value.email !== null && typeof value.email !== 'string') {\n throw new Error(\n `The preview runtime context ${label} must have a string \"email\" field when provided.`,\n );\n }\n if (value.name !== undefined && value.name !== null && typeof value.name !== 'string') {\n throw new Error(\n `The preview runtime context ${label} must have a string \"name\" field when provided.`,\n );\n }\n}\n\n/** Validates the identity-bearing minimum of the preview-provided `$` snapshot before any customer module is loaded. */\nexport function assertValidRuntimeContext(value: unknown): asserts value is RuntimeContext {\n if (!isIndexableRecord(value) || Array.isArray(value)) {\n throw new Error('The preview runtime context must be an object.');\n }\n const source = value.Source;\n if (!isIndexableRecord(source) || Array.isArray(source)) {\n throw new Error('The preview runtime context must have a \"Source\" object.');\n }\n assertRuntimeUser(source.initiator, 'Source.initiator');\n assertRuntimeUser(source.runAsUser, 'Source.runAsUser');\n}\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n\ntype LongPollingConfig = Required<LongPollingOptions>;\n\n// Derived from validate.ts's own resolveLongPolling rather than a hardcoded copy, so callers get\n// the same effective ceilings a real dev server derives without each passing one in.\nexport const DEFAULT_LONG_POLLING_CONFIG: LongPollingConfig = resolveLongPolling(undefined);\n\n/**\n * Both ceilings must exceed `pollQueryExecution`'s worst-case budget: polling time\n * (`maxRetries * timeoutMs`) plus the retry-delay budget. Exported so tests compute the expected\n * value instead of hardcoding a copy.\n */\nexport function deriveActionTimeouts(longPolling: LongPollingConfig): {\n actionCallTimeoutMs: number;\n totalExecutionTimeoutMs: number;\n} {\n const worstCaseMs =\n longPolling.maxRetries * longPolling.timeoutMs + getTotalRetryDelayBudgetMs(longPolling);\n return {\n // Bounds a single $.Actions call, exempt from the hang-detection timer — doRequest has\n // no deadline of its own, so an unsettled call would wedge the whole serialized queue.\n actionCallTimeoutMs: worstCaseMs * 2,\n // Absolute wall-clock ceiling, independent of the pause-and-extend mechanism above —\n // that can't tell a genuinely slow $.Actions call from a fire-and-forgot one masking a\n // real hang, so this bounds the masked case tighter without cutting off legitimate calls.\n totalExecutionTimeoutMs: worstCaseMs * 1.2,\n };\n}\n\n/** Loads a module by specifier, resolved against the customer's own project rather than build-plugins' dependency tree — the dev server passes its Vite instance's `ssrLoadModule` here. */\nexport type LoadModule = (specifier: string) => Promise<Record<string, unknown>>;\n\n/**\n * Loads a customer module under `runScriptLocally`'s top-level-evaluation `$`-scoping (see\n * `customerModuleLoadContext`), for callers like dev-server.ts's priming load that trigger real\n * top-level evaluation ahead of `executeScriptLocally`. Scopes `process.env` and the network guard\n * first so a dependency's top-level code can't capture the real, unwrapped `fs.readFileSync`/network\n * APIs and bypass the guard for the rest of the session. Resolves real Custom Credentials via\n * `projectRoot` too — module-scope SDK initialization (`new Stripe(process.env.X)`) would otherwise\n * always capture `undefined`. `onScopeStarted` lets a caller record this load's abandon token so a\n * hung load can be abandoned without affecting any other execution's still-active scope. Accepted\n * residual gap: this load still runs outside `runBlocked`, so top-level code has real, unguarded\n * network/subprocess access — not a hard boundary, matching this file's \"no OS sandbox\" framing.\n */\nexport async function loadCustomerModuleEntry(\n loadModule: LoadModule,\n entrySpecifier: string,\n projectRoot: string,\n onScopeStarted?: (handle: EnvScopeHandle) => void,\n): Promise<Record<string, unknown>> {\n const [{ buildScopedEnv, runWithScopedEnv }, customCredentials] = await Promise.all([\n getEnvGuard(),\n resolveCustomCredentials(projectRoot),\n getNetworkGuard(),\n ]);\n const scopedEnv = buildScopedEnv(customCredentials);\n return localExecutionResolutionContext.run(new Set(), () =>\n customerModuleLoadContext.run({ assigned: false, value: undefined }, () =>\n runWithScopedEnv(scopedEnv, () => loadModule(entrySpecifier), onScopeStarted),\n ),\n );\n}\n\n/** Executes a real `$.Actions.foo.bar(...)` call; the dev server supplies the implementation using its own auth, so this module never holds or sees a credential itself. */\nexport type ExecuteAction = (\n fqn: string,\n inputs: unknown,\n connectionId: string | undefined,\n) => Promise<unknown>;\n\n/** Resolves a fresh serializable `$` snapshot from an authenticated preview execution. */\nexport type GetRuntimeContext = () => Promise<unknown>;\n\n/** Mirrors the cloud path's server-side allowedConnectionIds restriction, so local dev enforces the same connection scoping as production. */\nfunction assertConnectionIdAllowed(\n connectionId: string | undefined,\n allowedConnectionIds: string[],\n actionDescription: string,\n): void {\n if (connectionId !== undefined && !allowedConnectionIds.includes(connectionId)) {\n throw new Error(\n `Action ${actionDescription} used connection \"${connectionId}\", which is not in this function's allowed connections: [${allowedConnectionIds.join(', ')}]`,\n );\n }\n}\n\n/** Shared validation for both $.Actions entry points (raw proxy and action-catalog typed wrapper) — extracted so a contract change can't be applied to one path and missed on the other. */\nfunction validateActionCall(\n call: Partial<ActionCallArgs>,\n allowedConnectionIds: string[],\n actionDescription: string,\n): { inputs: Record<string, unknown>; connectionId: string | undefined } {\n const { inputs, connectionId } = call;\n if (typeof inputs !== 'object' || !inputs) {\n throw new Error(`Action ${actionDescription} must have an inputs field`);\n }\n assertConnectionIdAllowed(connectionId, allowedConnectionIds, actionDescription);\n return { inputs, connectionId };\n}\n\n/** Shared validate → serialize → runAllowed sequence for both $.Actions entry points — same reasoning as `validateActionCall` above, extended to cover the whole call instead of just the inputs check. */\nasync function invokeAction(\n executeAction: ExecuteAction,\n actionId: string,\n call: Partial<ActionCallArgs>,\n allowedConnectionIds: string[],\n actionDescription: string,\n): Promise<unknown> {\n const { inputs, connectionId } = validateActionCall(\n call,\n allowedConnectionIds,\n actionDescription,\n );\n const serializedInputs = serializeActionInputs(inputs, actionDescription);\n const { runAllowed } = await getNetworkGuard();\n return runAllowed(() => executeAction(actionId, serializedInputs, connectionId));\n}\n\n/** Serializes local executions — a customer function deleting `globalThis.$` mid-flight would otherwise break `$` access for any other execution concurrently in progress (see `ensureDollarAccessorInstalled`). */\nlet queueTail: Promise<unknown> = Promise.resolve();\n\nfunction enqueue<T>(run: () => Promise<T>): Promise<T> {\n const result = queueTail.then(run);\n queueTail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n}\n\n// Shared wording for the \"no longer current\" rejection at every abandonment call site.\nfunction abandonedExecutionError(functionName: string, refusedAction: string): Error {\n return new Error(\n `Execution of \"${functionName}\" already concluded; refusing to ${refusedAction} ` +\n `as this stale execution to avoid using a newer execution's identity.`,\n );\n}\n\n/**\n * One shared guard across all executions — `enqueue` only serializes each execution's start, so a\n * timed-out `fn()` keeps running (abandoned, not canceled). `isCurrent()` rejects that zombie's\n * later dispatch once a newer scope takes over; `concludeIfCurrent()` only clears the generation if\n * its own scope is still active, so delayed cleanup can't clobber a newer scope.\n */\nconst executionEpoch = createEpochGuard();\n\n/** JSON round-trips `$.Actions` inputs before `runAllowed`, so a malicious `toJSON()`/getter can't sneak a network call under the trusted action — uses the same strict validation as a return value (`assertJsonRoundTrippable`), so a Map/Set/NaN/symbol-keyed input fails loudly instead of reaching the destination corrupted. Also re-checks the round-tripped shape, since a top-level `toJSON()` can turn an object into a string/array. */\nfunction serializeActionInputs(\n inputs: Record<string, unknown>,\n actionDescription: string,\n): Record<string, unknown> {\n const subject = `Inputs to action ${actionDescription}`;\n const roundTripped = assertJsonRoundTrippable(inputs, subject);\n if (roundTripped === null || typeof roundTripped !== 'object' || Array.isArray(roundTripped)) {\n throw new Error(\n `${subject} must be a plain object after JSON round-tripping, but a custom toJSON() changed its top-level shape to ${Array.isArray(roundTripped) ? 'an array' : roundTripped === null ? 'null' : typeof roundTripped} — return a plain JSON-compatible object instead.`,\n );\n }\n return roundTripped as Record<string, unknown>;\n}\n\n/** Resolves a `$.Actions` path to a callable wrapped in `runAllowed`, the one call exempted from `runBlocked` (see network-guard.ts). */\nfunction makeActionsProxy(\n executeAction: ExecuteAction,\n allowedConnectionIds: string[],\n pathParts: string[] = [],\n): unknown {\n return new Proxy(function () {}, {\n get(_target, prop) {\n // Must not look thenable/serializable — Promise/assertJsonSerializable probes for\n // .then()/.toJSON() would otherwise hit apply() below and hang or leak a rejection.\n if (prop === 'then' || prop === 'toJSON') {\n return undefined;\n }\n const nestedPathParts = pathParts.concat(String(prop));\n return makeActionsProxy(executeAction, allowedConnectionIds, nestedPathParts);\n },\n async apply(_target, _thisArg, args: unknown[]) {\n const actionPath = pathParts.join('.');\n if (args.length === 0) {\n throw new Error(`No arguments provided to action $.Actions.${actionPath}`);\n }\n const call: Partial<ActionCallArgs> = isIndexableRecord(args[0]) ? args[0] : {};\n const fqn = `com.datadoghq.${actionPath}`;\n return invokeAction(\n executeAction,\n fqn,\n call,\n allowedConnectionIds,\n `$.Actions.${actionPath}`,\n );\n },\n });\n}\n\n/** Bounds a promise that could otherwise hang forever — a `loadModule` call against a broken/circular graph, or a `$.Actions` call with no deadline of its own. Doesn't cancel the underlying promise, so late side effects can still fire if it eventually settles; see each call site for why that's harmless there. `label` is the full subject of the timeout message (e.g. `` `Loading ${specifier}` ``), not a suffix on a fixed prefix. */\nexport function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`${label} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err: unknown) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\n/** Shared once-ever-registration wrapper for both adapters below: no-ops if uninstalled (re-checked uncached, so a mid-session install is picked up on the next execution), caches by `loadModule` identity (true once-ever for a real dev server's reused `ssrLoadModule`, isolated per test), and evicts a rejection so the next execution retries instead of staying poisoned. */\nfunction registerOnceIfInstalled(\n isInstalled: (projectRoot: string) => boolean,\n registrations: WeakMap<LoadModule, Promise<void>>,\n registerOnce: (loadModule: LoadModule, timeoutMs: number) => Promise<void>,\n loadModule: LoadModule,\n projectRoot: string,\n timeoutMs: number,\n): Promise<void> {\n if (!isInstalled(projectRoot)) {\n return Promise.resolve();\n }\n const existing = registrations.get(loadModule);\n if (existing) {\n return existing;\n }\n const registration = registerOnce(loadModule, timeoutMs).catch((err) => {\n registrations.delete(loadModule);\n throw err;\n });\n registrations.set(loadModule, registration);\n return registration;\n}\n\n/** Keyed by `loadModule` identity — see `registerOnceIfInstalled`'s doc comment. */\nconst actionCatalogRegistrations = new WeakMap<LoadModule, Promise<void>>();\n\n/** Registers one stable dispatcher for the process lifetime that reads `executionDispatchContext.getStore()` at call time, so a zombie's typed-wrapper call can never dispatch under a newer execution's identity. */\nfunction registerActionCatalogIfInstalled(\n loadModule: LoadModule,\n projectRoot: string,\n timeoutMs: number,\n): Promise<void> {\n return registerOnceIfInstalled(\n isActionCatalogInstalled,\n actionCatalogRegistrations,\n registerActionCatalogOnce,\n loadModule,\n projectRoot,\n timeoutMs,\n );\n}\n\nasync function registerActionCatalogOnce(loadModule: LoadModule, timeoutMs: number): Promise<void> {\n const loadPromise = loadModule('@datadog/action-catalog/action-execution');\n const mod = await withTimeout(\n loadPromise,\n timeoutMs,\n 'Loading @datadog/action-catalog/action-execution',\n );\n const setExecuteActionImplementation = mod.setExecuteActionImplementation;\n if (typeof setExecuteActionImplementation !== 'function') {\n return;\n }\n setExecuteActionImplementation(async (actionId: string, request: unknown) => {\n const dispatch = executionDispatchContext.getStore();\n if (!dispatch) {\n throw new Error(`No active local execution to run \"${actionId}\" under.`);\n }\n if (dispatch.isAbandoned()) {\n throw abandonedExecutionError(dispatch.functionName, `run \"${actionId}\"`);\n }\n const call: Partial<ActionCallArgs> = isIndexableRecord(request) ? request : {};\n return invokeAction(\n dispatch.executeAction,\n actionId,\n call,\n dispatch.allowedConnectionIds,\n `\"${actionId}\"`,\n );\n });\n}\n\n/** Mirrors `actionCatalogRegistrations` — see `registerOnceIfInstalled`'s doc comment. */\nconst backendRuntimeRegistrations = new WeakMap<LoadModule, Promise<void>>();\n\n/** Registers one stable runtime Proxy for the process lifetime that resolves whichever execution's `$` is live on the AsyncLocalStorage stack, rather than binding to one execution's `$` at registration time. */\nfunction registerBackendRuntimeIfInstalled(\n loadModule: LoadModule,\n projectRoot: string,\n timeoutMs: number,\n): Promise<void> {\n return registerOnceIfInstalled(\n isDatadogAppsBackendInstalled,\n backendRuntimeRegistrations,\n registerBackendRuntimeOnce,\n loadModule,\n projectRoot,\n timeoutMs,\n );\n}\n\nasync function registerBackendRuntimeOnce(\n loadModule: LoadModule,\n timeoutMs: number,\n): Promise<void> {\n const loadPromise = Promise.all([\n loadModule('@datadog/apps-backend/runtime/jsFunctionWithActions'),\n loadModule('@datadog/apps-backend/runtime'),\n ]);\n const [jsFunctionWithActionsModule, runtimeModule] = await withTimeout(\n loadPromise,\n timeoutMs,\n 'Loading @datadog/apps-backend/runtime',\n );\n const buildRuntimeFromJsFunctionWithActions =\n jsFunctionWithActionsModule.buildRuntimeFromJsFunctionWithActions;\n const setBackend = runtimeModule.setBackend;\n if (\n typeof buildRuntimeFromJsFunctionWithActions !== 'function' ||\n typeof setBackend !== 'function'\n ) {\n return;\n }\n // Cached by dispatch identity, not rebuilt per accessor call — dispatch.$ is fixed for the whole execution.\n const runtimeByDispatch = new WeakMap<ExecutionDispatch, unknown>();\n // Forwards whatever shape the real runtime's property has (nested namespace or flat method) rather than assuming every property is callable.\n const backendRuntimeProxy = new Proxy(\n {},\n {\n get(_target, prop) {\n const dispatch = executionDispatchContext.getStore();\n if (!dispatch) {\n throw new Error(\n `No active local execution to resolve an apps-backend accessor under.`,\n );\n }\n if (dispatch.isAbandoned()) {\n throw abandonedExecutionError(\n dispatch.functionName,\n 'resolve a further apps-backend accessor',\n );\n }\n let runtime = runtimeByDispatch.get(dispatch);\n if (runtime === undefined) {\n runtime = buildRuntimeFromJsFunctionWithActions(dispatch.$);\n runtimeByDispatch.set(dispatch, runtime);\n }\n if (!isIndexableRecord(runtime)) {\n return undefined;\n }\n const value = runtime[String(prop)];\n // A flat method must be bound to the real runtime object, not this Proxy's empty target; a nested namespace is returned as-is since its own methods already bind correctly.\n return typeof value === 'function' ? value.bind(runtime) : value;\n },\n },\n );\n setBackend(backendRuntimeProxy);\n}\n\n/** Rejects a non-JSON-serializable result (circular reference, `BigInt`, a dropped function/`Symbol`, a `Map`/`Set` flattened to `{}`) here with a clear error, instead of failing downstream when serialized for the HTTP response. */\n// Lets the replacer's already-specific message pass through the outer catch below unwrapped, instead of being replaced by its generic fallback.\nclass UnsupportedJsonValueError extends Error {}\n\n/**\n * Shared by a function's return value and its `$.Actions` call inputs — both cross a JSON boundary\n * and need the same protection against JSON.stringify's silent corruption (Map/Set flattened to\n * `{}`, non-finite numbers to `null`, functions/symbols/`undefined` dropped, symbol-keyed\n * properties omitted) rather than a bare `JSON.parse(JSON.stringify(...))` that would let corrupted\n * data pass through unnoticed. `subject` names what's being checked for the thrown error message.\n */\nfunction assertJsonRoundTrippable(value: unknown, subject: string): unknown {\n let serialized: string | undefined;\n try {\n // Visits every key/value pair including the root, catching a disallowed value at any\n // depth. Root is tracked via a one-shot flag, not `key === ''`, since a real property can\n // itself be named `''`.\n let isRootCall = true;\n serialized = JSON.stringify(value, function (key, childValue) {\n const wasRootCall = isRootCall;\n isRootCall = false;\n // Checked on `childValue` (a custom toJSON()'s return value, not necessarily the\n // original object) since the replacer never runs for a symbol-keyed property at all —\n // a symbol key introduced only by toJSON() would otherwise go undetected.\n if (\n childValue !== null &&\n typeof childValue === 'object' &&\n Object.getOwnPropertySymbols(childValue).length > 0\n ) {\n throw new UnsupportedJsonValueError(\n `${subject} contains a Symbol-keyed property${key ? ` (at \"${key}\")` : ''}, which JSON.stringify silently drops instead of serializing — use a plain JSON-compatible value instead.`,\n );\n }\n if (childValue instanceof Map || childValue instanceof Set) {\n throw new UnsupportedJsonValueError(\n `${subject} contains a ${childValue.constructor.name}${key ? ` (at \"${key}\")` : ''}, which JSON.stringify silently flattens to \"{}\" instead of serializing its entries — use a plain array or object instead.`,\n );\n }\n if (typeof childValue === 'number' && !Number.isFinite(childValue)) {\n throw new UnsupportedJsonValueError(\n `${subject} contains ${childValue}${key ? ` (at \"${key}\")` : ''}, which JSON.stringify silently converts to \"null\" instead of throwing — use a finite number instead.`,\n );\n }\n // A plain object property holding `undefined` is silently omitted by JSON.stringify —\n // matching production's own serialization, so it's not flagged (unlike an array\n // element, where `undefined` is converted to `null` instead of dropped).\n if (!wasRootCall && childValue === undefined && Array.isArray(this)) {\n throw new UnsupportedJsonValueError(\n `${subject} contains undefined inside an array (at index ${key}), which JSON.stringify silently converts to null instead of dropping it — use null explicitly instead.`,\n );\n }\n if (\n !wasRootCall &&\n (typeof childValue === 'function' || typeof childValue === 'symbol') &&\n Array.isArray(this)\n ) {\n throw new UnsupportedJsonValueError(\n `${subject} contains a ${typeof childValue} inside an array (at index ${key}), which JSON.stringify silently converts to null instead of dropping it — use null explicitly instead.`,\n );\n }\n if (\n !wasRootCall &&\n (typeof childValue === 'function' || typeof childValue === 'symbol') &&\n !Array.isArray(this)\n ) {\n throw new UnsupportedJsonValueError(\n `${subject} contains a ${typeof childValue} (at \"${key}\"), which JSON.stringify silently drops instead of serializing — use a plain JSON-compatible value instead.`,\n );\n }\n return childValue;\n });\n } catch (err) {\n if (err instanceof UnsupportedJsonValueError) {\n throw err;\n }\n throw new Error(\n `${subject} can't be serialized to JSON: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n if (serialized === undefined) {\n if (value !== undefined) {\n throw new Error(\n `${subject} is a ${typeof value} value, which JSON.stringify silently drops instead of serializing — use a plain JSON-compatible value instead.`,\n );\n }\n return undefined;\n }\n // Return the parsed-and-reserialized value, not the original — a caller serializing again\n // for the HTTP response (or the executeAction call) would otherwise invoke a custom toJSON() a second time.\n return JSON.parse(serialized);\n}\n\nfunction assertJsonSerializable(result: unknown, func: BackendFunction): unknown {\n return assertJsonRoundTrippable(result, `Local execution of \"${func.name}\"'s return value`);\n}\n\n/**\n * Test-only entry point: exercises `runScriptLocally`'s queue/execution behavior with priming\n * already done via `primedEntry`. Production goes through `executeColdActionLocally` instead, which\n * primes inside the same `enqueue()` call — kept separate so `primedEntry` keeps its current\n * meaning for the tests calling this directly.\n */\nexport async function executeScriptLocally(\n func: BackendFunction,\n projectRoot: string,\n args: unknown[],\n executeAction: ExecuteAction,\n getRuntimeContext: GetRuntimeContext,\n loadModule: LoadModule,\n log: Logger,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n primedEntry?: Record<string, unknown>,\n longPolling: LongPollingConfig = DEFAULT_LONG_POLLING_CONFIG,\n): Promise<BackendOutputs> {\n return enqueue(async () => {\n const runtimeContext = await getRuntimeContext();\n assertValidRuntimeContext(runtimeContext);\n return runScriptLocally(\n func,\n projectRoot,\n args,\n executeAction,\n runtimeContext,\n loadModule,\n log,\n timeoutMs,\n primedEntry,\n longPolling,\n );\n });\n}\n\n/**\n * Cold-function entry point: collects `allowedConnectionIds`, then primes and runs the entry in\n * one `enqueue()` call — priming runs real top-level code, so doing it outside the queue would let\n * two cold functions run in parallel. Connection IDs are collected first, executing no code, so a\n * banned import is rejected before the entry runs.\n */\nexport async function executeColdActionLocally(\n func: BackendFunction,\n projectRoot: string,\n args: unknown[],\n executeAction: ExecuteAction,\n getRuntimeContext: GetRuntimeContext,\n loadModule: LoadModule,\n getAllowedConnectionIds: (entryId: string) => Promise<string[]>,\n log: Logger,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n longPolling: LongPollingConfig = DEFAULT_LONG_POLLING_CONFIG,\n): Promise<BackendOutputs> {\n const displayName = `${func.relativePath}/${func.name}`;\n return enqueue(async () => {\n const runtimeContext = await getRuntimeContext();\n assertValidRuntimeContext(runtimeContext);\n // Each step needs its own timeout bound independent of runScriptLocally's, which only\n // starts once its body begins.\n const connectionIdsPromise = getAllowedConnectionIds(func.absolutePath);\n const allowedConnectionIds = await withTimeout(\n connectionIdsPromise,\n timeoutMs,\n `Resolving allowed connections for \"${displayName}\"`,\n );\n const entrySpecifier = func.absolutePath + LOCAL_EXECUTION_LOAD_SUFFIX;\n let primingEnvScope: EnvScopeHandle | undefined;\n const primingPromise = loadCustomerModuleEntry(\n loadModule,\n entrySpecifier,\n projectRoot,\n (handle) => {\n primingEnvScope = handle;\n },\n );\n let primedEntry: Record<string, unknown> | undefined;\n try {\n primedEntry = await withTimeout(primingPromise, timeoutMs, `Loading \"${displayName}\"`);\n } catch (err) {\n // A hung priming load's own runWithScopedEnv finally never runs, so this call abandons\n // just its own token — leaving any other, unrelated execution's still-active scope alone.\n primingEnvScope?.abandon();\n throw err;\n }\n // Calls runScriptLocally directly, not executeScriptLocally, to avoid enqueueing twice.\n return runScriptLocally(\n { ...func, allowedConnectionIds },\n projectRoot,\n args,\n executeAction,\n runtimeContext,\n loadModule,\n log,\n timeoutMs,\n primedEntry,\n longPolling,\n );\n });\n}\n\nasync function runScriptLocally(\n func: BackendFunction,\n projectRoot: string,\n args: unknown[],\n executeAction: ExecuteAction,\n runtimeContext: RuntimeContext,\n loadModule: LoadModule,\n log: Logger,\n timeoutMs: number,\n primedEntry: Record<string, unknown> | undefined,\n longPolling: LongPollingConfig,\n): Promise<BackendOutputs> {\n // Never log the args themselves — they may carry secrets/PII, matching dev-server.ts's cloud path.\n log.debug(`Executing \"${func.name}\" in-process with args`);\n\n const { actionCallTimeoutMs, totalExecutionTimeoutMs } = deriveActionTimeouts(longPolling);\n\n // A timed-out execution is abandoned, not canceled — its fn() may keep running, so isCurrent()\n // gates both its $.Actions closure and the shared adapters against acting under a stale identity.\n const scope = executionEpoch.start();\n\n // A long-poll can legitimately outlast timeoutMs — pausing the timer while a call is in flight\n // and restarting it once all settle keeps real progress from being penalized while a genuine\n // hang still times out normally.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let rejectTimeout: ((error: Error) => void) | undefined;\n let pendingActionCalls = 0;\n let absoluteTimeoutTimer: ReturnType<typeof setTimeout> | undefined;\n // Set once runBlocked's/runWithScopedEnv's own scope starts — undefined until then, so an\n // execution abandoned before it reaches that point has nothing to abandon here.\n let blockedScope: BlockedScopeHandle | undefined;\n let envScope: EnvScopeHandle | undefined;\n\n // Promise.race abandons a hung fn without cancelling it, so its runBlocked/runWithScopedEnv\n // scope's try/finally cleanup never runs. Both handles only discharge their own token, so this\n // is safe even while a different, still-legitimately-running execution holds its own scope —\n // unlike forceResetEnv(), neither call can clobber a scope it doesn't own.\n const abandonExecutionAndRejectWith = (error: Error) => {\n concludeExecution();\n blockedScope?.abandonIfCurrent();\n envScope?.abandon();\n rejectTimeout?.(error);\n };\n\n const scheduleTimeout = () => {\n timer = setTimeout(() => {\n abandonExecutionAndRejectWith(\n new Error(`Local execution of \"${func.name}\" timed out after ${timeoutMs}ms`),\n );\n }, timeoutMs);\n };\n\n // Re-armed (not just set once) from each new $.Actions call below, so a function making\n // several sequential calls — each within its own actionCallTimeoutMs — isn't killed for\n // exceeding a ceiling sized for only one of them.\n const rearmAbsoluteTimeout = () => {\n clearTimeout(absoluteTimeoutTimer);\n absoluteTimeoutTimer = setTimeout(() => {\n abandonExecutionAndRejectWith(\n new Error(\n `Local execution of \"${func.name}\" exceeded the absolute ${totalExecutionTimeoutMs}ms execution ceiling, regardless of any $.Actions call in flight.`,\n ),\n );\n }, totalExecutionTimeoutMs);\n };\n\n const guardedExecuteAction: ExecuteAction = async (fqn, inputs, connectionId) => {\n if (!scope.isCurrent()) {\n // Wording stays conclusion-neutral, not \"timed out\" — a concluded scope may have\n // ended for another reason.\n throw abandonedExecutionError(func.name, `run \"${fqn}\"`);\n }\n pendingActionCalls += 1;\n clearTimeout(timer);\n rearmAbsoluteTimeout();\n try {\n const actionCallPromise = executeAction(fqn, inputs, connectionId);\n return await withTimeout(\n actionCallPromise,\n actionCallTimeoutMs,\n `$.Actions call to \"${fqn}\"`,\n );\n } finally {\n pendingActionCalls -= 1;\n if (pendingActionCalls === 0 && scope.isCurrent()) {\n scheduleTimeout();\n }\n }\n };\n\n const concludeExecution = () => {\n scope.concludeIfCurrent();\n };\n\n // The preview response is the same context already available to cloud backend code, but it\n // belongs to a bootstrap invocation. The platform owns that context's safe-field contract;\n // this executor never merges its API/App keys or OAuth token. Target-invocation-owned values\n // are always replaced locally.\n const $: BackendGlobals = {\n ...runtimeContext,\n backendFunctionArgs: args,\n Actions: makeActionsProxy(guardedExecuteAction, func.allowedConnectionIds),\n };\n\n const dispatch: ExecutionDispatch = {\n executeAction: guardedExecuteAction,\n allowedConnectionIds: func.allowedConnectionIds,\n isAbandoned: () => !scope.isCurrent(),\n functionName: func.name,\n $,\n };\n\n const run = async (): Promise<BackendOutputs> => {\n // Wraps the whole body so a module-load failure also concludes the scope — otherwise\n // activeGeneration stays pinned to this execution until the next start() overwrites it.\n try {\n // Loads the module before installing $ and the SDK bridges, matching production's\n // ordering. A caller that already primed this entry passes the resolved module\n // directly, keeping loadModule's identity stable for the registration caches below.\n const mod =\n primedEntry ??\n (await loadCustomerModuleEntry(\n loadModule,\n func.absolutePath + LOCAL_EXECUTION_LOAD_SUFFIX,\n projectRoot,\n ));\n const fn = mod[func.name];\n if (typeof fn !== 'function') {\n throw new Error(\n `\"${func.name}\" is not a function exported from ${func.absolutePath}`,\n );\n }\n\n // Reinstalls the accessor if a prior execution's code deleted globalThis.$ — only\n // closes the gap between executions, not a mid-flight deletion by a concurrent one.\n ensureDollarAccessorInstalled();\n\n // Scopes globalThis.$ and the dispatch info to this call's own async continuation chain.\n return await backendGlobalsContext.run({ value: $ }, () =>\n executionDispatchContext.run(dispatch, async () => {\n const rejectIfAbandoned = () => {\n if (!scope.isCurrent()) {\n throw new Error(\n `Execution of \"${func.name}\" was abandoned after timing out before it could start.`,\n );\n }\n };\n // Checked again below — getNetworkGuard()'s and getEnvGuard()'s dynamic imports\n // can themselves take long enough (their first call in a process) for the\n // timeout to fire while they load, and the customer function must never run once\n // already abandoned.\n rejectIfAbandoned();\n // Nests runBlocked (network/subprocess) with runWithScopedEnv (process.env) for\n // the same window — independent globals, so nesting order doesn't matter.\n // assertJsonSerializable runs inside both, since a malicious result's\n // toJSON()/getter must run while access is still blocked/scoped.\n const networkGuardPromise = getNetworkGuard();\n const envGuardPromise = getEnvGuard();\n const customCredentialsPromise = resolveCustomCredentials(projectRoot);\n const [\n { runBlocked },\n { buildScopedEnv, runWithScopedEnv },\n customCredentials,\n ] = await Promise.all([\n networkGuardPromise,\n envGuardPromise,\n customCredentialsPromise,\n ]);\n rejectIfAbandoned();\n const scopedEnv = buildScopedEnv(customCredentials);\n const data = await runWithScopedEnv(\n scopedEnv,\n () =>\n runBlocked(\n async () => {\n // Both adapters are stable and idempotent to re-register.\n // Registered here, inside the same env/network scope as the\n // customer function itself, since their loadModule() calls\n // resolve real npm packages a customer project could declare,\n // whose top-level code would otherwise run with the real,\n // unscoped environment and network.\n const actionCatalogRegistration =\n registerActionCatalogIfInstalled(\n loadModule,\n projectRoot,\n timeoutMs,\n );\n const backendRuntimeRegistration =\n registerBackendRuntimeIfInstalled(\n loadModule,\n projectRoot,\n timeoutMs,\n );\n await Promise.all([\n actionCatalogRegistration,\n backendRuntimeRegistration,\n ]);\n // Registration's loadModule() calls can themselves take long\n // enough to cross the timeout — the customer function must\n // never run once already abandoned.\n rejectIfAbandoned();\n const result = await fn(...args);\n return assertJsonSerializable(result, func);\n },\n (handle) => {\n blockedScope = handle;\n },\n ),\n (handle) => {\n envScope = handle;\n },\n );\n return { data };\n }),\n );\n } finally {\n // However this execution ends, mark it concluded so any further dispatch through it — direct or via the shared adapters — is rejected.\n concludeExecution();\n }\n };\n\n const timeout = new Promise<never>((_resolve, reject) => {\n rejectTimeout = reject;\n scheduleTimeout();\n });\n\n rearmAbsoluteTimeout();\n\n // Racing the timeout only stops the caller from waiting — run() keeps executing afterward,\n // since true cancellation would require terminating a Worker thread.\n const runPromise = run();\n // Lets the handler below tell an abandoned rejection from an ordinary one.\n let raceSettled = false;\n // Nothing awaits runPromise once the timeout wins, so a later rejection would otherwise\n // crash as unhandled — logged instead so a slow real failure stays diagnosable.\n runPromise.catch((error: unknown) => {\n if (!raceSettled) {\n return;\n }\n const message = error instanceof Error ? error.message : String(error);\n log.debug(`\"${func.name}\" failed after its caller had already stopped waiting: ${message}`);\n });\n\n try {\n return await Promise.race([runPromise, timeout]);\n } finally {\n raceSettled = true;\n clearTimeout(timer);\n clearTimeout(absoluteTimeoutTimer);\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 no-await-in-loop */\n\nimport type { AuthOptionsWithDefaults, Logger } from '@dd/core/types';\nimport { randomUUID } from 'crypto';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { build } from 'vite';\n\nimport { AUTH_GUIDANCE } from '../auth';\nimport type { DoAuthenticatedRequest } from '../auth';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { ExecuteActionRequest, ExecuteActionResponse } from '../backend/protocol';\nimport type { BackendFunction, BackendOutputs } from '../backend/types';\nimport { generateDevVirtualEntryContent } from '../backend/virtual-entry';\nimport { DEV_VERIFY_MODE } from '../constants';\nimport type { LongPollingOptions } from '../types';\n\nimport { createBackendConnectionIdCollector } from './backend-connection-id-collector';\nimport { createBackendStaticChecksPlugin } from './backend-static-checks-plugin';\nimport { getBaseBackendBuildConfig } from './build-config';\nimport type { ExecuteAction, GetRuntimeContext, LoadModule } from './local-execution';\nimport { DEFAULT_TIMEOUT_MS, executeColdActionLocally } from './local-execution';\nimport { getMaxRetryDelayMs } from './retry-delay';\n\ninterface BundleResult {\n func: BackendFunction;\n code: string;\n}\n\ntype BundleFn = (func: BackendFunction) => Promise<BundleResult>;\n\nconst DEV_VIRTUAL_PREFIX = 'virtual:dd-backend-dev:';\n\ntype AuthConfig = AuthOptionsWithDefaults;\ntype LongPollingConfig = Required<LongPollingOptions>;\n\nconst RUNTIME_CONTEXT_SCRIPT = `export async function main($) {\n return $;\n}`;\nconst RUNTIME_CONTEXT_DISPLAY_NAME = 'Datadog Apps local runtime context';\nconst RUNTIME_CONTEXT_TIMEOUT_MS = 60_000;\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n if (signal?.aborted) {\n onAbort();\n }\n });\n}\n\n// Structural check: the rejection is a DOMException from undici's realm, so\n// `instanceof` fails across realms (vm contexts, Jest).\nfunction isAbortError(error: unknown): boolean {\n if (error === null || typeof error !== 'object' || !('name' in error)) {\n return false;\n }\n\n return error.name === 'TimeoutError' || error.name === 'AbortError';\n}\n\n// Equal jitter (half fixed, half random) so the delay keeps a floor.\nexport function getRetryDelay(attempt: number, config: LongPollingConfig): number {\n const backoffDelay = getMaxRetryDelayMs(attempt, config.exponentialBackoff);\n\n return config.jitter ? backoffDelay / 2 + Math.random() * (backoffDelay / 2) : backoffDelay;\n}\n\n/**\n * Format a BackendFunction for display in log/error messages.\n */\nfunction formatRef(func: BackendFunction): string {\n return `${func.relativePath}/${func.name}`;\n}\n\n/**\n * Parse JSON body from an incoming request stream.\n */\nfunction parseRequestBody(req: IncomingMessage): Promise<ExecuteActionRequest> {\n return new Promise((resolve, reject) => {\n let body = '';\n req.on('data', (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on('end', () => {\n try {\n resolve(JSON.parse(body));\n } catch {\n reject(new Error('Invalid JSON body'));\n }\n });\n req.on('error', reject);\n });\n}\n\n/**\n * Bundle a backend function using Vite's build API (Rollup under the hood).\n * Uses write: false to produce an in-memory bundle with no temp files.\n */\nasync function bundleBackendFunction(\n viteBuild: typeof build,\n func: BackendFunction,\n projectRoot: string,\n log: Logger,\n): Promise<BundleResult> {\n const displayName = formatRef(func);\n const virtualId = `${DEV_VIRTUAL_PREFIX}${displayName}`;\n const virtualContent = generateDevVirtualEntryContent(\n func.name,\n func.absolutePath,\n projectRoot,\n );\n const connectionIdCollector = createBackendConnectionIdCollector(\n func.absolutePath,\n projectRoot,\n );\n\n log.debug(`Bundling backend function \"${displayName}\" from ${func.absolutePath}`);\n\n const staticChecksPlugin = createBackendStaticChecksPlugin(\n projectRoot,\n log,\n connectionIdCollector.getModuleRecords,\n );\n const baseConfig = getBaseBackendBuildConfig(projectRoot, { [virtualId]: virtualContent }, [\n connectionIdCollector.plugin,\n staticChecksPlugin,\n ]);\n\n // Dev: build a single function in-memory per request so we can send the\n // bundled script to the Datadog API without writing temp files.\n // Uses a plain \"virtual:\" prefix instead of \\0 because Rollup generates\n // empty chunks when \\0-prefixed IDs are used as input entries.\n const result = await viteBuild({\n ...baseConfig,\n build: {\n ...baseConfig.build,\n write: false,\n rollupOptions: {\n ...baseConfig.build.rollupOptions,\n input: virtualId,\n output: baseConfig.build.rollupOptions.output,\n },\n },\n });\n\n const output = Array.isArray(result) ? result[0] : result;\n\n if (!('output' in output)) {\n throw new Error(`Unexpected vite.build result for \"${displayName}\"`);\n }\n\n const code = output.output[0].type === 'chunk' ? output.output[0].code : '';\n const enrichedFunc = {\n ...func,\n allowedConnectionIds: connectionIdCollector.getAllowedConnectionIds(),\n };\n\n log.debug(`Bundled \"${displayName}\" (${code.length} bytes)`);\n\n return { func: enrichedFunc, code };\n}\n\n/**\n * Submits a query to Datadog's `preview-async` endpoint and long-polls until it resolves,\n * returning the raw `outputs`. `querySpec` is either the `jsFunctionWithActions` wrapper or\n * a single action's `{fqn, inputs}` — `submitQuery` doesn't care which.\n */\nasync function submitQuery(\n querySpec: Record<string, unknown>,\n displayName: string,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n signal?: AbortSignal,\n): Promise<unknown> {\n const endpoint = `https://api.${auth.site}/api/v2/app-builder/queries/preview-async`;\n\n log.debug(`Calling Datadog API: ${endpoint}`);\n\n const body = JSON.stringify({\n data: {\n type: 'queries',\n attributes: {\n query: {\n id: randomUUID(),\n name: displayName,\n type: 'action',\n properties: {\n spec: querySpec,\n onlyTriggerManually: true,\n },\n },\n template_params: {},\n },\n },\n });\n\n const initialResult = await doAuthenticatedRequest<{ data?: { id?: string } }>({\n url: endpoint,\n method: 'POST',\n type: 'json',\n signal,\n getData: () => ({\n data: body,\n headers: { 'Content-Type': 'application/json' },\n }),\n });\n\n const receiptId = initialResult.data?.id;\n\n if (!receiptId) {\n throw new Error('No receipt ID returned from Datadog API');\n }\n\n log.debug(`Query execution started with receipt: ${receiptId}`);\n\n return pollQueryExecution(receiptId, auth, doAuthenticatedRequest, longPolling, log, signal);\n}\n\n/** Executes a script via Datadog's app-builder queries API — the production round trip, wrapping the whole script as a `jsFunctionWithActions` query. */\nasync function executeScriptViaDatadog(\n scriptBody: string,\n func: BackendFunction,\n args: unknown[],\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n): Promise<BackendOutputs> {\n const displayName = formatRef(func);\n\n const outputs = await submitQuery(\n {\n fqn: 'com.datadoghq.datatransformation.jsFunctionWithActions',\n inputs: {\n script: scriptBody,\n allowedConnectionIds: func.allowedConnectionIds,\n context: { backendFunctionArgs: args },\n },\n },\n displayName,\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n\n if (typeof outputs !== 'object' || outputs === null || !('data' in outputs)) {\n throw new Error('Query execution completed without a \"data\" field in its outputs');\n }\n return outputs;\n}\n\n/**\n * Resolves the serializable `$` context exposed by an authenticated preview execution. The\n * platform response is deliberately kept opaque here; local-execution validates the identity\n * fields it needs before loading customer code and overlays invocation-owned fields locally.\n */\nfunction makeGetRuntimeContextRemotely(\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n): GetRuntimeContext {\n return async () => {\n const controller = new AbortController();\n const timeoutError = new Error(\n `Runtime context hydration timed out after ${RUNTIME_CONTEXT_TIMEOUT_MS}ms`,\n );\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => {\n controller.abort(timeoutError);\n reject(timeoutError);\n }, RUNTIME_CONTEXT_TIMEOUT_MS);\n });\n try {\n // The request signal cancels active fetches and our own retry delays. Racing the whole\n // operation also releases the local-execution queue if doRequest is already sleeping\n // inside async-retry, whose backoff timer does not observe AbortSignal. Promise.race\n // keeps observing submitQuery's eventual settlement after the deadline wins.\n const outputs = await Promise.race([\n submitQuery(\n {\n fqn: 'com.datadoghq.datatransformation.jsFunctionWithActions',\n inputs: {\n script: RUNTIME_CONTEXT_SCRIPT,\n allowedConnectionIds: [],\n context: {},\n },\n },\n RUNTIME_CONTEXT_DISPLAY_NAME,\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n controller.signal,\n ),\n deadline,\n ]);\n\n if (typeof outputs !== 'object' || outputs === null || !('data' in outputs)) {\n throw new Error(\n 'Runtime context hydration completed without a \"data\" field in its outputs',\n );\n }\n return outputs.data;\n } catch (error: unknown) {\n if (controller.signal.aborted) {\n throw controller.signal.reason;\n }\n throw error;\n } finally {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n }\n };\n}\n\n/** Submits a single-action `preview-async` query per `$.Actions` call and logs its result/error, since production's equivalent signal never reaches the `npm run dev` console. Callers must have already confirmed auth is configured (see `createDevServerMiddleware`). */\nfunction makeExecuteActionRemotely(\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n): ExecuteAction {\n return async (\n fqn: string,\n inputs: unknown,\n connectionId: string | undefined,\n ): Promise<unknown> => {\n try {\n const result = await submitQuery(\n connectionId !== undefined ? { fqn, inputs, connectionId } : { fqn, inputs },\n fqn,\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n log.info(`$.Actions call to \"${fqn}\" succeeded: ${JSON.stringify(result)}`);\n return result;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n log.error(`$.Actions call to \"${fqn}\" failed: ${message}`);\n throw error;\n }\n };\n}\n\ninterface PollResult {\n data?: { attributes?: { done?: boolean; outputs?: unknown } };\n errors?: Array<{ detail?: string; title?: string }>;\n}\n\n/**\n * Long-polls until a submitted query completes or times out, returning the raw `outputs` —\n * shape varies by query type, so callers interpret it. The server holds each poll open ~30s\n * and responds `done: false` on timeout; this loop only handles that re-polling, since\n * `doRequest` already retries transient HTTP failures.\n */\nasync function pollQueryExecution(\n receiptId: string,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n signal?: AbortSignal,\n): Promise<unknown> {\n const endpoint = `https://api.${auth.site}/api/v2/app-builder/queries/execution-long-polling/${receiptId}`;\n const { maxRetries, timeoutMs } = longPolling;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n if (attempt > 0) {\n const retryDelay = getRetryDelay(attempt, longPolling);\n log.debug(`Waiting ${Math.round(retryDelay)}ms before long-poll retry...`);\n await delay(retryDelay, signal);\n }\n\n log.debug(`Long-poll attempt ${attempt + 1}/${maxRetries}...`);\n\n let result: PollResult;\n try {\n const attemptTimeoutSignal = AbortSignal.timeout(timeoutMs);\n const requestSignal = signal\n ? AbortSignal.any([signal, attemptTimeoutSignal])\n : attemptTimeoutSignal;\n result = await doAuthenticatedRequest<PollResult>({\n url: endpoint,\n type: 'json',\n // Bounds the whole call, doRequest's internal retries included.\n signal: requestSignal,\n });\n } catch (error: unknown) {\n if (signal?.aborted) {\n throw signal.reason;\n }\n // A stall is recoverable: the receipt stays valid, so poll again.\n if (!isAbortError(error)) {\n throw error;\n }\n log.debug(`Long-poll attempt ${attempt + 1} timed out after ${timeoutMs}ms`);\n continue;\n }\n\n // Check for error responses.\n if (result.errors?.length) {\n const details = result.errors.map((e) => e.detail || e.title).join('; ');\n throw new Error(`Query execution failed: ${details}`);\n }\n\n const attrs = result.data?.attributes;\n log.debug(`Long-poll response, done: ${attrs?.done}`);\n\n if (attrs?.done) {\n if (attrs.outputs === undefined || attrs.outputs === null) {\n throw new Error('Query execution completed without outputs');\n }\n return attrs.outputs;\n }\n\n // `done: false` means the server-side window expired; retry.\n }\n\n throw new Error('Query execution timed out');\n}\n\n/**\n * Send a JSON error response.\n */\nfunction sendError(res: ServerResponse, statusCode: number, message: string): void {\n res.statusCode = statusCode;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ success: false, error: message } satisfies ExecuteActionResponse));\n}\n\n/**\n * Send a JSON success response.\n */\nfunction sendSuccess(res: ServerResponse, result: { data: unknown }): void {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ success: true, result } satisfies ExecuteActionResponse));\n}\n\n/**\n * Runs `run` only once auth is configured, matching production's auth-before-execution\n * ordering — checked upfront, not lazily inside a $.Actions call, so a function that never\n * calls $.Actions isn't a loophole. A local presence check only, adding no latency.\n */\nfunction guardAuthenticated(\n res: ServerResponse,\n doAuthenticatedRequest: DoAuthenticatedRequest | undefined,\n run: (doAuthenticatedRequest: DoAuthenticatedRequest) => Promise<void>,\n): void {\n if (!doAuthenticatedRequest) {\n sendError(res, 400, `Auth credentials not configured. ${AUTH_GUIDANCE}`);\n return;\n }\n run(doAuthenticatedRequest).catch(() => sendError(res, 500, 'Unexpected error'));\n}\n\n/** Shared catch-block shape for every handler below: an `HttpError` carries its own status code, anything else is a 500. `label` is omitted for handlers with no `log` in scope. */\nfunction handleHttpError(res: ServerResponse, error: unknown, log?: Logger, label?: string): void {\n const statusCode = error instanceof HttpError ? error.statusCode : 500;\n const message = error instanceof Error ? error.message : 'Internal server error';\n if (log && label) {\n log.debug(`Error handling ${label}: ${message}`);\n }\n sendError(res, statusCode, message);\n}\n\nclass HttpError extends Error {\n constructor(\n public statusCode: number,\n message: string,\n ) {\n super(message);\n }\n}\n\n/**\n * Split out from `validateAndBundle` so `handleExecuteAction`'s no-bundling local path can\n * reuse the same parse-and-lookup step without pulling in a bundle.\n */\nasync function parseAndLookupFunction(\n req: IncomingMessage,\n functionsByName: Map<string, BackendFunction>,\n): Promise<{ func: BackendFunction; args: unknown[] }> {\n const { functionName, args = [] } = await parseRequestBody(req);\n\n if (!functionName || typeof functionName !== 'string') {\n throw new HttpError(400, 'Missing or invalid functionName');\n }\n\n const func = functionsByName.get(functionName);\n if (!func) {\n throw new HttpError(404, `Backend function \"${functionName}\" not found`);\n }\n\n return { func, args };\n}\n\n/**\n * Shared by `handleDebugBundle` and `handleExecuteActionViaCloud` — the two handlers that\n * still need a bundle; `handleExecuteAction`'s no-bundling path calls `parseAndLookupFunction`\n * directly instead.\n */\nasync function validateAndBundle(\n req: IncomingMessage,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n): Promise<{ func: BackendFunction; code: string; args: unknown[] }> {\n const { func, args } = await parseAndLookupFunction(req, functionsByName);\n const bundled = await bundle(func);\n return { ...bundled, args };\n}\n\n/**\n * Handle POST /__dd/debugBundle — returns the bundled script for inspection.\n */\nasync function handleDebugBundle(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n): Promise<void> {\n try {\n const { code } = await validateAndBundle(req, functionsByName, bundle);\n\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/plain');\n res.end(code);\n } catch (error: unknown) {\n handleHttpError(res, error);\n }\n}\n\n/**\n * Handles POST /__dd/executeAction — imports a backend function's real file and executes\n * it in-process (see local-execution.ts), with no bundling. Auth is checked upfront by the\n * caller in `createDevServerMiddleware`, matching production's auth-before-execution ordering.\n */\nasync function handleExecuteAction(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n loadModule: LoadModule,\n getAllowedConnectionIds: (entryId: string) => Promise<string[]>,\n projectRoot: string,\n log: Logger,\n): Promise<void> {\n try {\n const { func, args } = await parseAndLookupFunction(req, functionsByName);\n const displayName = formatRef(func);\n\n log.debug(`Executing action locally: ${displayName} with args`);\n\n // Priming and connection-ID collection must happen inside the same serialization\n // boundary as execution — see executeColdActionLocally's doc comment for why.\n const executeAction = makeExecuteActionRemotely(\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n const getRuntimeContext = makeGetRuntimeContextRemotely(\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n const result = await executeColdActionLocally(\n func,\n projectRoot,\n args,\n executeAction,\n getRuntimeContext,\n loadModule,\n getAllowedConnectionIds,\n log,\n DEFAULT_TIMEOUT_MS,\n longPolling,\n );\n\n sendSuccess(res, result);\n } catch (error: unknown) {\n handleHttpError(res, error, log, 'executeAction');\n }\n}\n\n/** Handle POST /__dd/executeActionViaCloud: bundle and execute via the production round trip (queue + Deno subprocess). */\nasync function handleExecuteActionViaCloud(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest,\n longPolling: LongPollingConfig,\n log: Logger,\n): Promise<void> {\n try {\n const { func, code, args } = await validateAndBundle(req, functionsByName, bundle);\n const displayName = formatRef(func);\n\n log.debug(`Executing action via cloud: ${displayName} with args`);\n\n const result = await executeScriptViaDatadog(\n code,\n func,\n args,\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n\n sendSuccess(res, result);\n } catch (error: unknown) {\n // Labeled by the actual URL hit, not a fixed name, since dev-verify mode also reaches this via /__dd/executeAction.\n handleHttpError(res, error, log, req.url ?? 'executeActionViaCloud');\n }\n}\n\n/** Shared by both routes that reach the cloud round trip, so a fix to auth-checking or error handling can't drift between them. */\nfunction routeToCloudHandler(\n req: IncomingMessage,\n res: ServerResponse,\n functionsByName: Map<string, BackendFunction>,\n bundle: BundleFn,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest | undefined,\n longPolling: LongPollingConfig,\n log: Logger,\n): void {\n guardAuthenticated(res, doAuthenticatedRequest, (authedRequest) =>\n handleExecuteActionViaCloud(\n req,\n res,\n functionsByName,\n bundle,\n auth,\n authedRequest,\n longPolling,\n log,\n ),\n );\n}\n\n/**\n * Build a lookup map from encoded query names to BackendFunction objects.\n */\nfunction buildFunctionMap(backendFunctions: BackendFunction[]): Map<string, BackendFunction> {\n return new Map(backendFunctions.map((f) => [encodeQueryName(f), f]));\n}\n\n/**\n * Connect-compatible middleware intercepting backend function requests for the Vite dev server.\n * The lookup map rebuilds on each request via `getBackendFunctions()` so renamed/removed\n * functions are reflected without restarting the server.\n */\nexport function createDevServerMiddleware(\n viteBuild: typeof build,\n loadModule: LoadModule,\n getBackendFunctions: () => BackendFunction[],\n getAllowedConnectionIds: (entryId: string) => Promise<string[]>,\n auth: AuthConfig,\n doAuthenticatedRequest: DoAuthenticatedRequest | undefined,\n longPolling: LongPollingConfig,\n projectRoot: string,\n log: Logger,\n mode: string,\n): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {\n const bundle = (func: BackendFunction) =>\n bundleBackendFunction(viteBuild, func, projectRoot, log);\n const isDevVerifyMode = mode === DEV_VERIFY_MODE;\n\n const initialFunctions = getBackendFunctions();\n if (initialFunctions.length > 0) {\n log.info(\n `Dev server middleware active for ${initialFunctions.length} backend function(s): ${initialFunctions.map((f) => f.name).join(', ')}`,\n );\n }\n\n return (req: IncomingMessage, res: ServerResponse, next: () => void) => {\n if (req.method !== 'POST') {\n next();\n return;\n }\n\n const functionsByName = buildFunctionMap(getBackendFunctions());\n\n if (req.url === '/__dd/debugBundle') {\n handleDebugBundle(req, res, functionsByName, bundle).catch(() => {\n sendError(res, 500, 'Unexpected error');\n });\n } else if (\n req.url === '/__dd/executeActionViaCloud' ||\n (req.url === '/__dd/executeAction' && isDevVerifyMode)\n ) {\n // The client always POSTs to /__dd/executeAction regardless of mode, so dev-verify is routed here server-side instead.\n routeToCloudHandler(\n req,\n res,\n functionsByName,\n bundle,\n auth,\n doAuthenticatedRequest,\n longPolling,\n log,\n );\n } else if (req.url === '/__dd/executeAction') {\n guardAuthenticated(res, doAuthenticatedRequest, (authedRequest) =>\n handleExecuteAction(\n req,\n res,\n functionsByName,\n auth,\n authedRequest,\n longPolling,\n loadModule,\n getAllowedConnectionIds,\n projectRoot,\n log,\n ),\n );\n } else {\n next();\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 { rm } from '@dd/core/helpers/fs';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\nimport type { build } from 'vite';\n\nimport {\n AUTH_GUIDANCE,\n getAuthenticatedRequest,\n MissingAuthenticationError,\n type DoAuthenticatedRequest,\n} from '../auth';\nimport { extractExportedFunctions } from '../backend/ast-parsing/extract-backend-functions';\nimport { extractConnectionIdsFromModuleGraph } from '../backend/ast-parsing/extract-connection-ids-from-module-graph';\nimport { shouldTraverseCollectedModule } from '../backend/ast-parsing/module-graph';\nimport { analyzeModuleScope } from '../backend/ast-parsing/module-scope';\nimport { runBackendStaticChecks } from '../backend/ast-parsing/run-backend-static-checks';\nimport { ensureProgram } from '../backend/ast-parsing/type-guards';\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport { generateProxyModule } from '../backend/proxy-codegen';\nimport type { BackendFunction } from '../backend/types';\nimport {\n BACKEND_FILE_RE,\n BACKEND_FILE_WITH_QUERY_RE,\n LOCAL_EXECUTION_LOAD_SUFFIX,\n PLUGIN_NAME,\n} from '../constants';\nimport type { AppsOptionsWithDefaults } from '../types';\n\nimport { buildBackendFunctions } from './build-backend-functions';\nimport { buildAppPackage } from './build-package';\nimport { CUSTOM_CREDENTIALS_LOCAL_FILENAME } from './custom-credentials-resolver';\nimport { collectModuleGraphFromServer } from './dev-server-module-graph';\nimport { createDevServerMiddleware } from './dev-server';\nimport { localExecutionResolutionContext } from './local-execution';\n\nexport type ViteBundler = {\n build: typeof build;\n};\n\nexport interface VitePluginOptions {\n bundler: ViteBundler;\n context: GlobalContext;\n options: AppsOptionsWithDefaults;\n}\n\n/**\n * Build BackendFunction entries from discovered export names and generate\n * the frontend proxy module that replaces the original backend code.\n */\nfunction buildProxyModule(\n exportNames: string[],\n id: string,\n buildRoot: string,\n): { functions: BackendFunction[]; proxyCode: string } {\n const relativePath = path.relative(buildRoot, id);\n const refPath = relativePath.replace(BACKEND_FILE_RE, '');\n\n const functions: BackendFunction[] = [];\n const proxyExports: Array<{ exportName: string; queryName: string }> = [];\n\n for (const exportName of exportNames) {\n const func = {\n relativePath: refPath,\n name: exportName,\n absolutePath: id,\n allowedConnectionIds: [],\n };\n functions.push(func);\n proxyExports.push({ exportName, queryName: encodeQueryName(func) });\n }\n\n return { functions, proxyCode: generateProxyModule(proxyExports) };\n}\n\n/**\n * Create a registry for tracking discovered backend functions.\n * Uses a Map keyed by entryPath so that re-transforms (e.g. during HMR)\n * replace stale entries for a file instead of appending duplicates.\n */\nfunction createBackendFunctionRegistry() {\n const functionsByEntryPath = new Map<string, BackendFunction[]>();\n\n return {\n /** Replace all entries for a given file. Handles HMR re-transforms. */\n setBackendFunctions(entryPath: string, functions: BackendFunction[]) {\n functionsByEntryPath.set(entryPath, functions);\n },\n /** Get a flat array of all currently registered backend functions. */\n getBackendFunctions(): BackendFunction[] {\n return Array.from(functionsByEntryPath.values()).flat();\n },\n };\n}\n\nconst APPS_RUNTIME_PATH = path.join(__dirname, './apps-runtime.mjs');\n\n// Not exported by Vite; mirrors its server.fs.deny default so it can be spread in below.\nexport const VITE_DEFAULT_SERVER_FS_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];\n\n/**\n * Returns the Vite-specific plugin hooks for the apps plugin.\n *\n * Transform: discovers backend exports and connection allowlists, registers\n * backend functions, and replaces each backend module with its frontend proxy.\n *\n * Production (closeBundle): builds backend functions (if any) then writes the\n * deployable package without resolving authentication or performing requests.\n\n * Dev (configureServer): registers middleware for local backend function\n * testing when auth credentials are available.\n */\nexport const getVitePlugin = ({\n bundler,\n context,\n options,\n}: VitePluginOptions): PluginOptions['vite'] => {\n const log = context.getLogger(PLUGIN_NAME);\n const { auth } = context;\n\n context.inject({\n type: 'file',\n position: InjectPosition.MIDDLE,\n value: APPS_RUNTIME_PATH,\n });\n\n const { setBackendFunctions, getBackendFunctions } = createBackendFunctionRegistry();\n\n // Vite 6 invokes closeBundle when a dev server's plugin container closes,\n // not only for production builds. configureServer only runs for dev\n // servers, so use it to mark the session and skip packaging there — a\n // dev exit must not rebuild backend functions or replace the production\n // package with dev-session-derived output.\n let devServerActive = false;\n\n return {\n // @datadog/apps-backend and @datadog/action-catalog ship ESM-only, but ssrLoadModule\n // externalizes node_modules by default (a plain require()), which throws \"Cannot use\n // import statement outside a module\" — ssr.noExternal forces Vite's SSR transform instead.\n config() {\n return {\n ssr: {\n noExternal: ['@datadog/apps-backend', '@datadog/action-catalog'],\n },\n // Vite replaces its whole server.fs.deny default rather than merging with a\n // plugin's own list, so the defaults above must be spread in here or dev-server\n // protection for .env/.git/certs silently disappears once this filename is added.\n server: {\n fs: {\n deny: [...VITE_DEFAULT_SERVER_FS_DENY, CUSTOM_CREDENTIALS_LOCAL_FILENAME],\n },\n },\n };\n },\n // Propagates LOCAL_EXECUTION_LOAD_SUFFIX through the backend-file dependency graph so a\n // nested `.backend.ts` import isn't replaced with the frontend proxy stub. Every subgraph\n // module gets its own suffixed id, since Vite otherwise shares one cached id across callers.\n resolveId: {\n // Must run before Vite's built-in resolver ('pre'): a plain relative specifier like\n // `./other.backend` is otherwise fully resolved by Vite's own filesystem resolution\n // first, short-circuiting the hook chain before this plugin ever sees it.\n order: 'pre',\n async handler(source, importer, resolveOptions) {\n // Strips the query/hash suffix before comparing, matching Vite's own postfixRE —\n // otherwise a `?raw`/`#fragment`-suffixed import bypasses this check and Vite\n // inlines the real secret into a chunk build-package.ts's filter never sees.\n const sourceWithoutPostfix = source.replace(/[?#].*$/, '');\n if (\n path.basename(sourceWithoutPostfix).toLowerCase() ===\n CUSTOM_CREDENTIALS_LOCAL_FILENAME\n ) {\n throw new Error(\n `${CUSTOM_CREDENTIALS_LOCAL_FILENAME} cannot be imported directly — read Custom Credentials via process.env instead.`,\n );\n }\n\n // Top-level guard (not folded into each branch) so any future branch added below\n // inherits it automatically: local execution's traversal is always SSR, so without\n // this a client-mode resolution could inherit the marker and leak real backend code.\n if (resolveOptions.ssr !== true) {\n return null;\n }\n\n // The other half of the scoping: the store is only populated while a local\n // execution's own loadModule call is in flight (see configureServer), so an\n // unrelated SSR resolution never inherits a marker from an earlier execution.\n const subgraphImporters = localExecutionResolutionContext.getStore();\n const isPartOfSuffixedSubgraph =\n !!importer &&\n (importer.endsWith(LOCAL_EXECUTION_LOAD_SUFFIX) ||\n (!!subgraphImporters && subgraphImporters.has(importer)));\n if (!isPartOfSuffixedSubgraph) {\n return null;\n }\n\n const resolved = await this.resolve(source, importer, {\n ...resolveOptions,\n skipSelf: true,\n });\n if (!resolved || resolved.external) {\n return resolved;\n }\n\n if (resolved.id.endsWith(LOCAL_EXECUTION_LOAD_SUFFIX)) {\n return resolved;\n }\n\n // Only app-local source gets a distinct local-execution identity — an SDK/package\n // import must resolve to the same module Vite otherwise caches for it, since an\n // unrecognized query on a node_modules id can break Vite's optimizeDeps handling.\n if (!shouldTraverseCollectedModule(resolved.id, context.buildRoot)) {\n return resolved;\n }\n\n const suffixedId = resolved.id + LOCAL_EXECUTION_LOAD_SUFFIX;\n if (!BACKEND_FILE_RE.test(resolved.id)) {\n subgraphImporters?.add(suffixedId);\n }\n return { ...resolved, id: suffixedId };\n },\n },\n transform: {\n filter: {\n id: {\n include: [BACKEND_FILE_WITH_QUERY_RE],\n exclude: [/node_modules/, /[/\\\\]dist[/\\\\]/],\n },\n },\n // For each .backend.* file, parse its named exports, register\n // them as backend functions, and replace the module with a\n // frontend proxy that calls executeBackendFunction at runtime.\n handler(code, id, transformOptions) {\n if (id.endsWith(LOCAL_EXECUTION_LOAD_SUFFIX) && transformOptions?.ssr) {\n // Local execution needs the real function body, not the proxy stub below — real loads always go through ssrLoadModule, which runs in SSR, so this only fires for that legitimate path.\n return null;\n }\n // Any other case (no query, a spoofed client-side import reusing the suffix, or an unrecognized query) falls through to the safe proxy-stub generation below. Strip the query first so it registers under the file's real (unsuffixed) relativePath/query-name, not a duplicate.\n const queryIndex = id.indexOf('?');\n const normalizedId = queryIndex === -1 ? id : id.slice(0, queryIndex);\n\n const ast = this.parse(code);\n const program = ensureProgram(ast, normalizedId);\n // Shared so the checks below don't each independently re-walk the same AST to build the same scope graph.\n const scopeAnalysis = analyzeModuleScope(program);\n // Runs even for a file with zero exports, to catch a banned import/global as soon as it's written.\n runBackendStaticChecks(ast, normalizedId, log, scopeAnalysis);\n const exportNames = extractExportedFunctions(ast, normalizedId);\n if (exportNames.length === 0) {\n // Only a genuinely no-query id can be trusted as a real re-transform of this\n // exact file's own source. Vite's own `?raw`/`?url`/`?worker` load hooks all\n // produce a default export, which enumerateBackendExports already rejects\n // with a loud throw before this branch is reached — but some other\n // query-bearing load producing zero-export content isn't ruled out, and\n // clearing the registry for that case would silently and permanently break\n // the file's real (unsuffixed) registration until a file edit or server\n // restart, over an import that never touched its real source.\n if (queryIndex === -1) {\n log.warn(\n `Backend file ${normalizedId} has no exported functions. ` +\n `Did you forget to add a named export?`,\n );\n // Clear any previously registered functions for this file\n // so stale entries don't persist across HMR re-transforms.\n setBackendFunctions(normalizedId, []);\n }\n return { code: '', map: null };\n }\n\n const { functions, proxyCode } = buildProxyModule(\n exportNames,\n normalizedId,\n context.buildRoot,\n );\n setBackendFunctions(normalizedId, functions);\n log.debug(`Generated proxy for ${normalizedId} with ${functions.length} export(s)`);\n\n return { code: proxyCode, map: null };\n },\n },\n async closeBundle() {\n if (devServerActive) {\n log.debug('Skipping app packaging: dev server session.');\n return;\n }\n let backendOutDir: string | undefined;\n let backendOutputs = new Map<string, string>();\n let backendFunctions = getBackendFunctions();\n if (backendFunctions.length > 0) {\n const result = await buildBackendFunctions(\n bundler.build,\n backendFunctions,\n context.buildRoot,\n log,\n );\n backendOutDir = result.outDir;\n backendOutputs = result.outputs;\n backendFunctions = result.functions;\n }\n try {\n await buildAppPackage({\n backendOutputs,\n backendFunctions,\n context,\n options,\n });\n } finally {\n if (backendOutDir) {\n await rm(backendOutDir);\n }\n }\n },\n configureServer(server) {\n devServerActive = true;\n let doAuthenticatedRequest: DoAuthenticatedRequest | undefined;\n try {\n doAuthenticatedRequest = getAuthenticatedRequest();\n } catch (error) {\n if (!(error instanceof MissingAuthenticationError)) {\n throw error;\n }\n log.warn(\n `No authentication configured. Both the /__dd/executeAction and /__dd/executeActionViaCloud endpoints will be unavailable. ${AUTH_GUIDANCE}`,\n );\n }\n\n const loadModule = server.ssrLoadModule.bind(server);\n // Safe to call before `loadModule` runs anything: collectModuleGraphFromServer primes\n // each node itself via `transformRequest`, since `moduleParsed` (production's\n // mechanism) is Rollup-build-only and never fires on a real dev server.\n const getAllowedConnectionIds = async (entryId: string) => {\n const moduleGraph = await collectModuleGraphFromServer(\n server,\n entryId,\n context.buildRoot,\n log,\n );\n return extractConnectionIdsFromModuleGraph(entryId, moduleGraph, context.buildRoot);\n };\n const middleware = createDevServerMiddleware(\n bundler.build,\n loadModule,\n getBackendFunctions,\n getAllowedConnectionIds,\n auth,\n doAuthenticatedRequest,\n options.longPolling,\n context.buildRoot,\n log,\n server.config.mode,\n );\n server.middlewares.use(middleware);\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 { rm } from '@dd/core/helpers/fs';\nimport type { Logger } from '@dd/core/types';\nimport { mkdtemp } from 'fs/promises';\nimport { tmpdir } from 'os';\nimport path from 'path';\nimport type { build } from 'vite';\n\nimport { encodeQueryName } from '../backend/encodeQueryName';\nimport type { BackendFunction } from '../backend/types';\nimport { generateVirtualEntryContent } from '../backend/virtual-entry';\n\nimport { createBackendConnectionIdCollector } from './backend-connection-id-collector';\nimport { createBackendStaticChecksPlugin } from './backend-static-checks-plugin';\nimport { getBaseBackendBuildConfig } from './build-config';\n\nconst VIRTUAL_PREFIX = '\\0dd-backend:';\n\n/**\n * Build all backend functions using a separate vite.build() call.\n * Produces one standalone JS file per function in a temp directory.\n *\n * Each bundle filename is the encoded query name (`{hash(path)}.{name}.js`)\n * for the flat backend/ directory in the ZIP.\n */\nexport async function buildBackendFunctions(\n viteBuild: typeof build,\n functions: BackendFunction[],\n buildRoot: string,\n log: Logger,\n): Promise<{ outDir: string; outputs: Map<string, string>; functions: BackendFunction[] }> {\n const outDir = await mkdtemp(path.join(tmpdir(), 'dd-apps-backend-'));\n const outputs = new Map<string, string>();\n const allowedConnectionIdsByEntryPath = new Map<string, string[]>();\n\n log.debug(`Building ${functions.length} backend function(s) via vite.build()`);\n\n try {\n // Build each function individually so that each output is a single self-contained JS file.\n for (const func of functions) {\n const bundleName = encodeQueryName(func);\n const virtualId = `${VIRTUAL_PREFIX}${bundleName}`;\n const virtualContent = generateVirtualEntryContent(\n func.name,\n func.absolutePath,\n buildRoot,\n );\n const connectionIdCollector = createBackendConnectionIdCollector(\n func.absolutePath,\n buildRoot,\n );\n\n const staticChecksPlugin = createBackendStaticChecksPlugin(\n buildRoot,\n log,\n connectionIdCollector.getModuleRecords,\n );\n const baseConfig = getBaseBackendBuildConfig(\n buildRoot,\n { [virtualId]: virtualContent },\n [connectionIdCollector.plugin, staticChecksPlugin],\n );\n\n // eslint-disable-next-line no-await-in-loop\n const result = await viteBuild({\n ...baseConfig,\n build: {\n ...baseConfig.build,\n write: true,\n outDir,\n emptyOutDir: false,\n rollupOptions: {\n ...baseConfig.build.rollupOptions,\n input: { [bundleName]: virtualId },\n output: {\n ...baseConfig.build.rollupOptions.output,\n entryFileNames: '[name].js',\n },\n },\n },\n });\n\n const output = Array.isArray(result) ? result[0] : result;\n\n if ('output' in output) {\n for (const chunk of output.output) {\n if (chunk.type !== 'chunk' || !chunk.isEntry) {\n continue;\n }\n const absolutePath = path.resolve(outDir, chunk.fileName);\n outputs.set(bundleName, absolutePath);\n log.debug(`Backend function \"${bundleName}\" output: ${absolutePath}`);\n }\n }\n\n allowedConnectionIdsByEntryPath.set(\n func.absolutePath,\n connectionIdCollector.getAllowedConnectionIds(),\n );\n }\n } catch (error) {\n // A rejected build throws before outDir is returned, so the caller's success-path cleanup never runs — clean it up here. Cleanup failure is only logged so it can't mask the real build error.\n try {\n await rm(outDir);\n } catch (cleanupError) {\n log.warn(`Failed to clean up temp output directory \"${outDir}\": ${cleanupError}`);\n }\n throw error;\n }\n\n return {\n outDir,\n outputs,\n functions: functions.map((func) => ({\n ...func,\n allowedConnectionIds: allowedConnectionIdsByEntryPath.get(func.absolutePath)!,\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 } from '@dd/core/types';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { AppsOptions } from './types';\nimport { validateOptions } from './validate';\nimport { getVitePlugin } from './vite/index';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport type types = {\n // Add the types you'd like to expose here.\n AppsOptions: AppsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context, bundler }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options);\n\n if (context.bundler.name !== 'vite') {\n log.warn(`The apps plugin only supports Vite; skipping under '${context.bundler.name}'.`);\n return [];\n }\n\n // Vite's production hook creates the deployable package; publishing is\n // intentionally owned by @datadog/apps-cli. Backend functions are compiled\n // before packaging inside closeBundle.\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n vite: getVitePlugin({\n bundler,\n context,\n options: validatedOptions,\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 = 'errorTracking' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-error-tracking-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Output } from '@dd/core/types';\nimport chalk from 'chalk';\nimport path from 'path';\n\nimport {\n type SourcemapsOptionsWithDefaults,\n type Sourcemap,\n type MinifiedPathPrefix,\n} from '../types';\n\ntype PartialSourcemap = Pick<Sourcemap, 'minifiedFilePath' | 'minifiedUrl' | 'relativePath'>;\n\n// Helper function to safely join URLs or paths\nexport const joinUrlOrPath = (prefix: MinifiedPathPrefix, relativePath: string): string => {\n // Prefix is a path.\n if (prefix.startsWith('/')) {\n // Simply join the prefix with the relative path.\n return path.join(prefix, relativePath);\n }\n\n // Prefix is a URL.\n try {\n // Ensure it ends with a slash for deterministic URL path joining.\n const normalizedPrefix = prefix.replace(/\\/*$/, '/');\n const url = new URL(normalizedPrefix);\n // Ensure the relative path does not start with a slash\n // otherwise it will act as a \"root\" path when joined with the url.\n const normalizedRelativePath = relativePath.replace(/^[\\\\/]*/, '');\n return new URL(normalizedRelativePath, url).href;\n } catch {\n // Fallback to simple concatenation if URL constructor fails\n return `${prefix}${relativePath}`;\n }\n};\n\nexport const decomposePath = (\n prefix: MinifiedPathPrefix | undefined,\n // This is coming from context.bundler.outDir, which is absolute.\n absoluteOutDir: string,\n sourcemapFilePath: string,\n): PartialSourcemap => {\n if (path.extname(sourcemapFilePath) !== '.map') {\n throw new Error(`The file ${chalk.green.bold(sourcemapFilePath)} is not a sourcemap.`);\n }\n\n const minifiedFilePath = sourcemapFilePath.replace(/\\.map$/, '');\n const relativePath = path.relative(absoluteOutDir, minifiedFilePath);\n const minifiedUrl = prefix\n ? joinUrlOrPath(prefix, relativePath)\n : relativePath.split(path.sep).join('/');\n\n return {\n minifiedFilePath,\n minifiedUrl,\n relativePath,\n };\n};\n\nexport type SourcemapsFilesContext = {\n outputs?: Output[];\n outDir: string;\n};\n\nexport const getSourcemapsFiles = (\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsFilesContext,\n): Sourcemap[] => {\n if (!context.outputs || context.outputs.length === 0) {\n throw new Error('No output files found.');\n }\n\n const sourcemapFilesList = context.outputs\n .filter((file) => file.filepath.endsWith('.map'))\n .map((file) => file.filepath);\n\n const sourcemapFiles = sourcemapFilesList.map((sourcemapFilePath) => {\n const minifiedPathPrefix =\n options.debugId === false ? options.minifiedPathPrefix : undefined;\n return {\n ...decomposePath(minifiedPathPrefix, context.outDir, sourcemapFilePath),\n sourcemapFilePath,\n 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 fsp from 'fs/promises';\n\n// Matches the `ddDebugId:\"<uuid>\"` literal the RUM plugin injects into each chunk's own content\n// (see packages/plugins/rum/src/getSourceCodeContextSnippet.ts). The key is quoted in source\n// (`JSON.stringify(context)`) but minifiers like terser strip quotes from object keys that are\n// valid identifiers, so the built output can have either `\"ddDebugId\":\"...\"` or `ddDebugId:\"...\"`.\n// Reading it back out of the file we're about to upload means we never have to trust a filename\n// as a coordination key between the RUM plugin and this one, so it stays correct across any\n// bundler renaming step.\nconst DEBUG_ID_RX = /\"?ddDebugId\"?:\"([0-9a-fA-F-]{36})\"/;\n\n// Read progressively so the common case only needs the first KiB, while still supporting\n// bundlers or transforms that place the injected snippet later in the artifact.\nexport const DEBUG_ID_SEARCH_CHUNK_BYTES = 1024;\n\n// Keep enough content from the previous chunk to match a debug ID literal split across a read\n// boundary. The longest supported literal is shorter than this overlap.\nconst DEBUG_ID_SEARCH_OVERLAP_CHARACTERS = 64;\n\nconst matchDebugId = (fileContent: string): string | undefined => {\n return DEBUG_ID_RX.exec(fileContent)?.[1];\n};\n\n// Search in fixed-size reads and stop as soon as the debug ID is found. Only a small overlap is\n// retained between reads, so even the worst case (scanning to EOF) uses bounded memory.\nconst readDebugId = async (filePath: string): Promise<string | undefined> => {\n const fd = await fsp.open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(DEBUG_ID_SEARCH_CHUNK_BYTES);\n let overlap = '';\n let position = 0;\n\n while (true) {\n const { bytesRead } = await fd.read(buffer, 0, DEBUG_ID_SEARCH_CHUNK_BYTES, position);\n if (bytesRead === 0) {\n return undefined;\n }\n\n const searchableContent = overlap + buffer.toString('utf-8', 0, bytesRead);\n const debugId = matchDebugId(searchableContent);\n if (debugId) {\n return debugId;\n }\n\n overlap = searchableContent.slice(-DEBUG_ID_SEARCH_OVERLAP_CHARACTERS);\n position += bytesRead;\n }\n } finally {\n await fd.close();\n }\n};\n\n// Reads the minified file's own content and extracts the debug_id from it, instead of\n// trusting a filename as a coordination key with the RUM plugin — the bundler may still\n// rename the file after injection (e.g. webpack/rspack's realContentHash), but the content,\n// and the debug_id embedded in it, is unaffected.\nexport const extractDebugId = async (filePath: string): Promise<string | undefined> => {\n return readDebugId(filePath).catch(() => undefined);\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 type: string;\n service?: string;\n version?: string;\n git_repository_url?: string;\n git_commit_sha?: string;\n debug_id?: 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: prefix ? prefixRepeat(sourcemap.relativePath, prefix) : '',\n };\n};\n\nexport const getPayload = async (\n sourcemap: Sourcemap,\n metadata: Metadata,\n prefix?: string,\n git?: RepositoryData,\n debugId?: string,\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 debug_id: debugId,\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 { normalizeTagValue } from '@dd/core/helpers/strings';\nimport type { Metric } from '@dd/core/types';\n\nimport type { SourcemapsOptionsWithDefaults } from '../types';\n\nimport type { UploadContext } from './sender';\n\nexport const SOURCEMAP_UPLOAD_METRIC_PREFIX = 'sourcemaps.upload';\n\ntype UploadMetricName = 'retry' | 'failure';\n\ntype UploadMetric = {\n name: UploadMetricName;\n value: number;\n tags: string[];\n};\n\nexport type SourcemapUploadMetrics = {\n metrics: Map<string, UploadMetric>;\n baseTags: string[];\n};\n\nconst getMetricKey = (name: UploadMetricName, tags: string[]) => `${name}|${tags.join('|')}`;\n\nconst getStatusCodeTag = (error: Error): string => {\n const match = error.message.match(/HTTP (\\d{3})/);\n return match ? `status_code:${match[1]}` : 'status_code:unknown';\n};\n\nconst getErrorTypeTag = (error: Error): string => {\n const statusCodeTag = getStatusCodeTag(error);\n if (statusCodeTag !== 'status_code:unknown') {\n return `error_type:http_${statusCodeTag.replace('status_code:', '')}`;\n }\n\n return `error_type:${normalizeTagValue(error.name || 'unknown')}`;\n};\n\nexport const createSourcemapUploadMetrics = (\n options: SourcemapsOptionsWithDefaults,\n): SourcemapUploadMetrics => ({\n metrics: new Map(),\n baseTags: options.debugId === false ? [`service:${options.service}`] : ['matching:debug_id'],\n});\n\nconst incrementUploadMetric = (\n uploadMetrics: SourcemapUploadMetrics,\n name: UploadMetricName,\n tags: string[],\n) => {\n const metricKey = getMetricKey(name, tags);\n const currentMetric = uploadMetrics.metrics.get(metricKey);\n if (currentMetric) {\n currentMetric.value++;\n return;\n }\n\n uploadMetrics.metrics.set(metricKey, { name, value: 1, tags });\n};\n\nexport const recordSourcemapUploadRetry = (\n uploadMetrics: SourcemapUploadMetrics,\n error: Error,\n attempt: number,\n) => {\n incrementUploadMetric(uploadMetrics, 'retry', [\n ...uploadMetrics.baseTags,\n `attempt:${attempt}`,\n getStatusCodeTag(error),\n getErrorTypeTag(error),\n ]);\n};\n\nexport const recordSourcemapUploadFailure = (\n uploadMetrics: SourcemapUploadMetrics,\n error: Error,\n) => {\n incrementUploadMetric(uploadMetrics, 'failure', [\n ...uploadMetrics.baseTags,\n getStatusCodeTag(error),\n getErrorTypeTag(error),\n ]);\n};\n\nexport const getSourcemapUploadMetrics = (uploadMetrics: SourcemapUploadMetrics): Metric[] => {\n const timestamp = Math.floor(Date.now() / 1000);\n return Array.from(uploadMetrics.metrics.values()).map((metric) => ({\n metric: `${SOURCEMAP_UPLOAD_METRIC_PREFIX}.${metric.name}`,\n type: 'count',\n points: [[timestamp, metric.value]],\n tags: metric.tags,\n }));\n};\n\nexport const addSourcemapUploadMetrics = (\n uploadMetrics: SourcemapUploadMetrics,\n context: UploadContext,\n) => {\n if (!context.sendMetrics) {\n return;\n }\n\n if (!uploadMetrics.metrics.size) {\n return;\n }\n\n const metrics = getSourcemapUploadMetrics(uploadMetrics);\n for (const metric of metrics) {\n context.addMetric(metric);\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 { getDDEnvValue } from '@dd/core/helpers/env';\nimport { getFile } from '@dd/core/helpers/fs';\nimport {\n createRequestData,\n doRequest,\n getOriginHeaders,\n NB_RETRIES,\n type RequestData,\n} from '@dd/core/helpers/request';\nimport { formatDuration, prettyObject } from '@dd/core/helpers/strings';\nimport type { Logger, Metric, RepositoryData } from '@dd/core/types';\nimport chalk from 'chalk';\nimport PQueue from 'p-queue';\n\nimport type { SourcemapsOptionsWithDefaults, Sourcemap } from '../types';\n\nimport { extractDebugId } from './debugId';\nimport type { Metadata, MultipartFileValue, Payload } from './payload';\nimport { getPayload } from './payload';\nimport {\n addSourcemapUploadMetrics,\n createSourcemapUploadMetrics,\n recordSourcemapUploadFailure,\n recordSourcemapUploadRetry,\n} from './upload-metrics';\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\ntype SourcemapWithDebugId = {\n sourcemap: Sourcemap;\n debugId?: string;\n};\n\nexport const SOURCEMAPS_API_SUBDOMAIN = 'sourcemap-intake';\nexport const SOURCEMAPS_API_PATH = 'api/v2/srcmap';\n\nexport const getIntakeUrl = (site: string) => {\n const envIntake = getDDEnvValue('SOURCEMAP_INTAKE_URL');\n return envIntake || `https://${SOURCEMAPS_API_SUBDOMAIN}.${site}/${SOURCEMAPS_API_PATH}`;\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<RequestData> => {\n return createRequestData({\n getForm: async () => {\n const form = new FormData();\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 return form;\n },\n defaultHeaders,\n zip: true,\n });\n };\n\nexport type UploadContext = {\n addMetric: (metric: Metric) => void;\n apiKey?: string;\n bundlerName: string;\n sendMetrics?: boolean;\n site: string;\n version: string;\n outDir: string;\n};\n\nexport const upload = async (\n payloads: Payload[],\n options: SourcemapsOptionsWithDefaults,\n context: UploadContext,\n log: Logger,\n) => {\n const errors: { metadata?: FileMetadata; error: Error }[] = [];\n const warnings: string[] = [];\n\n if (!context.apiKey) {\n errors.push({ error: new Error('No authentication token provided') });\n return { errors, warnings };\n }\n\n if (payloads.length === 0) {\n warnings.push('No sourcemaps to upload');\n return { errors, warnings };\n }\n\n const queueTimer = log.time('Queue uploads');\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const queue = new Queue({ concurrency: options.maxConcurrency });\n const intakeUrl = getIntakeUrl(context.site);\n const defaultHeaders = getOriginHeaders({\n bundler: context.bundlerName,\n plugin: 'sourcemaps',\n version: context.version,\n });\n const uploadMetrics = createSourcemapUploadMetrics(options);\n\n // Show a pretty summary of the configuration.\n const configurationString = prettyObject({\n ...options,\n intakeUrl,\n outDir: context.outDir,\n defaultHeaders: `\\n${JSON.stringify(defaultHeaders, null, 2)}`,\n });\n\n const summary = `\\nUploading ${green(payloads.length.toString())} sourcemaps with configuration:\\n${configurationString}`;\n\n log.debug(summary);\n\n const addPromises = [];\n\n for (const payload of payloads) {\n const metadata = {\n sourcemap: (payload.content.get('source_map') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n file: (payload.content.get('minified_file') as MultipartFileValue)?.path.replace(\n context.outDir,\n '.',\n ),\n };\n\n addPromises.push(\n queue.add(async () => {\n try {\n await doRequest({\n auth: { apiKey: context.apiKey },\n url: intakeUrl,\n method: 'POST',\n getData: getData(payload, defaultHeaders),\n // On retry we store the error as a warning.\n onRetry: (error: Error, attempt: number) => {\n recordSourcemapUploadRetry(uploadMetrics, error, attempt);\n const warningMessage = `Failed to upload ${yellow(metadata.sourcemap)} | ${yellow(metadata.file)}:\\n ${error.message}\\nRetrying ${attempt}/${NB_RETRIES}`;\n // This will be logged at the end of the process.\n warnings.push(warningMessage);\n log.debug(warningMessage);\n },\n });\n } catch (e: any) {\n recordSourcemapUploadFailure(uploadMetrics, e);\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 queueTimer.end();\n log.debug(`Queued ${green(payloads.length.toString())} uploads.`);\n\n try {\n await Promise.all(addPromises);\n await queue.onIdle();\n } finally {\n addSourcemapUploadMetrics(uploadMetrics, context);\n }\n\n return { warnings, errors };\n};\n\nexport type SourcemapsSenderContext = UploadContext & {\n git?: RepositoryData;\n};\n\nexport const sendSourcemaps = async (\n sourcemaps: Sourcemap[],\n options: SourcemapsOptionsWithDefaults,\n context: SourcemapsSenderContext,\n log: Logger,\n) => {\n const start = Date.now();\n const prefix = options.debugId === false ? options.minifiedPathPrefix : undefined;\n\n const metadata: Metadata = {\n git_repository_url: context.git?.remote,\n git_commit_sha: context.git?.hash,\n plugin_version: context.version,\n project_path: context.outDir,\n type: 'js_sourcemap',\n ...(options.debugId === false\n ? { service: options.service, version: options.releaseVersion }\n : {}),\n };\n\n const payloadsTimer = log.time('Compute payloads');\n // @ts-expect-error PQueue's default isn't typed.\n const Queue = PQueue.default ? PQueue.default : PQueue;\n const payloadsQueue = new Queue({ concurrency: options.maxConcurrency });\n const sourcemapsWithDebugIds: SourcemapWithDebugId[] = await payloadsQueue.addAll(\n sourcemaps.map((sourcemap) => async () => {\n const debugId = await extractDebugId(sourcemap.minifiedFilePath);\n return { sourcemap, debugId };\n }),\n );\n const debugIdCount = sourcemapsWithDebugIds.filter(({ debugId }) => debugId).length;\n log.debug(\n `Extracted debug_id for ${green(`${debugIdCount}/${sourcemaps.length}`)} sourcemaps.`,\n );\n\n if (options.debugId && sourcemaps.length > 0 && debugIdCount === 0) {\n payloadsTimer.end();\n const errorMsg = 'No debug ID found in any minified file. Aborting upload.';\n log.error(errorMsg);\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n return;\n }\n\n const skippedSourcemaps = options.debugId\n ? sourcemapsWithDebugIds.filter(({ debugId }) => !debugId)\n : [];\n const sourcemapsToUpload = options.debugId\n ? sourcemapsWithDebugIds.filter(({ debugId }) => debugId)\n : sourcemapsWithDebugIds;\n const payloads: Payload[] = await payloadsQueue.addAll(\n sourcemapsToUpload.map(\n ({ sourcemap, debugId }) =>\n async () =>\n getPayload(sourcemap, metadata, prefix, context.git, debugId),\n ),\n );\n payloadsTimer.end();\n\n const errors = payloads.map((payload) => payload.errors).flat();\n const warnings = [\n ...skippedSourcemaps.map(\n ({ sourcemap }) =>\n `Skipping sourcemap ${sourcemap.sourcemapFilePath} because no debug ID was found in ${sourcemap.minifiedFilePath}`,\n ),\n ...payloads.map((payload) => payload.warnings).flat(),\n ];\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 uploadTimer = log.time('Upload sourcemaps');\n const { errors: uploadErrors, warnings: uploadWarnings } = await upload(\n payloads,\n options,\n {\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n version: context.version,\n outDir: context.outDir,\n site: context.site,\n sendMetrics: context.sendMetrics,\n addMetric: context.addMetric,\n },\n log,\n );\n uploadTimer.end();\n log.debug(\n `Done uploading ${green(`${payloads.length - uploadErrors.length}/${payloads.length}`)} sourcemaps in ${green(formatDuration(Date.now() - start))}.`,\n );\n\n if (uploadErrors.length > 0) {\n const listOfErrors = ` - ${uploadErrors\n .map(({ metadata: fileMetadata, error }) => {\n const errorToPrint = error.cause || error.stack || error.message;\n if (fileMetadata) {\n return `${red(fileMetadata.file)} | ${red(fileMetadata.sourcemap)} :\\n${errorToPrint}`;\n }\n return errorToPrint;\n })\n .join('\\n - ')}`;\n\n const errorMsg = `Failed to upload some sourcemaps:\\n${listOfErrors}`;\n log.error(errorMsg);\n\n // Depending on the configuration we throw or not.\n // This should not be reached as we'd have thrown earlier.\n if (options.bailOnError === true) {\n throw new Error(errorMsg);\n }\n }\n\n if (uploadWarnings.length > 0) {\n log.warn(`Warnings while uploading sourcemaps:\\n - ${uploadWarnings.join('\\n - ')}`);\n }\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger } from '@dd/core/types';\n\nimport type { ErrorTrackingOptionsWithSourcemaps } from '../types';\n\nimport type { SourcemapsFilesContext } from './files';\nimport { getSourcemapsFiles } from './files';\nimport type { SourcemapsSenderContext } from './sender';\nimport { sendSourcemaps } from './sender';\n\nexport type UploadSourcemapsContext = SourcemapsSenderContext & SourcemapsFilesContext;\n\nexport const uploadSourcemaps = async (\n options: ErrorTrackingOptionsWithSourcemaps,\n context: UploadSourcemapsContext,\n log: Logger,\n) => {\n // Gather the sourcemaps files.\n const sourcemapsTime = log.time('get sourcemaps files');\n const sourcemaps = getSourcemapsFiles(options.sourcemaps, {\n outDir: context.outDir,\n outputs: context.outputs,\n });\n sourcemapsTime.end();\n\n // Send everything.\n const sendTime = log.time('send sourcemaps');\n await sendSourcemaps(\n sourcemaps,\n options.sourcemaps,\n {\n addMetric: context.addMetric,\n apiKey: context.apiKey,\n bundlerName: context.bundlerName,\n git: context.git,\n outDir: context.outDir,\n sendMetrics: context.sendMetrics,\n site: context.site,\n version: context.version,\n },\n log,\n );\n sendTime.end();\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport {\n type ErrorTrackingOptions,\n type ErrorTrackingOptionsWithDefaults,\n type SourcemapsOptionsWithDefaults,\n} from './types';\n\n// Deal with validation and defaults here.\nexport const validateOptions = (config: Options, log: Logger): ErrorTrackingOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sourcemapsResults = validateSourcemapsOptions(config);\n errors.push(...sourcemapsResults.errors);\n\n // Throw if there are any errors.\n if (errors.length) {\n log.error(`\\n - ${errors.join('\\n - ')}`);\n throw new Error(`Invalid configuration for ${PLUGIN_NAME}.`);\n }\n\n return {\n ...config[CONFIG_KEY],\n sourcemaps: sourcemapsResults.config,\n };\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 return toReturn;\n }\n\n const sourcemapsCfg = validatedOptions.sourcemaps;\n\n if (sourcemapsCfg.debugId === true) {\n if (config.rum?.enable === false) {\n toReturn.errors.push(\n `${red('rum')} must be enabled to upload source maps by debug ID.`,\n );\n }\n if (!config.rum?.sourceCodeContext?.debugId) {\n toReturn.errors.push(\n `${red('rum.sourceCodeContext.debugId')} must be enabled to upload source maps by debug ID.`,\n );\n }\n if (\n sourcemapsCfg.service !== undefined ||\n sourcemapsCfg.releaseVersion !== undefined ||\n sourcemapsCfg.minifiedPathPrefix !== undefined\n ) {\n toReturn.errors.push(\n `${red('sourcemaps.service')}, ${red('sourcemaps.releaseVersion')}, and ${red('sourcemaps.minifiedPathPrefix')} cannot be used when ${red('sourcemaps.debugId')} is enabled.`,\n );\n }\n if (!config.auth?.apiKey) {\n toReturn.errors.push(\n `${red('auth.apiKey')} is required to upload source maps by debug ID.`,\n );\n }\n\n if (toReturn.errors.length === 0) {\n toReturn.config = {\n bailOnError: false,\n dryRun: false,\n maxConcurrency: 20,\n ...sourcemapsCfg,\n };\n }\n\n return toReturn;\n }\n\n // Resolve `releaseVersion`: prefer the plugin-specific option, then\n // fall back to the shared top-level `metadata.version`. Letting users\n // configure one canonical build version at the top level keeps every\n // consumer (live-debugger, sourcemaps, …) reading from the same place.\n const releaseVersion = sourcemapsCfg.releaseVersion || config.metadata?.version;\n\n // Validate the configuration.\n if (!releaseVersion) {\n toReturn.errors.push(\n `${red('sourcemaps.releaseVersion')} is required (set it directly or via ${red('metadata.version')}).`,\n );\n }\n if (\n sourcemapsCfg.releaseVersion &&\n config.metadata?.version &&\n sourcemapsCfg.releaseVersion !== config.metadata.version\n ) {\n toReturn.errors.push(\n `${red('sourcemaps.releaseVersion')} must match ${red('metadata.version')} when both are configured.`,\n );\n }\n if (!sourcemapsCfg.service) {\n toReturn.errors.push(`${red('sourcemaps.service')} is required.`);\n }\n if (!sourcemapsCfg.minifiedPathPrefix) {\n toReturn.errors.push(`${red('sourcemaps.minifiedPathPrefix')} is required.`);\n }\n\n // Validate the minifiedPathPrefix.\n if (\n sourcemapsCfg.minifiedPathPrefix &&\n !validateMinifiedPathPrefix(sourcemapsCfg.minifiedPathPrefix)\n ) {\n toReturn.errors.push(\n `${red('sourcemaps.minifiedPathPrefix')} must be a valid URL or start with '/'.`,\n );\n }\n\n // Build the resolved config only when `releaseVersion` actually\n // resolves; otherwise an error has been recorded and the caller will\n // throw before the config is read.\n if (releaseVersion) {\n toReturn.config = {\n bailOnError: false,\n dryRun: false,\n maxConcurrency: 20,\n ...sourcemapsCfg,\n debugId: false,\n releaseVersion,\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 { resolveEnable } from '@dd/core/helpers/options';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { BuildReport, GetPlugins, RepositoryData } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\nimport { uploadSourcemaps } from './sourcemaps';\nimport type { ErrorTrackingOptions, ErrorTrackingOptionsWithSourcemaps } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME } from './constants';\n\nexport type types = {\n // Add the types you'd like to expose here.\n ErrorTrackingOptions: ErrorTrackingOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const timeOptions = log.time('validate options');\n const validatedOptions = validateOptions(options, log);\n timeOptions.end();\n const sendSourcemapUploadMetrics = resolveEnable(options, 'metrics', log);\n\n let gitInfo: RepositoryData | undefined;\n let buildReport: BuildReport | undefined;\n let sourcemapsHandled: boolean = false;\n let sourcemapsHandling: Promise<void> | undefined;\n\n const handleSourcemaps = async () => {\n if (!validatedOptions.sourcemaps || sourcemapsHandled) {\n return;\n }\n if (!sourcemapsHandling) {\n sourcemapsHandling = (async () => {\n await context.artifactsReady;\n sourcemapsHandled = true;\n const totalTime = log.time('sourcemaps process');\n await uploadSourcemaps(\n // Need the \"as\" because Typescript doesn't understand that we've already checked for sourcemaps.\n validatedOptions as ErrorTrackingOptionsWithSourcemaps,\n {\n apiKey: context.auth.apiKey,\n bundlerName: context.bundler.name,\n git: gitInfo,\n addMetric: context.addMetric,\n outDir: context.bundler.outDir,\n outputs: buildReport?.outputs || [],\n sendMetrics: sendSourcemapUploadMetrics,\n site: context.auth.site,\n version: context.version,\n },\n log,\n );\n totalTime.end();\n })();\n }\n\n await sourcemapsHandling;\n };\n\n const handleOrQueueSourcemaps = async () => {\n if (context.artifactsPending) {\n const sourcemapsPromise = handleSourcemaps();\n context.queue(sourcemapsPromise);\n return;\n }\n await handleSourcemaps();\n };\n\n const plugins: ReturnType<GetPlugins> = [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n async git(repoData) {\n gitInfo = repoData;\n\n if (buildReport) {\n await handleOrQueueSourcemaps();\n }\n },\n async buildReport(report) {\n buildReport = report;\n\n if (gitInfo || !shouldGetGitInfo(options)) {\n await handleOrQueueSourcemaps();\n }\n },\n async asyncTrueEnd() {\n // If we're at the end and sourcemaps have not been handled yet,\n // just do it. It can happen when git data isn't accessible for some reason.\n // For insteance, when working from an unpushed repository.\n if (!sourcemapsHandled) {\n await handleSourcemaps();\n }\n },\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 { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'liveDebugger' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-live-debugger-plugin' as const;\n\n// Skip instrumentation comment\nexport const SKIP_INSTRUMENTATION_COMMENT = '@dd-no-instrumentation';\n\nexport const DEFAULT_FILE_EXTENSIONS = [\n '.js',\n '.jsx',\n '.ts',\n '.tsx',\n '.mjs',\n '.cjs',\n '.mts',\n '.cts',\n] as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport path from 'path';\nimport picomatch from 'picomatch';\n\nimport type { FileExtensions, LiveDebuggerOptionsWithDefaults } from './types';\n\ntype Pattern = string | RegExp;\ntype Matcher = (id: string) => boolean;\n\nconst BACKSLASH_PATTERN = /\\\\/g;\nconst WINDOWS_ABSOLUTE_PATH_PATTERN = /^(?:[A-Z]:[\\\\/]|\\\\\\\\)/i;\nconst ID_SUFFIX_PATTERN = /[?#]/;\n\nconst normalizePath = (filePath: string): string => filePath.replace(BACKSLASH_PATTERN, '/');\n\nconst resolveGlob = (glob: string): string => {\n if (\n glob.startsWith('**') ||\n path.isAbsolute(glob) ||\n WINDOWS_ABSOLUTE_PATH_PATTERN.test(glob)\n ) {\n return normalizePath(glob);\n }\n\n const absoluteGlob = path.resolve(glob);\n return normalizePath(absoluteGlob);\n};\n\nconst createPatternMatcher = (pattern: Pattern): Matcher => {\n if (pattern instanceof RegExp) {\n return (id) => {\n const normalizedId = normalizePath(id);\n const matches = pattern.test(normalizedId);\n pattern.lastIndex = 0;\n return matches;\n };\n }\n\n const glob = resolveGlob(pattern);\n const matchesGlob = picomatch(glob, { dot: true });\n return (id) => {\n const normalizedId = normalizePath(id);\n return matchesGlob(normalizedId);\n };\n};\n\nconst createPatternFilter = (include: Pattern[], exclude: Pattern[]): Matcher => {\n const includeMatchers = include.map(createPatternMatcher);\n const excludeMatchers = exclude.map(createPatternMatcher);\n\n return (id) => {\n if (excludeMatchers.some((matches) => matches(id))) {\n return false;\n }\n\n return includeMatchers.length === 0 || includeMatchers.some((matches) => matches(id));\n };\n};\n\nconst createFileExtensionFilter = (fileExtensions: FileExtensions): Matcher => {\n if (fileExtensions === 'all') {\n return () => true;\n }\n\n const normalizedExtensions = fileExtensions.map((extension) => extension.toLowerCase());\n return (id) => {\n const [filePath] = id.split(ID_SUFFIX_PATTERN);\n const normalizedFilePath = filePath.toLowerCase();\n return normalizedExtensions.some((extension) => normalizedFilePath.endsWith(extension));\n };\n};\n\nexport const createFileFilter = (\n options: Pick<LiveDebuggerOptionsWithDefaults, 'include' | 'exclude' | 'fileExtensions'>,\n): Matcher => {\n const matchesPatterns = createPatternFilter(options.include, options.exclude);\n const matchesFileExtension = createFileExtensionFilter(options.fileExtensions);\n\n return (id) => matchesFileExtension(id) && matchesPatterns(id);\n};\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport const createFileExtensionPattern = (fileExtensions: FileExtensions): RegExp | undefined => {\n if (fileExtensions === 'all') {\n return undefined;\n }\n\n const escapedExtensions = fileExtensions.map(escapeRegExp);\n return new RegExp(`(?:${escapedExtensions.join('|')})(?:[?#].*)?$`, 'i');\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// Minimal runtime stub injected into all chunks.\n// `$dd_probes` is called unconditionally by instrumented functions, so it must\n// exist before the Browser Debugger SDK initializes. The SDK's `init()` later\n// replaces the stubbed globals with the real implementations.\nconst runtimeStubs = `if(typeof globalThis.$dd_probes==='undefined'){globalThis.$dd_probes=function(){}}`;\nconst buildMetadataGlobal = '__DD_LIVE_DEBUGGER_BUILD__' as const;\n\n// Build the runtime bootstrap injected into all chunks. When\n// `metadata.version` is configured, also expose build metadata so the\n// Browser Debugger SDK can default its runtime version from the injected value.\nexport const getRuntimeBootstrap = (version?: string): string => {\n if (version === undefined) {\n return runtimeStubs;\n }\n\n return `${runtimeStubs};if(typeof globalThis.${buildMetadataGlobal}==='undefined'){globalThis.${buildMetadataGlobal}={version:${JSON.stringify(version)}}}`;\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/**\n * Resolve a CJS default export that may be double-wrapped by bundler interop.\n *\n * When a CJS module uses `module.exports = function ...`, ESM `import foo from`\n * should yield the function directly. However, some bundlers (rspack, webpack)\n * wrap the namespace so `foo` is `{ default: fn }` instead of `fn`.\n * This helper normalizes both shapes to the underlying function.\n */\nexport function resolveCjsDefaultExport<T extends Function>(imported: T | { default: T }): T {\n if (typeof imported === 'function') {\n return imported;\n }\n return imported.default;\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 * as t from '@babel/types';\nimport path from 'path';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\n\n/**\n * Generate a stable, unique function ID\n * Format (POC): <relative-file-path>;<function-name>\n * Example: src/utils.js;add\n *\n * NOTE: This POC format only supports uniquely named functions.\n * Anonymous functions will use the format <file-path>;<anonymous>:<index>\n */\nexport function generateFunctionId(\n filePath: string,\n buildRoot: string,\n functionPath: BabelPath<t.Function>,\n anonymousSiblingIndex: number,\n typesModule: BabelTypesModule,\n): string {\n const relativePath = path.relative(buildRoot, filePath).replace(/\\\\/g, '/');\n const functionName = getFunctionName(functionPath, typesModule);\n\n if (functionName) {\n return `${relativePath};${functionName}`;\n }\n\n const locationSuffix = getFunctionLocation(functionPath);\n\n return `${relativePath};<anonymous>@${locationSuffix}:${anonymousSiblingIndex}`;\n}\n\n/**\n * Get the name of a function if available\n */\nexport function getFunctionName(\n functionPath: BabelPath<t.Function>,\n typesModule: BabelTypesModule,\n): string | null {\n const node = functionPath.node;\n const parent = functionPath.parent;\n\n // Named function declaration: function foo() {}\n if ('id' in node && typesModule.isIdentifier(node.id)) {\n return node.id.name;\n }\n\n // Object/Class method: { foo() {} } or class { foo() {} }\n if (\n typesModule.isObjectMethod(node) ||\n typesModule.isClassMethod(node) ||\n typesModule.isClassPrivateMethod(node)\n ) {\n return getPropertyLikeName(node.key, typesModule);\n }\n\n // Variable declaration: const foo = () => {}\n if (typesModule.isVariableDeclarator(parent) && typesModule.isIdentifier(parent.id)) {\n return parent.id.name;\n }\n\n // Assignment: foo = () => {} or obj.foo = () => {}\n if (typesModule.isAssignmentExpression(parent)) {\n return getAssignmentTargetName(parent.left, typesModule);\n }\n\n // Object property: { foo: () => {} }\n if (\n typesModule.isObjectProperty(parent) ||\n typesModule.isClassProperty(parent) ||\n typesModule.isClassPrivateProperty(parent)\n ) {\n return getPropertyLikeName(parent.key, typesModule);\n }\n\n return null;\n}\n\nfunction getAssignmentTargetName(\n target: t.LVal | t.OptionalMemberExpression,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(target)) {\n return target.name;\n }\n\n if (typesModule.isMemberExpression(target) || typesModule.isOptionalMemberExpression(target)) {\n const objectName = getMemberObjectName(target.object, typesModule);\n const propertyName = getMemberPropertyName(target.property, target.computed, typesModule);\n\n if (objectName && propertyName) {\n return `${objectName}.${propertyName}`;\n }\n }\n\n return null;\n}\n\nfunction getMemberObjectName(\n target: t.Expression | t.Super,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(target)) {\n return target.name;\n }\n\n if (typesModule.isThisExpression(target)) {\n return 'this';\n }\n\n if (typesModule.isMemberExpression(target) || typesModule.isOptionalMemberExpression(target)) {\n const parentObjectName = getMemberObjectName(target.object, typesModule);\n const propertyName = getMemberPropertyName(target.property, target.computed, typesModule);\n\n if (parentObjectName && propertyName) {\n return `${parentObjectName}.${propertyName}`;\n }\n }\n\n return null;\n}\n\nfunction getMemberPropertyName(\n property: t.Expression | t.PrivateName,\n isComputed: boolean,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isPrivateName(property) && typesModule.isIdentifier(property.id)) {\n return `#${property.id.name}`;\n }\n\n if (isComputed) {\n return null;\n }\n\n if (typesModule.isIdentifier(property)) {\n return property.name;\n }\n\n return null;\n}\n\nfunction getPropertyLikeName(\n key: t.Expression | t.PrivateName | t.Identifier,\n typesModule: BabelTypesModule,\n): string | null {\n if (typesModule.isIdentifier(key)) {\n return key.name;\n }\n\n if (\n typesModule.isStringLiteral(key) ||\n typesModule.isNumericLiteral(key) ||\n typesModule.isBigIntLiteral(key)\n ) {\n return String(key.value);\n }\n\n if (typesModule.isPrivateName(key) && typesModule.isIdentifier(key.id)) {\n return `#${key.id.name}`;\n }\n\n return null;\n}\n\nfunction getFunctionLocation(functionPath: BabelPath<t.Function>): string {\n const line = functionPath.node.loc?.start.line ?? 0;\n const column = functionPath.node.loc?.start.column ?? 0;\n\n return `${line}:${column}`;\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 * as t from '@babel/types';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\n\nfunction hasSkipComment(path: BabelPath, skipComment: string): boolean {\n if (path.node.leadingComments) {\n for (const comment of path.node.leadingComments) {\n if (comment.value.includes(skipComment)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Check if a function should be skipped based on comments.\n *\n * Walks up the AST from the function node through wrapping expression/declaration\n * nodes (VariableDeclarator, VariableDeclaration, ExportNamedDeclaration, etc.)\n * and checks leadingComments at each level. Stops at statement-level boundaries\n * so that comments on unrelated statements are never matched.\n *\n * After reaching a statement boundary (e.g. VariableDeclaration), also checks the\n * parent if it is an export declaration, because `export const fn = ...` attaches\n * the comment to the ExportNamedDeclaration, one level above the statement.\n */\nexport function shouldSkipFunction(\n functionPath: BabelPath<t.Function>,\n skipComment: string,\n typesModule: BabelTypesModule,\n): boolean {\n let current: BabelPath | null = functionPath;\n\n while (current) {\n if (hasSkipComment(current, skipComment)) {\n return true;\n }\n\n // Stop once we reach a statement or export declaration — that is the\n // outermost node where Babel would attach a line-level leading comment.\n if (\n typesModule.isStatement(current.node) ||\n typesModule.isExportDeclaration(current.node)\n ) {\n // For `export const fn = ...`, the comment is on the ExportDeclaration\n // which wraps the VariableDeclaration statement.\n if (current.parentPath && typesModule.isExportDeclaration(current.parentPath.node)) {\n return hasSkipComment(current.parentPath, skipComment);\n }\n break;\n }\n\n current = current.parentPath;\n }\n\n return false;\n}\n\n/**\n * Check if function should be instrumented\n * Skips: generators and constructors\n */\nexport function canInstrumentFunction(\n functionPath: BabelPath<t.Function>,\n typesModule: BabelTypesModule,\n): boolean {\n const node = functionPath.node;\n\n // Skip generators\n if (node.generator) {\n return false;\n }\n\n // Skip constructors\n if (typesModule.isClassMethod(node) && node.kind === 'constructor') {\n return false;\n }\n\n return true;\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 * as t from '@babel/types';\n\nimport type { BabelTypesModule } from './babel-path.types';\n\nexport const MAX_CAPTURE_VARIABLES = 25;\n\nexport interface LocalVariableTemporalDeadZone {\n start: number;\n end: number;\n}\n\nexport interface LocalVariableDeclaration {\n name: string;\n declarationEnd: number;\n temporalDeadZones: LocalVariableTemporalDeadZone[];\n}\n\nexport function getParameterNames(\n functionNode: t.Function,\n typesModule: BabelTypesModule,\n): string[] {\n const variables: string[] = [];\n\n for (const param of functionNode.params) {\n for (const name of getPatternIdentifiers(param, typesModule)) {\n // TypeScript's `this` parameter (e.g. `fn(this: Type)`) is not\n // a real parameter and `this` can't be used as a shorthand\n // property name in object literals.\n if (name !== 'this') {\n variables.push(name);\n }\n }\n }\n\n if (variables.length > MAX_CAPTURE_VARIABLES) {\n return variables.slice(0, MAX_CAPTURE_VARIABLES);\n }\n\n return variables;\n}\n\nexport function getLocalVariableDeclarations(\n functionNode: t.Function,\n typesModule: BabelTypesModule,\n): LocalVariableDeclaration[] {\n const variables: LocalVariableDeclaration[] = [];\n\n if (typesModule.isBlockStatement(functionNode.body)) {\n const paramNames = functionNode.params.flatMap((param) =>\n getPatternIdentifiers(param, typesModule),\n );\n const paramSet = new Set(paramNames);\n const functionName =\n 'id' in functionNode && typesModule.isIdentifier(functionNode.id)\n ? functionNode.id.name\n : '';\n\n for (const stmt of functionNode.body.body) {\n if (typesModule.isVariableDeclaration(stmt)) {\n const declarationEnd = stmt.end;\n if (declarationEnd == null) {\n continue;\n }\n\n for (const decl of stmt.declarations) {\n for (const name of getPatternIdentifiers(decl.id, typesModule)) {\n if (!paramSet.has(name) && name !== functionName) {\n variables.push({\n name,\n declarationEnd,\n temporalDeadZones: [],\n });\n }\n }\n }\n }\n }\n }\n\n const cappedVariables =\n variables.length > MAX_CAPTURE_VARIABLES\n ? variables.slice(0, MAX_CAPTURE_VARIABLES)\n : variables;\n\n if (typesModule.isBlockStatement(functionNode.body)) {\n const localNames = cappedVariables.map(({ name }) => name);\n const localNameSet = new Set(localNames);\n const temporalDeadZonesByName = getNestedTemporalDeadZonesByName(\n functionNode.body,\n localNameSet,\n typesModule,\n );\n\n for (const variable of cappedVariables) {\n variable.temporalDeadZones = temporalDeadZonesByName.get(variable.name) ?? [];\n }\n }\n\n return cappedVariables;\n}\n\nfunction getNestedTemporalDeadZonesByName(\n functionBody: t.BlockStatement,\n localNames: Set<string>,\n typesModule: BabelTypesModule,\n): Map<string, LocalVariableTemporalDeadZone[]> {\n const temporalDeadZonesByName = new Map<string, LocalVariableTemporalDeadZone[]>();\n\n for (const stmt of functionBody.body) {\n collectTemporalDeadZonesFromStatement(\n stmt,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n\n return temporalDeadZonesByName;\n}\n\nfunction collectTemporalDeadZonesFromStatement(\n stmt: t.Statement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n if (typesModule.isFunctionDeclaration(stmt) || typesModule.isClassDeclaration(stmt)) {\n return;\n }\n\n if (typesModule.isBlockStatement(stmt)) {\n collectTemporalDeadZonesFromBlock(stmt, localNames, temporalDeadZonesByName, typesModule);\n } else if (typesModule.isIfStatement(stmt)) {\n collectTemporalDeadZonesFromStatement(\n stmt.consequent,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n if (stmt.alternate) {\n collectTemporalDeadZonesFromStatement(\n stmt.alternate,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n } else if (\n typesModule.isForStatement(stmt) ||\n typesModule.isForInStatement(stmt) ||\n typesModule.isForOfStatement(stmt) ||\n typesModule.isWhileStatement(stmt) ||\n typesModule.isDoWhileStatement(stmt)\n ) {\n collectTemporalDeadZonesFromStatement(\n stmt.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n } else if (typesModule.isSwitchStatement(stmt)) {\n collectTemporalDeadZonesFromSwitch(stmt, localNames, temporalDeadZonesByName, typesModule);\n } else if (typesModule.isTryStatement(stmt)) {\n collectTemporalDeadZonesFromBlock(\n stmt.block,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n if (stmt.handler) {\n collectTemporalDeadZonesFromBlock(\n stmt.handler.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n if (stmt.finalizer) {\n collectTemporalDeadZonesFromBlock(\n stmt.finalizer,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n } else if (typesModule.isLabeledStatement(stmt) || typesModule.isWithStatement(stmt)) {\n collectTemporalDeadZonesFromStatement(\n stmt.body,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n}\n\nfunction collectTemporalDeadZonesFromBlock(\n block: t.BlockStatement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n addTemporalDeadZonesFromStatements(\n block.body,\n block.start,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n\n for (const stmt of block.body) {\n collectTemporalDeadZonesFromStatement(\n stmt,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n}\n\nfunction collectTemporalDeadZonesFromSwitch(\n stmt: t.SwitchStatement,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n for (const caseClause of stmt.cases) {\n addTemporalDeadZonesFromStatements(\n caseClause.consequent,\n stmt.start,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n\n for (const consequent of caseClause.consequent) {\n collectTemporalDeadZonesFromStatement(\n consequent,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n }\n }\n}\n\nfunction addTemporalDeadZonesFromStatements(\n statements: t.Statement[],\n scopeStart: number | null | undefined,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n if (scopeStart == null) {\n return;\n }\n\n for (const stmt of statements) {\n if (typesModule.isVariableDeclaration(stmt) && stmt.kind !== 'var') {\n addVariableDeclarationTemporalDeadZones(\n stmt,\n scopeStart,\n localNames,\n temporalDeadZonesByName,\n typesModule,\n );\n } else if (typesModule.isClassDeclaration(stmt) && stmt.id) {\n addTemporalDeadZone(\n stmt.id.name,\n scopeStart,\n stmt.end,\n localNames,\n temporalDeadZonesByName,\n );\n }\n }\n}\n\nfunction addVariableDeclarationTemporalDeadZones(\n stmt: t.VariableDeclaration,\n scopeStart: number,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n typesModule: BabelTypesModule,\n): void {\n for (const decl of stmt.declarations) {\n for (const name of getPatternIdentifiers(decl.id, typesModule)) {\n addTemporalDeadZone(name, scopeStart, stmt.end, localNames, temporalDeadZonesByName);\n }\n }\n}\n\nfunction addTemporalDeadZone(\n name: string,\n start: number,\n end: number | null | undefined,\n localNames: Set<string>,\n temporalDeadZonesByName: Map<string, LocalVariableTemporalDeadZone[]>,\n): void {\n if (end == null || !localNames.has(name)) {\n return;\n }\n\n const existingZones = temporalDeadZonesByName.get(name) ?? [];\n existingZones.push({ start, end });\n temporalDeadZonesByName.set(name, existingZones);\n}\n\nfunction getPatternIdentifiers(pattern: t.Node, typesModule: BabelTypesModule): string[] {\n if (typesModule.isIdentifier(pattern)) {\n return [pattern.name];\n }\n\n if (typesModule.isRestElement(pattern)) {\n return typesModule.isIdentifier(pattern.argument)\n ? [pattern.argument.name]\n : getPatternIdentifiers(pattern.argument, typesModule);\n }\n\n if (typesModule.isAssignmentPattern(pattern)) {\n return getPatternIdentifiers(pattern.left, typesModule);\n }\n\n if (typesModule.isObjectPattern(pattern)) {\n return pattern.properties.flatMap((property) => {\n if (typesModule.isRestElement(property)) {\n return getPatternIdentifiers(property.argument, typesModule);\n }\n\n return getPatternIdentifiers(property.value, typesModule);\n });\n }\n\n if (typesModule.isArrayPattern(pattern)) {\n return pattern.elements.flatMap((element) => {\n if (!element) {\n return [];\n }\n\n return getPatternIdentifiers(element, typesModule);\n });\n }\n\n if (typesModule.isTSParameterProperty(pattern)) {\n return typesModule.isIdentifier(pattern.parameter) ? [pattern.parameter.name] : [];\n }\n\n return [];\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 { ParserPlugin } from '@babel/parser';\nimport type _traverse from '@babel/traverse';\nimport type * as BabelTypes from '@babel/types';\nimport type MagicStringType from 'magic-string';\nimport type { SourceMap } from 'magic-string';\n\nimport { SKIP_INSTRUMENTATION_COMMENT } from '../constants';\nimport type { DecoratorSyntax, FunctionKind } from '../types';\n\nimport type { BabelPath, BabelTypesModule } from './babel-path.types';\nimport { resolveCjsDefaultExport } from './cjs-interop';\nimport { generateFunctionId, getFunctionName } from './functionId';\nimport { canInstrumentFunction, shouldSkipFunction } from './instrumentation';\nimport { getLocalVariableDeclarations, getParameterNames } from './scopeTracker';\nimport type { LocalVariableDeclaration } from './scopeTracker';\n\ntype TraverseFn = typeof _traverse;\ntype ParseFn = (\n code: string,\n options: {\n sourceType: 'unambiguous';\n plugins: ParserPlugin[];\n sourceFilename: string;\n },\n) => BabelTypes.File;\ntype MagicStringConstructor = typeof import('magic-string').default;\n\n/**\n * Optional peer dependencies that must be present at runtime for the\n * Live Debugger transform to work. They are declared as optional peer\n * dependencies on the published packages so users who don't enable the\n * plugin don't have to install them.\n */\nconst REQUIRED_PEER_DEPS = [\n '@babel/parser',\n '@babel/traverse',\n '@babel/types',\n 'magic-string',\n] as const;\ntype RequiredPeerDep = (typeof REQUIRED_PEER_DEPS)[number];\n\n// Node attaches a string `code` to filesystem/module resolution errors.\ntype NodeModuleError = Error & { code?: string };\n\nlet hasLoadedTransformRuntime = false;\nlet parse: ParseFn;\nlet traverse: TraverseFn;\nlet babelTypes: BabelTypesModule;\nlet MagicString: MagicStringConstructor;\n\nconst getTransformRuntime = (): void => {\n if (!hasLoadedTransformRuntime) {\n // Lazy-load heavy peer deps only when we actually instrument a file.\n // `require()` (not `import()`) because the transform hook is synchronous.\n // `requireOptionalPeerDep` rewrites `MODULE_NOT_FOUND` into a message\n // pointing users at the install step.\n parse = requireOptionalPeerDep<{ parse: ParseFn }>('@babel/parser').parse;\n traverse = resolveCjsDefaultExport(\n requireOptionalPeerDep<TraverseFn | { default: TraverseFn }>('@babel/traverse'),\n );\n babelTypes = requireOptionalPeerDep<BabelTypesModule>('@babel/types');\n MagicString = resolveCjsDefaultExport(\n requireOptionalPeerDep<MagicStringConstructor | { default: MagicStringConstructor }>(\n 'magic-string',\n ),\n );\n\n hasLoadedTransformRuntime = true;\n }\n};\n\n/**\n * Wrapper around `require()` that turns `MODULE_NOT_FOUND` into a clear,\n * actionable error pointing at our optional peer dependencies.\n *\n * The name is restricted to the list of known optional peer deps so each\n * require uses a literal string (survives bundling and satisfies lint rules).\n */\nfunction requireOptionalPeerDep<T>(name: RequiredPeerDep): T {\n try {\n return loadKnownPeerDep(name) as T;\n } catch (error) {\n throw rewrapMissingPeerDepError(error);\n }\n}\n\nfunction loadKnownPeerDep(name: RequiredPeerDep): unknown {\n switch (name) {\n case '@babel/parser':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/parser');\n case '@babel/traverse':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/traverse');\n case '@babel/types':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('@babel/types');\n case 'magic-string':\n // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires\n return require('magic-string');\n default: {\n const exhaustive: never = name;\n throw new Error(`Unknown peer dependency: ${exhaustive as string}`);\n }\n }\n}\n\nfunction rewrapMissingPeerDepError(error: unknown): Error {\n if (!isMissingPeerDepError(error)) {\n return error instanceof Error ? error : new Error(String(error));\n }\n const missingDep = REQUIRED_PEER_DEPS.find((dep) => error.message.includes(dep));\n const target = missingDep ?? REQUIRED_PEER_DEPS.join(', ');\n return new Error(\n `Datadog Live Debugger could not load \"${target}\". ` +\n `It is an optional peer dependency that must be installed in your project ` +\n `when the \\`liveDebugger\\` plugin is enabled. Install the peer dependencies with: ` +\n `\\`npm install --save-dev ${REQUIRED_PEER_DEPS.join(' ')}\\` ` +\n `(or the yarn/pnpm/bun equivalent). ` +\n `Underlying error: ${error.message}`,\n );\n}\n\nfunction isMissingPeerDepError(error: unknown): error is NodeModuleError {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = (error as NodeModuleError).code;\n if (code !== 'MODULE_NOT_FOUND' && code !== 'ERR_MODULE_NOT_FOUND') {\n return false;\n }\n return REQUIRED_PEER_DEPS.some((dep) => error.message.includes(dep));\n}\n\nfunction escapeSingleQuotedJavaScriptString(value: string): string {\n return value.replace(/['\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case \"'\":\n return \"\\\\'\";\n case '\\\\':\n return '\\\\\\\\';\n case '\\n':\n return '\\\\n';\n case '\\r':\n return '\\\\r';\n case '\\u2028':\n return '\\\\u2028';\n case '\\u2029':\n return '\\\\u2029';\n default:\n return character;\n }\n });\n}\n\nconst HAS_FUNCTION_SYNTAX = /\\bfunction\\b|=>|\\bclass\\b|\\)\\s*\\{/;\n\ninterface ReturnInfo {\n start: number;\n end: number;\n argStart: number | undefined;\n argEnd: number | undefined;\n hasSequenceExpressionArgument: boolean;\n}\n\ninterface FunctionTarget {\n bodyStart: number;\n bodyEnd: number;\n functionEnd: number;\n isExpressionBody: boolean;\n hasSequenceExpressionBody: boolean;\n aliasesExpressionBodySuperCall: boolean;\n needsTrailingReturn: boolean;\n useThisAlias: boolean;\n bodyParenStart: number | undefined;\n directivesEnd: number | undefined;\n functionId: string;\n probeVarName: string;\n probeIdx: string;\n entryVars: string[];\n localVars: LocalVariableDeclaration[];\n returns: ReturnInfo[];\n}\n\ninterface SuperCallTarget {\n start: number;\n end: number;\n}\n\ninterface ConstructorThisAliasTarget {\n bodyStart: number;\n superCalls: SuperCallTarget[];\n}\n\nexport interface TransformOptions {\n code: string;\n filePath: string;\n buildRoot: string;\n honorSkipComments: boolean;\n functionTypes: FunctionKind[] | undefined;\n namedOnly: boolean;\n decorators: DecoratorSyntax;\n}\n\n/**\n * Build the Babel parser plugin list. Decorators are opt-in per proposal\n * because Babel cannot enable the legacy and Stage 3 grammars simultaneously.\n */\nfunction getParserPlugins(decorators: DecoratorSyntax): ParserPlugin[] {\n if (decorators === 'modern') {\n // TC39 Stage 3 decorators, including `accessor` auto-accessor fields.\n return ['jsx', 'typescript', 'decorators', 'decoratorAutoAccessors'];\n }\n\n // TypeScript's `experimentalDecorators` grammar (also allows parameter decorators).\n return ['jsx', 'typescript', 'decorators-legacy'];\n}\n\nexport interface TransformResult {\n code: string;\n map?: SourceMap;\n failedCount: number;\n instrumentedCount: number;\n skippedByCommentCount: number;\n skippedFileCount: number;\n skippedUnsupportedCount: number;\n totalFunctions: number;\n}\n\n/**\n * Transform JavaScript code to add Live Debugger instrumentation.\n * Uses Babel to parse and read the AST, then MagicString for injection.\n */\nexport function transformCode(options: TransformOptions): TransformResult {\n const { code, filePath, buildRoot, honorSkipComments, functionTypes, namedOnly, decorators } =\n options;\n\n let failedCount = 0;\n let instrumentedCount = 0;\n let skippedByCommentCount = 0;\n let skippedUnsupportedCount = 0;\n let totalFunctions = 0;\n\n if (containsUnsupportedImports(code)) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 1,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n if (!HAS_FUNCTION_SYNTAX.test(code)) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n getTransformRuntime();\n const ast = parse(code, {\n sourceType: 'unambiguous',\n plugins: getParserPlugins(decorators),\n sourceFilename: filePath,\n });\n\n // Read-only traverse: collect instrumentation targets without mutating the AST\n const targets: FunctionTarget[] = [];\n const constructorBodyStartsByNode = new Map<BabelTypes.Node, number>();\n const constructorsUsingThisAlias = new Set<BabelTypes.Node>();\n const superCallsByConstructorNode = new Map<BabelTypes.Node, SuperCallTarget[]>();\n const anonymousCountByParent = new Map<BabelTypes.Node, number>();\n let probeVarCounter = 0;\n\n // @babel/parser and @babel/traverse bundle separate copies of @babel/types,\n // causing a structural type mismatch. The cast is safe: parse() returns a\n // valid AST that traverse() accepts at runtime.\n traverse(ast as unknown as BabelTypes.Node, {\n Function(path: BabelPath<BabelTypes.Function>) {\n totalFunctions++;\n\n const derivedConstructor = getDerivedConstructor(path, babelTypes);\n if (derivedConstructor) {\n constructorBodyStartsByNode.set(derivedConstructor, derivedConstructor.body.start!);\n superCallsByConstructorNode.set(\n derivedConstructor,\n getSuperCallTargets(derivedConstructor.body.body, babelTypes),\n );\n }\n\n if (!canInstrumentFunction(path, babelTypes)) {\n skippedUnsupportedCount++;\n return;\n }\n\n if (\n honorSkipComments &&\n shouldSkipFunction(path, SKIP_INSTRUMENTATION_COMMENT, babelTypes)\n ) {\n skippedByCommentCount++;\n return;\n }\n\n if (functionTypes && !functionTypes.includes(getFunctionKind(path.node, babelTypes))) {\n skippedUnsupportedCount++;\n return;\n }\n\n if (namedOnly && !getFunctionName(path, babelTypes)) {\n skippedUnsupportedCount++;\n return;\n }\n\n // O(1) anonymous sibling index via pre-indexed Map\n let anonymousSiblingIndex = 0;\n if (!getFunctionName(path, babelTypes)) {\n const parentNode = path.parentPath?.node;\n if (parentNode) {\n anonymousSiblingIndex = anonymousCountByParent.get(parentNode) || 0;\n anonymousCountByParent.set(parentNode, anonymousSiblingIndex + 1);\n }\n }\n\n const functionId = generateFunctionId(\n filePath,\n buildRoot,\n path,\n anonymousSiblingIndex,\n babelTypes,\n );\n\n try {\n const node = path.node;\n const idx = probeVarCounter++;\n const probeVarName = `$dd_p${idx}`;\n const entryVars = getParameterNames(node, babelTypes);\n const localVars = getLocalVariableDeclarations(node, babelTypes);\n\n const isExpressionBody =\n babelTypes.isArrowFunctionExpression(node) &&\n !babelTypes.isBlockStatement(node.body);\n const hasSequenceExpressionBody =\n isExpressionBody && babelTypes.isSequenceExpression(node.body);\n const constructorPath = getDerivedConstructorForLexicalThis(path, babelTypes);\n const useThisAlias = constructorPath != null;\n if (constructorPath) {\n constructorsUsingThisAlias.add(constructorPath.node);\n constructorBodyStartsByNode.set(\n constructorPath.node,\n constructorPath.node.body.start!,\n );\n }\n\n const returns: ReturnInfo[] = [];\n const needsTrailingReturn =\n isExpressionBody ||\n !babelTypes.isBlockStatement(node.body) ||\n !alwaysReturns(node.body.body, babelTypes);\n if (!isExpressionBody && babelTypes.isBlockStatement(node.body)) {\n collectReturnStatements(node.body.body, returns, babelTypes);\n }\n\n let directivesEnd: number | undefined;\n if (\n !isExpressionBody &&\n babelTypes.isBlockStatement(node.body) &&\n node.body.directives.length > 0\n ) {\n const lastDirective = node.body.directives[node.body.directives.length - 1];\n directivesEnd = lastDirective.end!;\n }\n\n targets.push({\n bodyStart: node.body.start!,\n bodyEnd: node.body.end!,\n functionEnd: node.end!,\n isExpressionBody,\n hasSequenceExpressionBody,\n aliasesExpressionBodySuperCall:\n useThisAlias &&\n isExpressionBody &&\n isSuperCallExpression(node.body, babelTypes),\n needsTrailingReturn,\n useThisAlias,\n bodyParenStart:\n isExpressionBody && typeof node.body.extra?.parenStart === 'number'\n ? node.body.extra.parenStart\n : undefined,\n directivesEnd,\n functionId,\n probeVarName,\n probeIdx: String(idx),\n entryVars,\n localVars,\n returns,\n });\n\n instrumentedCount++;\n } catch (error) {\n failedCount++;\n }\n },\n });\n\n if (instrumentedCount === 0) {\n return {\n code,\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n }\n\n const s = new MagicString(code);\n const superCallRangesHandledByExpressionBodies =\n getSuperCallRangesHandledByExpressionBodies(targets);\n const constructorThisAliasTargets = getConstructorThisAliasTargets(\n constructorsUsingThisAlias,\n constructorBodyStartsByNode,\n superCallsByConstructorNode,\n superCallRangesHandledByExpressionBodies,\n );\n\n // Process inner (deeper) functions before outer ones so same-side\n // MagicString insertions at shared positions stack in the correct order.\n for (let i = targets.length - 1; i >= 0; i--) {\n injectInstrumentation(s, code, targets[i]);\n }\n for (const target of constructorThisAliasTargets) {\n injectConstructorThisAlias(s, code, target);\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({ source: filePath, hires: true }),\n failedCount,\n instrumentedCount,\n skippedByCommentCount,\n skippedFileCount: 0,\n skippedUnsupportedCount,\n totalFunctions,\n };\n}\n\n/**\n * Inject instrumentation for a single function.\n */\nfunction injectInstrumentation(s: MagicStringType, code: string, target: FunctionTarget): void {\n const {\n probeVarName,\n probeIdx,\n functionId,\n entryVars,\n localVars,\n returns,\n bodyStart,\n bodyEnd,\n functionEnd,\n isExpressionBody,\n hasSequenceExpressionBody,\n aliasesExpressionBodySuperCall,\n useThisAlias,\n bodyParenStart,\n directivesEnd,\n } = target;\n\n const rvVarName = `$dd_rv${probeIdx}`;\n const receiverArg = useThisAlias ? '$dd_t' : 'this';\n\n const entryVarsList = entryVars.join(', ');\n\n const hasParams = entryVarsList !== '';\n\n const entryArgs = `{${entryVarsList}}`;\n const argsArg = hasParams ? `, ${entryArgs}` : '';\n\n const escapedFunctionId = escapeSingleQuotedJavaScriptString(functionId);\n // `$dd_entry` swaps the probe list for a handle identifying this invocation\n // (undefined when no probe produced an entry), reusing the same binding so\n // every exit hook pairs with its own entry state, not a concurrent call's.\n const probeDecl = `let ${probeVarName} = $dd_probes('${escapedFunctionId}');`;\n const entryCall = `if (${probeVarName}) ${probeVarName} = $dd_entry(${probeVarName}, ${receiverArg}${argsArg});`;\n const catchBlock = `catch(e) { if (${probeVarName}) $dd_throw(${probeVarName}, e, ${receiverArg}${argsArg}); throw e; }`;\n\n if (isExpressionBody) {\n // Arrow expression body: (a) => expr\n // Wrap in block body with temp variable to avoid duplicating nested expressions\n\n // Handle parenthesized expression bodies: () => ({key: value})\n // The parentheses must be removed when converting to a block body,\n // otherwise the output would be => ({block_code}) which is a syntax error.\n // Babel stores nested bodies like `((1))` as body `1`, so every wrapper\n // paren around the body range must be removed before injecting a block.\n //\n // Blank the paren with `update(..., '')` rather than `remove()`. When the\n // body is itself an instrumented function whose end abuts the closing\n // paren (e.g. `(a) => ((b) => a + b)`), that inner function has already\n // appended its instrumentation suffix to the same offset. `remove()`\n // clears the chunk's intro/outro and would drop that suffix, producing\n // invalid JavaScript; `update()` edits the content only and preserves it.\n if (bodyParenStart != null) {\n const openingParens = getLeadingArrowBodyParens(code, bodyParenStart, bodyStart);\n const closingParens = getTrailingArrowBodyParens(code, bodyEnd, functionEnd);\n const parenCount = Math.min(openingParens.length, closingParens.length);\n\n for (let i = 0; i < parenCount; i++) {\n const openingParen = openingParens[i];\n const closingParen = closingParens[i];\n s.update(openingParen, openingParen + 1, '');\n s.update(closingParen, closingParen + 1, '');\n }\n }\n\n const prefix = [\n '{',\n probeDecl,\n 'try {',\n entryCall,\n aliasesExpressionBodySuperCall\n ? `const ${rvVarName} = ($dd_t = `\n : `const ${rvVarName} = `,\n ]\n .filter(Boolean)\n .join('\\n');\n\n const returnCaptureArgs = getReturnCaptureArgs(entryArgs, hasParams, localVars, bodyEnd);\n let expressionSuffix = hasSequenceExpressionBody ? ');' : ';';\n if (aliasesExpressionBodySuperCall) {\n expressionSuffix = hasSequenceExpressionBody ? '));' : ');';\n }\n const suffix = [\n expressionSuffix,\n `if (${probeVarName}) $dd_return(${probeVarName}, ${rvVarName}, ${receiverArg}${returnCaptureArgs});`,\n `return ${rvVarName};`,\n `} ${catchBlock}`,\n '}',\n ].join('\\n');\n\n // Anchor each injected line to the original expression's location by\n // editing the first boundary char and appending after the body. This\n // avoids overwriting nested function instrumentation when a curried\n // arrow's expression body ends at the inner function's closing brace.\n // For a single-char body (e.g. `() => 1`) the two ranges would\n // collide, so we fall back to one update covering the whole body.\n if (bodyEnd - bodyStart >= 2) {\n const bodyPrefix = hasSequenceExpressionBody\n ? `${prefix}(${code[bodyStart]}`\n : prefix + code[bodyStart];\n s.update(bodyStart, bodyStart + 1, bodyPrefix);\n s.appendRight(bodyEnd, suffix);\n } else {\n s.update(bodyStart, bodyEnd, prefix + code.slice(bodyStart, bodyEnd) + suffix);\n }\n } else {\n // Block body function\n const preamble = [probeDecl, 'try {', `let ${rvVarName};`, entryCall]\n .filter(Boolean)\n .join('\\n');\n\n // Wrap return statements BEFORE the boundary updates so that when\n // a semicolon-free final return shares its argEnd position with\n // bodyEnd - 1, the return suffix is appended to the preceding chunk\n // (its outro) and ends up before the postamble in the generated code.\n for (const ret of returns) {\n const returnCaptureArgs = getReturnCaptureArgs(\n entryArgs,\n hasParams,\n localVars,\n ret.start,\n );\n\n if (ret.argStart != null && ret.argEnd != null) {\n // return EXPR; → return ($dd_rvN = EXPR, probe ? $dd_return(...) : $dd_rvN);\n const assignmentPrefix = ret.hasSequenceExpressionArgument\n ? `(${rvVarName} = (`\n : `(${rvVarName} = `;\n const assignmentSuffix = ret.hasSequenceExpressionArgument ? ')' : '';\n\n s.appendLeft(ret.argStart, assignmentPrefix);\n s.appendRight(\n ret.argEnd,\n `${assignmentSuffix}, ${probeVarName} ? $dd_return(${probeVarName}, ${rvVarName}, ${receiverArg}${returnCaptureArgs}) : ${rvVarName})`,\n );\n } else {\n // return; → if (probe) $dd_return(...); return;\n s.appendLeft(\n ret.start,\n `if (${probeVarName}) $dd_return(${probeVarName}, undefined, ${receiverArg}${returnCaptureArgs}); `,\n );\n }\n }\n\n // Wrap the boundary character (last directive char or the body's\n // opening `{`) with `<char><preamble>`. Editing through `update()`\n // makes magic-string emit a source-map segment for every line of\n // the new content, all anchored at that boundary char's location —\n // so injected preamble lines map to the function's own line instead\n // of to nothing.\n //\n // For directives, an additional leading newline keeps the preamble\n // on its own line (the directive's trailing `;` already ends a\n // statement, but its terminator stays on the directive's line).\n if (directivesEnd != null) {\n const anchor = directivesEnd - 1;\n s.update(anchor, directivesEnd, `${code[anchor]}\\n${preamble}`);\n } else {\n s.update(bodyStart, bodyStart + 1, `${code[bodyStart]}${preamble}`);\n }\n\n // Build the postamble. The optional trailing-return helper is\n // included here (rather than as a separate appendLeft) so that the\n // single boundary update for `}` covers it; this keeps the trailing\n // helper's source-map segment anchored to the closing brace too.\n const trailingReturnCaptureArgs = getReturnCaptureArgs(\n entryArgs,\n hasParams,\n localVars,\n bodyEnd,\n );\n const trailingReturn = target.needsTrailingReturn\n ? `if (${probeVarName}) $dd_return(${probeVarName}, undefined, ${receiverArg}${trailingReturnCaptureArgs});\\n`\n : '';\n const postamble = `\\n${trailingReturn}} ${catchBlock}\\n`;\n s.update(bodyEnd - 1, bodyEnd, `${postamble}${code[bodyEnd - 1]}`);\n }\n}\n\nfunction injectConstructorThisAlias(\n s: MagicStringType,\n code: string,\n target: ConstructorThisAliasTarget,\n): void {\n s.update(target.bodyStart, target.bodyStart + 1, `${code[target.bodyStart]}let $dd_t;`);\n\n for (const superCall of target.superCalls) {\n s.appendLeft(superCall.start, '($dd_t = ');\n s.appendLeft(superCall.end, ')');\n }\n}\n\nfunction getSuperCallTargets(\n statements: BabelTypes.Statement[],\n typesModule: BabelTypesModule,\n): SuperCallTarget[] {\n const targets: SuperCallTarget[] = [];\n for (const statement of statements) {\n collectSuperCallTargetsFromNode(statement, targets, typesModule);\n }\n\n return targets;\n}\n\nfunction collectSuperCallTargetsFromNode(\n node: BabelTypes.Node,\n targets: SuperCallTarget[],\n typesModule: BabelTypesModule,\n): void {\n if (isSuperCallExpression(node, typesModule)) {\n targets.push({\n start: node.start!,\n end: node.end!,\n });\n }\n\n const values = Object.values(node);\n for (const value of values) {\n if (Array.isArray(value)) {\n for (const item of value) {\n collectSuperCallTargetsFromUnknown(item, targets, typesModule);\n }\n } else {\n collectSuperCallTargetsFromUnknown(value, targets, typesModule);\n }\n }\n}\n\nfunction collectSuperCallTargetsFromUnknown(\n value: unknown,\n targets: SuperCallTarget[],\n typesModule: BabelTypesModule,\n): void {\n if (!typesModule.isNode(value)) {\n return;\n }\n\n if (typesModule.isFunction(value) && !typesModule.isArrowFunctionExpression(value)) {\n return;\n }\n\n collectSuperCallTargetsFromNode(value, targets, typesModule);\n}\n\nfunction getConstructorThisAliasTargets(\n constructorsUsingThisAlias: Set<BabelTypes.Node>,\n constructorBodyStartsByNode: Map<BabelTypes.Node, number>,\n superCallsByConstructorNode: Map<BabelTypes.Node, SuperCallTarget[]>,\n superCallRangesHandledByExpressionBodies: Set<string>,\n): ConstructorThisAliasTarget[] {\n const targets: ConstructorThisAliasTarget[] = [];\n\n for (const constructorNode of constructorsUsingThisAlias) {\n const bodyStart = constructorBodyStartsByNode.get(constructorNode);\n if (bodyStart == null) {\n continue;\n }\n\n targets.push({\n bodyStart,\n superCalls: (superCallsByConstructorNode.get(constructorNode) ?? []).filter(\n (superCall) =>\n !superCallRangesHandledByExpressionBodies.has(getRangeKey(superCall)),\n ),\n });\n }\n\n return targets;\n}\n\nfunction getSuperCallRangesHandledByExpressionBodies(targets: FunctionTarget[]): Set<string> {\n const ranges = new Set<string>();\n for (const target of targets) {\n if (target.aliasesExpressionBodySuperCall) {\n ranges.add(getRangeKey({ start: target.bodyStart, end: target.bodyEnd }));\n }\n }\n\n return ranges;\n}\n\nfunction getRangeKey(range: SuperCallTarget): string {\n return `${range.start}:${range.end}`;\n}\n\nfunction getDerivedConstructor(\n path: BabelPath<BabelTypes.Function>,\n typesModule: BabelTypesModule,\n): BabelTypes.ClassMethod | undefined {\n if (\n typesModule.isClassMethod(path.node) &&\n path.node.kind === 'constructor' &&\n isDerivedClassMethod(path, typesModule)\n ) {\n return path.node;\n }\n\n return undefined;\n}\n\nfunction getDerivedConstructorForLexicalThis(\n path: BabelPath,\n typesModule: BabelTypesModule,\n): BabelPath<BabelTypes.ClassMethod> | undefined {\n if (typesModule.isFunction(path.node) && !typesModule.isArrowFunctionExpression(path.node)) {\n return undefined;\n }\n\n let current = path.parentPath;\n while (current) {\n const node = current.node;\n if (typesModule.isClassMethod(node) && node.kind === 'constructor') {\n if (!isDerivedClassMethod(current, typesModule)) {\n return undefined;\n }\n\n return {\n node,\n parent: current.parent,\n parentPath: current.parentPath,\n };\n }\n\n if (typesModule.isFunction(node)) {\n if (typesModule.isArrowFunctionExpression(node)) {\n current = current.parentPath;\n continue;\n }\n\n return undefined;\n }\n\n current = current.parentPath;\n }\n\n return undefined;\n}\n\nfunction isSuperCallExpression(\n node: BabelTypes.Node,\n typesModule: BabelTypesModule,\n): node is BabelTypes.CallExpression {\n return typesModule.isCallExpression(node) && typesModule.isSuper(node.callee);\n}\n\nfunction isDerivedClassMethod(path: BabelPath, typesModule: BabelTypesModule): boolean {\n const classPath = path.parentPath?.parentPath;\n if (!classPath) {\n return false;\n }\n\n const classNode = classPath.node;\n return (\n (typesModule.isClassDeclaration(classNode) || typesModule.isClassExpression(classNode)) &&\n classNode.superClass != null\n );\n}\n\nfunction getReturnCaptureArgs(\n entryArgs: string,\n hasParams: boolean,\n localVars: LocalVariableDeclaration[],\n exitPosition: number,\n): string {\n const localsArg = getLocalCaptureArg(localVars, exitPosition);\n if (hasParams && localsArg) {\n return `, ${entryArgs}, ${localsArg}`;\n }\n if (hasParams) {\n return `, ${entryArgs}`;\n }\n if (localsArg) {\n return `, undefined, ${localsArg}`;\n }\n return '';\n}\n\nfunction getLeadingArrowBodyParens(code: string, start: number, end: number): number[] {\n return collectArrowWrapperParens(code, start, end, '(');\n}\n\nfunction getTrailingArrowBodyParens(code: string, start: number, end: number): number[] {\n return collectArrowWrapperParens(code, start, end, ')');\n}\n\n/**\n * Collect the positions of wrapper parens around an arrow expression body.\n *\n * Only whitespace, comments, and the wrapping parens themselves can appear\n * between the outermost paren and the body (leading) or between the body and\n * the arrow's end (trailing). Comments are skipped so that parens inside a\n * comment are not mistaken for wrapper parens, which would otherwise misalign\n * removal and emit invalid JavaScript.\n *\n * Any `/` in this range necessarily starts a comment (division/regex are not\n * grammatically valid here), so no string/regex handling is required.\n */\nfunction collectArrowWrapperParens(\n code: string,\n start: number,\n end: number,\n paren: '(' | ')',\n): number[] {\n const parens: number[] = [];\n let i = start;\n while (i < end) {\n const char = code[i];\n if (char === '/') {\n const next = code[i + 1];\n if (next === '/') {\n i += 2;\n while (i < end && code[i] !== '\\n') {\n i++;\n }\n continue;\n }\n if (next === '*') {\n i += 2;\n while (i < end && !(code[i] === '*' && code[i + 1] === '/')) {\n i++;\n }\n i += 2;\n continue;\n }\n } else if (char === paren) {\n parens.push(i);\n }\n i++;\n }\n return parens;\n}\n\nfunction getLocalCaptureArg(\n localVars: LocalVariableDeclaration[],\n exitPosition: number,\n): string | undefined {\n const availableLocals = localVars\n .filter(\n ({ declarationEnd, temporalDeadZones }) =>\n declarationEnd <= exitPosition &&\n !isInTemporalDeadZone(temporalDeadZones, exitPosition),\n )\n .map(({ name }) => name);\n\n if (availableLocals.length === 0) {\n return undefined;\n }\n\n return `{${availableLocals.join(', ')}}`;\n}\n\nfunction isInTemporalDeadZone(\n temporalDeadZones: LocalVariableDeclaration['temporalDeadZones'],\n position: number,\n): boolean {\n return temporalDeadZones.some(({ start, end }) => start <= position && position < end);\n}\n\n/**\n * Recursively collect return statements within a function body,\n * skipping nested function/class bodies.\n */\nfunction collectReturnStatements(\n statements: BabelTypes.Statement[],\n returns: ReturnInfo[],\n typesModule: BabelTypesModule,\n): void {\n for (const stmt of statements) {\n if (typesModule.isReturnStatement(stmt)) {\n returns.push({\n start: stmt.start!,\n end: stmt.end!,\n argStart: stmt.argument?.start ?? undefined,\n argEnd: stmt.argument?.end ?? undefined,\n hasSequenceExpressionArgument: typesModule.isSequenceExpression(stmt.argument),\n });\n continue;\n }\n\n if (typesModule.isFunctionDeclaration(stmt) || typesModule.isClassDeclaration(stmt)) {\n continue;\n }\n\n if (typesModule.isBlockStatement(stmt)) {\n collectReturnStatements(stmt.body, returns, typesModule);\n } else if (typesModule.isIfStatement(stmt)) {\n collectReturnStatements([stmt.consequent], returns, typesModule);\n if (stmt.alternate) {\n collectReturnStatements([stmt.alternate], returns, typesModule);\n }\n } else if (\n typesModule.isForStatement(stmt) ||\n typesModule.isForInStatement(stmt) ||\n typesModule.isForOfStatement(stmt) ||\n typesModule.isWhileStatement(stmt) ||\n typesModule.isDoWhileStatement(stmt)\n ) {\n collectReturnStatements([stmt.body], returns, typesModule);\n } else if (typesModule.isSwitchStatement(stmt)) {\n for (const caseClause of stmt.cases) {\n collectReturnStatements(caseClause.consequent, returns, typesModule);\n }\n } else if (typesModule.isTryStatement(stmt)) {\n collectReturnStatements(stmt.block.body, returns, typesModule);\n if (stmt.handler) {\n collectReturnStatements(stmt.handler.body.body, returns, typesModule);\n }\n if (stmt.finalizer) {\n collectReturnStatements(stmt.finalizer.body, returns, typesModule);\n }\n } else if (typesModule.isLabeledStatement(stmt)) {\n collectReturnStatements([stmt.body], returns, typesModule);\n } else if (typesModule.isWithStatement(stmt)) {\n collectReturnStatements([stmt.body], returns, typesModule);\n }\n }\n}\n\n/**\n * Lightweight control-flow check: does this statement list guarantee a return\n * on every path? Handles direct returns and exhaustive if/else branches.\n * Conservatively returns false for loops, switch, try/catch, etc.\n */\nfunction alwaysReturns(statements: BabelTypes.Statement[], typesModule: BabelTypesModule): boolean {\n if (statements.length === 0) {\n return false;\n }\n const last = statements[statements.length - 1];\n\n if (typesModule.isReturnStatement(last)) {\n return true;\n }\n\n if (typesModule.isIfStatement(last) && last.alternate) {\n const consequent = typesModule.isBlockStatement(last.consequent)\n ? last.consequent.body\n : [last.consequent];\n const alternate = typesModule.isBlockStatement(last.alternate)\n ? last.alternate.body\n : [last.alternate];\n return alwaysReturns(consequent, typesModule) && alwaysReturns(alternate, typesModule);\n }\n\n return false;\n}\n\nfunction getFunctionKind(node: BabelTypes.Function, typesModule: BabelTypesModule): FunctionKind {\n if (typesModule.isFunctionDeclaration(node)) {\n return 'functionDeclaration';\n }\n if (typesModule.isArrowFunctionExpression(node)) {\n return 'arrowFunction';\n }\n if (typesModule.isObjectMethod(node)) {\n return 'objectMethod';\n }\n if (typesModule.isClassPrivateMethod(node)) {\n return 'classPrivateMethod';\n }\n if (typesModule.isClassMethod(node)) {\n return 'classMethod';\n }\n return 'functionExpression';\n}\n\nfunction containsUnsupportedImports(code: string): boolean {\n return /['\"][^'\"]*(?:@css-module:|\\?worker\\b|\\?sprite\\b|dynamic!)[^'\"]*['\"]/.test(code);\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 VALID_FUNCTION_KINDS = [\n 'functionDeclaration',\n 'functionExpression',\n 'arrowFunction',\n 'objectMethod',\n 'classMethod',\n 'classPrivateMethod',\n] as const;\n\nexport type FunctionKind = (typeof VALID_FUNCTION_KINDS)[number];\nexport type FileExtensions = string[] | 'all';\n\n// Which decorator syntax the parser should accept. `legacy` matches\n// TypeScript's `experimentalDecorators` (Angular, NestJS, TypeORM, including\n// parameter decorators); `modern` matches the TC39 Stage 3 proposal\n// (`accessor` fields, decorators before `export`).\nexport const VALID_DECORATOR_SYNTAXES = ['legacy', 'modern'] as const;\n\nexport type DecoratorSyntax = (typeof VALID_DECORATOR_SYNTAXES)[number];\n\nexport type LiveDebuggerOptions = {\n enable?: boolean;\n include?: (string | RegExp)[];\n exclude?: (string | RegExp)[];\n fileExtensions?: FileExtensions;\n honorSkipComments?: boolean;\n functionTypes?: FunctionKind[];\n namedOnly?: boolean;\n decorators?: DecoratorSyntax;\n};\n\nexport type LiveDebuggerOptionsWithDefaults = {\n version: string | undefined;\n include: (string | RegExp)[];\n exclude: (string | RegExp)[];\n fileExtensions: FileExtensions;\n honorSkipComments: boolean;\n functionTypes: FunctionKind[] | undefined;\n namedOnly: boolean;\n decorators: DecoratorSyntax;\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, DEFAULT_FILE_EXTENSIONS, PLUGIN_NAME } from './constants';\nimport type { LiveDebuggerOptions, LiveDebuggerOptionsWithDefaults } from './types';\nimport { VALID_DECORATOR_SYNTAXES, VALID_FUNCTION_KINDS } from './types';\n\nconst red = chalk.bold.red;\nconst INVALID_FILE_EXTENSION_PATTERN = /[\\\\/?#]/;\n\nconst normalizeFileExtensions = (fileExtensions: readonly string[]): string[] => {\n const lowercaseExtensions = fileExtensions.map((extension) => extension.toLowerCase());\n return [...new Set(lowercaseExtensions)];\n};\n\nexport const validateOptions = (config: Options, log: Logger): LiveDebuggerOptionsWithDefaults => {\n const pluginConfig: LiveDebuggerOptions = config[CONFIG_KEY] || {};\n const metadataVersion = config.metadata?.version;\n const errors: string[] = [];\n\n // Validate include option\n if (pluginConfig.include !== undefined) {\n if (!Array.isArray(pluginConfig.include)) {\n errors.push(`${red('include')} must be an array of strings or RegExp`);\n } else {\n for (const pattern of pluginConfig.include) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n errors.push(`${red('include')} patterns must be strings or RegExp`);\n break;\n }\n }\n }\n }\n\n // Validate exclude option\n if (pluginConfig.exclude !== undefined) {\n if (!Array.isArray(pluginConfig.exclude)) {\n errors.push(`${red('exclude')} must be an array of strings or RegExp`);\n } else {\n for (const pattern of pluginConfig.exclude) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n errors.push(`${red('exclude')} patterns must be strings or RegExp`);\n break;\n }\n }\n }\n }\n\n // Validate fileExtensions option\n if (pluginConfig.fileExtensions !== undefined && pluginConfig.fileExtensions !== 'all') {\n if (!Array.isArray(pluginConfig.fileExtensions)) {\n errors.push(`${red('fileExtensions')} must be an array of strings or \"all\"`);\n } else if (pluginConfig.fileExtensions.length === 0) {\n errors.push(`${red('fileExtensions')} must contain at least one extension`);\n } else {\n for (const extension of pluginConfig.fileExtensions) {\n if (\n typeof extension !== 'string' ||\n extension.length < 2 ||\n !extension.startsWith('.') ||\n INVALID_FILE_EXTENSION_PATTERN.test(extension)\n ) {\n errors.push(\n `${red('fileExtensions')} values must begin with \".\" and contain no path or query separators`,\n );\n break;\n }\n }\n }\n }\n\n // Validate honorSkipComments option\n if (\n pluginConfig.honorSkipComments !== undefined &&\n typeof pluginConfig.honorSkipComments !== 'boolean'\n ) {\n errors.push(`${red('honorSkipComments')} must be a boolean`);\n }\n\n // Validate functionTypes option\n if (pluginConfig.functionTypes !== undefined) {\n if (!Array.isArray(pluginConfig.functionTypes)) {\n errors.push(`${red('functionTypes')} must be an array of FunctionKind values`);\n } else {\n for (const kind of pluginConfig.functionTypes) {\n if (!VALID_FUNCTION_KINDS.includes(kind)) {\n errors.push(\n `${red('functionTypes')} contains invalid value \"${kind}\". Valid values: ${VALID_FUNCTION_KINDS.join(', ')}`,\n );\n break;\n }\n }\n }\n }\n\n // Validate namedOnly option\n if (pluginConfig.namedOnly !== undefined && typeof pluginConfig.namedOnly !== 'boolean') {\n errors.push(`${red('namedOnly')} must be a boolean`);\n }\n\n // Validate decorators option\n if (\n pluginConfig.decorators !== undefined &&\n !VALID_DECORATOR_SYNTAXES.includes(pluginConfig.decorators)\n ) {\n errors.push(`${red('decorators')} must be one of: ${VALID_DECORATOR_SYNTAXES.join(', ')}`);\n }\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 const configuredFileExtensions = pluginConfig.fileExtensions ?? DEFAULT_FILE_EXTENSIONS;\n const fileExtensions =\n configuredFileExtensions === 'all'\n ? configuredFileExtensions\n : normalizeFileExtensions(configuredFileExtensions);\n\n // Build the final configuration with defaults\n return {\n version: metadataVersion,\n include: pluginConfig.include ?? [],\n exclude: pluginConfig.exclude || [\n /\\/node_modules\\//,\n /\\.min\\.js$/,\n /\\/pyodide-lib\\//, // Bundled third-party Pyodide library\n /^vite\\//, // Vite internal modules\n /\\0/, // Virtual modules (Rollup/Vite convention)\n /commonjsHelpers\\.js$/, // Rollup commonjs helpers\n /__vite-browser-external/, // Vite browser externals\n /@datadog\\/browser-/, // Datadog browser SDK packages (when npm linked)\n /browser-sdk\\/packages\\//, // Datadog browser SDK source files\n ],\n fileExtensions,\n honorSkipComments: pluginConfig.honorSkipComments ?? true,\n functionTypes: pluginConfig.functionTypes,\n namedOnly: pluginConfig.namedOnly ?? false,\n decorators: pluginConfig.decorators ?? 'legacy',\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, GlobalContext, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport remapping from '@jridgewell/remapping';\nimport type { SourceMapInput } from '@jridgewell/remapping';\nimport type { SourceMap } from 'magic-string';\nimport type { SourceMapCompact, UnpluginBuildContext } from 'unplugin';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { createFileExtensionPattern, createFileFilter } from './filter';\nimport { getRuntimeBootstrap } from './runtime-bootstrap';\nimport { transformCode } from './transform';\nimport type { LiveDebuggerOptions, LiveDebuggerOptionsWithDefaults } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nconst DD_LD_LIMIT = Number(process.env.DD_LD_LIMIT) || Infinity;\n\n// Export types for factory integration\nexport type types = {\n LiveDebuggerOptions: LiveDebuggerOptions;\n};\n\nexport const getLiveDebuggerPlugin = (\n pluginOptions: LiveDebuggerOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n const shouldInstrumentFile = createFileFilter(pluginOptions);\n const fileExtensionPattern = createFileExtensionPattern(pluginOptions.fileExtensions);\n const nativeInclude = fileExtensionPattern ? [fileExtensionPattern] : pluginOptions.include;\n\n let instrumentedCount = 0;\n let failedCount = 0;\n let skippedByCommentCount = 0;\n let skippedFileCount = 0;\n let skippedUnsupportedCount = 0;\n let transformedFileCount = 0;\n let totalFunctions = 0;\n let totalFilesWithFunctions = 0;\n\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: nativeInclude,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n // Enforce all file filters at runtime because unplugin's\n // native filter is not applied in bundler child compilations\n // (e.g., web worker bundles in rspack/webpack).\n if (!shouldInstrumentFile(id)) {\n return { code };\n }\n\n if (totalFilesWithFunctions >= DD_LD_LIMIT) {\n return { code };\n }\n\n try {\n const result = transformCode({\n code,\n filePath: id,\n buildRoot: context.buildRoot,\n honorSkipComments: pluginOptions.honorSkipComments,\n functionTypes: pluginOptions.functionTypes,\n namedOnly: pluginOptions.namedOnly,\n decorators: pluginOptions.decorators,\n });\n\n instrumentedCount += result.instrumentedCount;\n totalFunctions += result.totalFunctions;\n failedCount += result.failedCount;\n skippedByCommentCount += result.skippedByCommentCount;\n skippedFileCount += result.skippedFileCount;\n skippedUnsupportedCount += result.skippedUnsupportedCount;\n\n if (result.totalFunctions > 0) {\n totalFilesWithFunctions++;\n }\n\n if (result.instrumentedCount === 0) {\n return {\n // No changes, return original code\n code,\n };\n }\n\n transformedFileCount++;\n\n const inputMap = getInputSourceMap(this);\n const composedMap =\n result.map && inputMap\n ? composeWithInputMap(result.map, inputMap, id, log)\n : result.map;\n\n return {\n code: result.code,\n map: composedMap,\n };\n } catch (e) {\n log.error(`Instrumentation Error in ${id}: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n buildEnd: () => {\n if (totalFunctions > 0) {\n log.info(\n `Live Debugger: ${instrumentedCount}/${totalFunctions} functions instrumented across ${transformedFileCount}/${totalFilesWithFunctions} files`,\n {\n forward: true,\n context: {\n failedCount,\n skippedByCommentCount,\n skippedFileCount,\n skippedUnsupportedCount,\n totalFilesWithFunctions,\n instrumentedCount,\n totalFunctions,\n transformedFileCount,\n },\n },\n );\n }\n },\n };\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options, log);\n\n // Inject no-op stubs for the runtime globals so instrumented code\n // doesn't crash when the Datadog Browser Debugger SDK is absent.\n // The SDK's init() overwrites these with the real implementations.\n context.inject({\n type: 'code',\n position: InjectPosition.BEFORE,\n injectIntoAllChunks: true,\n value: getRuntimeBootstrap(validatedOptions.version),\n });\n\n return [getLiveDebuggerPlugin(validatedOptions, context)];\n};\n\n/**\n * Return the source map produced by the previous loader, if any.\n */\nfunction getInputSourceMap(ctx: UnpluginBuildContext): SourceMapInput | undefined {\n const native = ctx.getNativeBuildContext?.();\n return (native as { inputSourceMap?: SourceMapInput })?.inputSourceMap;\n}\n\n/**\n * Compose a local source map with the previous loader's source map. The result maps instrumented\n * output directly back to original source coordinates.\n */\nfunction composeWithInputMap(\n instrumentMap: SourceMap,\n inputMap: SourceMapInput,\n id: string,\n log: ReturnType<GlobalContext['getLogger']>,\n): SourceMapCompact | SourceMap {\n try {\n return remapping(instrumentMap as unknown as SourceMapInput, (_file, ctx) =>\n ctx.depth === 1 ? inputMap : null,\n ) as unknown as SourceMapCompact;\n } catch (e) {\n log.error(`Failed to compose source map for ${id}: ${e}`, { forward: true });\n return instrumentMap;\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, GlobalStores } from '@dd/core/types';\n\nexport const initializeMetricsCollector = (context: GlobalContext, stores: GlobalStores) => {\n context.addMetric = (metric) => {\n stores.metrics.add(metric);\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Metric } from '@dd/core/types';\n\nconst filterTreeMetrics = (metric: Metric): Metric | null =>\n // Remove tree metrics because way too verbose\n !/modules\\.tree\\.(count|size)$/.test(metric.metric) ? metric : null;\n\nconst filterSourcemapsAndNodeModules = (metric: Metric): Metric | null =>\n metric.tags.some(\n (tag: string) =>\n // Remove sourcemaps.\n /^assetName:.*\\.map$/.test(tag) ||\n // Remove third parties.\n /^moduleName:\\/node_modules/.test(tag),\n )\n ? null\n : metric;\n\nconst filterMetricsOnThreshold = (metric: Metric): Metric | null => {\n const thresholds = {\n size: 100000,\n count: 10,\n duration: 1000,\n };\n if (/^sourcemaps\\.upload\\.(failure|retry)$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Allow count for smaller results.\n if (/(entries|loaders|warnings|errors)\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n // Dependencies are huges, lets submit a bit less.\n if (/(modules\\.(dependencies|dependents)$)/.test(metric.metric)) {\n thresholds.count = 30;\n }\n // Dependency tree calculation can output a lot of metrics.\n if (/modules\\.tree\\.count$/.test(metric.metric)) {\n thresholds.count = 150;\n }\n if (/modules\\.tree\\.size$/.test(metric.metric)) {\n thresholds.size = 1500000;\n }\n // We want to track entry size whatever their size.\n if (/entries\\.size$/.test(metric.metric)) {\n thresholds.size = 0;\n }\n // We want to track entry module count whatever their number\n if (/entries\\.modules\\.count$/.test(metric.metric)) {\n thresholds.count = 0;\n }\n const avg = metric.points.length\n ? metric.points.reduce((accumulator, currentPoint) => accumulator + currentPoint[1], 0) /\n metric.points.length\n : 0;\n return avg > thresholds[metric.type] ? metric : null;\n};\n\nexport const defaultFilters: ((metric: Metric) => Metric | null)[] = [\n filterTreeMetrics,\n filterSourcemapsAndNodeModules,\n filterMetricsOnThreshold,\n];\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'metrics' as const;\nexport const PLUGIN_NAME: PluginName = `datadog-metrics-plugin` as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { normalizeTagValue } from '@dd/core/helpers/strings';\nimport type {\n GlobalContext,\n OptionsWithDefaults,\n Metric,\n ValueContext,\n MetricToSend,\n} from '@dd/core/types';\nimport { CONFIG_KEY } from '@dd/metrics-plugin/constants';\nimport type {\n Module,\n Compilation,\n MetricsOptionsWithDefaults,\n Filter,\n} from '@dd/metrics-plugin/types';\n\nimport { defaultFilters } from './filters';\n\nexport const getTimestamp = (timestamp?: number): number => {\n return Math.floor((timestamp || Date.now()) / 1000);\n};\n\nexport const validateOptions = (\n opts: OptionsWithDefaults,\n bundlerName: string,\n): MetricsOptionsWithDefaults => {\n const options = opts[CONFIG_KEY];\n\n const timestamp = getTimestamp(options?.timestamp);\n\n let prefix = options?.enableDefaultPrefix === false ? '' : `build.${bundlerName}`;\n if (options?.prefix) {\n prefix += prefix ? `.${options.prefix}` : options.prefix;\n }\n\n return {\n enableDefaultPrefix: true,\n enableTracing: false,\n filters: defaultFilters,\n tags: [],\n ...opts[CONFIG_KEY],\n timestamp,\n // Make it lowercase and remove any leading/closing dots.\n prefix: prefix.toLowerCase().replace(/(^\\.*|\\.*$)/g, ''),\n };\n};\n\nexport const getDefaultTags = (context: GlobalContext, configuredTags: string[]): string[] => {\n const defaultTags = [\n `bundler:${normalizeTagValue(context.bundler.name)}`,\n `plugin_version:${normalizeTagValue(context.version)}`,\n `site:${normalizeTagValue(context.auth.site)}`,\n ];\n\n if (context.build.metadata.name) {\n defaultTags.push(`build_name:${normalizeTagValue(context.build.metadata.name)}`);\n }\n\n if (context.build.metadata.version) {\n defaultTags.push(`build_version:${normalizeTagValue(context.build.metadata.version)}`);\n }\n\n return [...defaultTags, ...configuredTags];\n};\n\nconst getMetric = (metric: MetricToSend, defaultTags: string[], prefix: string): MetricToSend => {\n return {\n ...metric,\n tags: [...metric.tags, ...defaultTags],\n metric: prefix ? `${prefix}.${metric.metric}` : metric.metric,\n };\n};\n\nexport const getMetricsToSend = (\n metrics: Set<Metric>,\n timestamp: number,\n filters: Filter[],\n defaultTags: string[],\n prefix: string,\n): Set<MetricToSend> => {\n const metricsToSend: Set<MetricToSend> = new Set();\n\n // Apply filters\n for (const metric of metrics) {\n let processedMetrics: MetricToSend = { ...metric, toSend: true };\n if (filters?.length) {\n for (const filter of filters) {\n const result = filter({\n metric: processedMetrics.metric,\n type: processedMetrics.type,\n points: processedMetrics.points,\n tags: processedMetrics.tags,\n });\n\n if (result) {\n // Keep the toSend value from the original metric.\n processedMetrics = { ...result, toSend: processedMetrics.toSend };\n } else {\n // Do not modify the metric but mark it as not to send.\n processedMetrics.toSend = false;\n }\n }\n }\n\n // We wrap the metric after the filters\n // to ensure we apply the right prefix and default tags\n // without being impacted by the filters.\n metricsToSend.add(getMetric(processedMetrics, defaultTags, prefix));\n }\n\n // Count only the metrics that pass the filters\n const count = Array.from(metricsToSend).filter((m) => m.toSend).length;\n metricsToSend.add(\n getMetric(\n {\n metric: 'metrics.count',\n type: 'count',\n points: [[timestamp, count + 1]],\n tags: [],\n toSend: true,\n },\n defaultTags,\n prefix,\n ),\n );\n\n return metricsToSend;\n};\n\nexport const getPluginName = (opts: string | { name: string }) =>\n typeof opts === 'string' ? opts : opts.name;\n\n// We want to ensure cwd ends with a slash.\nconst formatCwd = (cwd: string = ''): string => {\n return cwd.endsWith('/') ? cwd : `${cwd}/`;\n};\n\n// Format a module name by trimming the user's specific part out.\nexport const getDisplayName = (name: string, cwd?: string) => {\n let toReturn: string = name;\n const nameSplit: string[] = name.split(formatCwd(cwd));\n if (cwd && nameSplit.length) {\n toReturn = nameSplit.pop()!;\n }\n\n return (\n toReturn\n // Remove loaders query\n .split('!')\n .pop()!\n // Remove everything in front of /node_modules\n .replace(/(.*)?\\/node_modules\\//, '/node_modules/')\n // Remove any prefixing ../\n .replace(/^((\\.)*\\/)+/, '')\n );\n};\n\nexport const formatModuleName = (name: string, context?: string) =>\n name\n // Remove loaders query\n .split('!')\n .pop()!\n // Webpack store its modules with a relative path\n // let's do the same so we can integrate better with it.\n .replace(formatCwd(context), './');\n\nexport const getModulePath = (module: Module, compilation: Compilation) => {\n let path: string | undefined = module.userRequest;\n if (!path) {\n let issuer;\n if (compilation.moduleGraph && typeof compilation.moduleGraph.getIssuer === 'function') {\n issuer = compilation.moduleGraph.getIssuer(module);\n } else {\n issuer = module.issuer;\n }\n\n path = issuer?.userRequest;\n\n if (!path) {\n // eslint-disable-next-line no-underscore-dangle\n path = module._identifier?.split('!').pop();\n }\n }\n return path || 'unknown';\n};\n\n// Find the module name and format it the same way as webpack.\nexport const getModuleName = (module: Module, compilation: Compilation, context?: string) => {\n let name: string = module.name || module.userRequest;\n if (!name) {\n name = getModulePath(module, compilation);\n }\n return formatModuleName(name || 'no-name', context);\n};\n\n// Format the loader's name by extracting it from the query.\n// \"[...]/node_modules/babel-loader/lib/index.js\" => babel-loader\nconst formatLoaderName = (loader: string) =>\n loader.replace(/^.*\\/node_modules\\/(@[a-z0-9][\\w-.]+\\/[a-z0-9][\\w-.]*|[^/]+).*$/, '$1');\n\n// Find a module's loaders names and format them.\nexport const getLoaderNames = (module: Module) =>\n (module.loaders || []).map((l: any) => l.loader || l).map(formatLoaderName);\n\nexport const getValueContext = (args: any[]): ValueContext[] => {\n return args.map((arg) => ({\n type: arg?.constructor?.name ?? typeof arg,\n name: arg?.name,\n value: typeof arg === 'string' ? arg : undefined,\n }));\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport { formatDuration, truncateString } from '@dd/core/helpers/strings';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Output,\n TimingsMap,\n TimingsReport,\n} from '@dd/core/types';\nimport chalk from 'chalk';\nimport prettyBytes from 'pretty-bytes';\n\n// How many items do we show in the top lists.\nconst TOP = 5;\n// How long a path can be before we truncate it.\nconst MAX_VALUE_LENGTH = 60;\n\nconst numColor = chalk.bold.red;\nconst nameColor = chalk.bold.cyan;\n\ntype ValuesToPrint = { name: string; top: boolean; values: { name: string; value: string }[] };\n\ntype FileReport = {\n name: string;\n aggregatedSize?: number;\n size: number;\n dependencies: Set<string>;\n dependents: Set<string>;\n};\n\n// Sort a collection by attribute\nconst sortDesc = (attr: ((arg: any) => any) | string) => (a: any, b: any) => {\n let aVal;\n let bVal;\n\n if (typeof attr === 'function') {\n aVal = attr(a);\n bVal = attr(b);\n } else {\n aVal = a[attr];\n bVal = b[attr];\n }\n\n if (aVal > bVal) {\n return -1;\n } else if (aVal < bVal) {\n return 1;\n } else {\n return 0;\n }\n};\n\nexport const getGeneralValues = (context: GlobalContext): ValuesToPrint[] => {\n const valuesToPrint: ValuesToPrint = {\n name: 'General Numbers',\n values: [],\n top: false,\n };\n\n const nbModules = context.build.inputs ? context.build.inputs.length : 0;\n const nbAssets = context.build.outputs ? context.build.outputs.length : 0;\n const nbWarnings = context.build.warnings.length;\n const nbErrors = context.build.errors.length;\n const nbEntries = context.build.entries ? context.build.entries.length : 0;\n\n if (context.build.start) {\n valuesToPrint.values.push({\n name: 'Overhead duration',\n value: formatDuration(context.build.start - context.start),\n });\n }\n\n if (context.build.duration) {\n valuesToPrint.values.push({\n name: 'Build duration',\n value: formatDuration(context.build.duration),\n });\n }\n\n if (context.build.writeDuration) {\n valuesToPrint.values.push({\n name: 'Write duration',\n value: formatDuration(context.build.writeDuration),\n });\n }\n\n valuesToPrint.values.push(\n {\n name: 'Number of modules',\n value: nbModules.toString(),\n },\n {\n name: 'Number of assets',\n value: nbAssets.toString(),\n },\n {\n name: 'Number of entries',\n value: nbEntries.toString(),\n },\n {\n name: 'Number of warnings',\n value: nbWarnings.toString(),\n },\n {\n name: 'Number of errors',\n value: nbErrors.toString(),\n },\n );\n\n return [valuesToPrint];\n};\n\nconst getAssetsValues = (context: GlobalContext): ValuesToPrint[] => {\n const assetSizesToPrint: ValuesToPrint = {\n name: 'Asset size',\n values: (context.build.outputs || [])\n // We don't want to report on sourcemaps here.\n .filter((output) => output.type !== 'map')\n .sort(sortDesc((output: Output) => output.size))\n .map((output) => ({\n name: output.name,\n value: prettyBytes(output.size),\n })),\n top: true,\n };\n\n const entrySizesToPrint: ValuesToPrint = {\n name: 'Entry aggregated size',\n values: (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: prettyBytes(entry.size),\n })),\n top: true,\n };\n\n const entryModulesToPrint: ValuesToPrint = {\n name: 'Entry number of modules',\n values:\n (context.build.entries || [])\n .sort(sortDesc((entry: Entry) => entry.size))\n .map((entry) => ({\n name: entry.name,\n value: entry.inputs.length.toString(),\n })) || [],\n top: true,\n };\n\n return [assetSizesToPrint, entrySizesToPrint, entryModulesToPrint];\n};\n\nconst getModulesValues = (context: GlobalContext): ValuesToPrint[] => {\n const dependentsToPrint: ValuesToPrint = {\n name: `Module total dependents`,\n values: [],\n top: true,\n };\n\n const dependenciesToPrint: ValuesToPrint = {\n name: `Module total dependencies`,\n values: [],\n top: true,\n };\n\n const sizesToPrint: ValuesToPrint = {\n name: `Module size`,\n values: [],\n top: true,\n };\n\n const aggregatedSizesToPrint: ValuesToPrint = {\n name: `Module aggregated size`,\n values: [],\n top: true,\n };\n\n const dependencies: Set<FileReport> = new Set();\n\n // Build our collections.\n const serializedReport = serializeBuildReport(context.build);\n const inputs: Map<string, FileReport> = new Map();\n const fileDependencies: Map<string, Set<string>> = new Map();\n const fileDependents: Map<string, Set<string>> = new Map();\n\n for (const input of serializedReport.inputs || []) {\n // We don't want to report on sourcemaps here.\n if (input.type === 'map') {\n continue;\n }\n\n const dependenciesSet = new Set(input.dependencies);\n const dependentsSet = new Set(input.dependents);\n\n // Create the sets for all the dependencies.\n for (const dep of dependenciesSet) {\n if (!fileDependents.has(dep)) {\n fileDependents.set(dep, new Set());\n }\n fileDependents.get(dep)!.add(input.filepath);\n }\n\n // Create the sets for all the dependents.\n for (const dep of dependentsSet) {\n if (!fileDependencies.has(dep)) {\n fileDependencies.set(dep, new Set());\n }\n fileDependencies.get(dep)!.add(input.filepath);\n }\n\n if (fileDependencies.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependencies = fileDependencies.get(input.filepath)!;\n for (const dep of existingDependencies) {\n dependenciesSet.add(dep);\n }\n }\n\n if (fileDependents.has(input.filepath)) {\n // If we already have a set for this file, we complete it.\n const existingDependents = fileDependents.get(input.filepath)!;\n for (const dep of existingDependents) {\n dependentsSet.add(dep);\n }\n }\n\n fileDependencies.set(input.filepath, dependenciesSet);\n fileDependents.set(input.filepath, dependentsSet);\n\n inputs.set(input.filepath, {\n name: input.name,\n size: input.size,\n dependencies: dependenciesSet,\n dependents: dependentsSet,\n });\n }\n\n for (const [filepath, input] of inputs) {\n const inputDependencies = fileDependencies.get(filepath) || new Set();\n const inputDependents = fileDependents.get(filepath) || new Set();\n\n // Aggregate size.\n let aggregatedSize = input.size;\n for (const dep of inputDependencies) {\n aggregatedSize += inputs.get(dep)?.size || 0;\n }\n\n dependencies.add({\n name: input.name,\n size: input.size,\n aggregatedSize,\n dependents: inputDependents,\n dependencies: inputDependencies,\n });\n }\n\n if (!dependencies.size) {\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint];\n }\n\n const dependenciesArray = Array.from(dependencies);\n // Sort by dependents, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependents.size));\n dependentsToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependents.size.toString(),\n }));\n // Sort by dependencies, biggest first\n dependenciesArray.sort(sortDesc((file: FileReport) => file.dependencies.size));\n dependenciesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: file.dependencies.size.toString(),\n }));\n // Sort by size, biggest first\n dependenciesArray.sort(sortDesc('size'));\n sizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.size),\n }));\n // Sort by aggregated size, biggest first\n dependenciesArray.sort(sortDesc('aggregatedSize'));\n aggregatedSizesToPrint.values = dependenciesArray.map((file) => ({\n name: file.name,\n value: prettyBytes(file.aggregatedSize || file.size),\n }));\n\n return [dependentsToPrint, dependenciesToPrint, sizesToPrint, aggregatedSizesToPrint];\n};\n\nconst getTimingValues = (name: string, timings?: TimingsMap): ValuesToPrint[] => {\n if (!timings || !timings.size) {\n return [];\n }\n\n const times = Array.from(timings.values());\n // Sort by duration, longest first\n times.sort(sortDesc('duration'));\n const durationsToPrint: ValuesToPrint = {\n name: `${name} duration`,\n values: times.map((module) => ({\n name: module.name,\n value: formatDuration(module.duration),\n })),\n top: true,\n };\n\n // Sort by increment, biggest first\n times.sort(sortDesc('increment'));\n const hitsToPrint: ValuesToPrint = {\n name: `${name} hits`,\n values: times.map((module) => ({\n name: module.name,\n value: module.increment.toString(),\n })),\n top: true,\n };\n\n return [durationsToPrint, hitsToPrint];\n};\n\nconst renderValues = (values: ValuesToPrint[]): string => {\n let outputString = '';\n\n const titlePadding = 4;\n const valuePadding = 4;\n\n // Cleaning and preparing out the groups.\n for (const group of values) {\n // Only keep the top values if requested.\n if (group.top && group.values.length >= TOP) {\n group.values = group.values.slice(0, TOP);\n group.name = `Top ${TOP} ${group.name}`;\n }\n\n // Truncate values' names when they are way too long.\n for (const value of group.values) {\n value.name = truncateString(value.name, MAX_VALUE_LENGTH);\n }\n }\n\n // Calculating the width of the columns.\n const maxTitleWidth = Math.max(...values.map((val) => val.name.length));\n const maxNameWidth = Math.max(...values.flatMap((val) => val.values.map((v) => v.name.length)));\n const maxValueWidth = Math.max(\n ...values.flatMap((val) => val.values.map((v) => v.value.length)),\n );\n const totalWidth = Math.max(\n maxTitleWidth + titlePadding,\n maxNameWidth + maxValueWidth + valuePadding,\n );\n\n // Composing the output.\n for (const group of values) {\n if (group.values.length === 0) {\n continue;\n }\n\n const titlePad = totalWidth - (group.name.length + titlePadding);\n\n outputString += `\\n== ${group.name} ${'='.repeat(titlePad)}=\\n`;\n\n for (const value of group.values) {\n const valuePad = maxValueWidth - value.value.length;\n outputString += ` [${numColor(value.value)}] ${' '.repeat(valuePad)}${nameColor(value.name)}\\n`;\n }\n }\n\n return outputString;\n};\n\nexport const outputTexts = (globalContext: GlobalContext, log: Logger, timings?: TimingsReport) => {\n const valuesToPrint: ValuesToPrint[] = [];\n\n if (timings) {\n // Output legacy/tracing.\n valuesToPrint.push(...getTimingValues('Loader', timings.loaders));\n valuesToPrint.push(...getTimingValues('Tapable', timings.tapables));\n valuesToPrint.push(...getTimingValues('Module', timings.modules));\n }\n\n valuesToPrint.push(...getModulesValues(globalContext));\n valuesToPrint.push(...getAssetsValues(globalContext));\n valuesToPrint.push(...getGeneralValues(globalContext));\n\n const outputString = renderValues(valuesToPrint);\n\n log.info(outputString);\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { Logger, Metric, MetricToSend } from '@dd/core/types';\nimport chalk from 'chalk';\n\nexport const METRICS_API_PATH = 'api/v1/series';\n\nconst green = chalk.bold.green;\n\nexport const sendMetrics = (\n metrics: Set<MetricToSend>,\n auth: { apiKey?: string; site: string },\n log: Logger,\n) => {\n if (!auth.apiKey) {\n log.info(`Won't send metrics to Datadog: missing API Key.`);\n return;\n }\n if (!metrics.size) {\n log.debug(`No metrics to send.`);\n return;\n }\n\n // Only send metrics that are to be sent.\n const metricsToSend: Metric[] = Array.from(metrics)\n .filter((metric) => metric.toSend)\n .map((metric) => {\n return {\n ...metric,\n toSend: undefined,\n };\n });\n\n const metricIterations: Map<string, number> = new Map();\n for (const metric of metricsToSend) {\n if (!metricIterations.has(metric.metric)) {\n metricIterations.set(metric.metric, 0);\n }\n metricIterations.set(metric.metric, metricIterations.get(metric.metric)! + 1);\n }\n\n const metricsNames = Array.from(metricIterations.entries())\n // Sort by metric name.\n .sort(([nameA], [nameB]) => nameA.localeCompare(nameB))\n .map(([name, count]) => `${name} - ${count}`);\n\n log.debug(`\nSending ${metricsToSend.length} metrics with configuration:\n - intake: ${green(`https://api.${auth.site}/${METRICS_API_PATH}`)}\n\nMetrics:\n - ${metricsNames.join('\\n - ')}`);\n\n return doRequest({\n method: 'POST',\n url: `https://api.${auth.site}/${METRICS_API_PATH}?api_key=${auth.apiKey}`,\n getData: () => ({\n data: JSON.stringify({ series: metricsToSend } satisfies {\n series: Metric[];\n }),\n }),\n }).catch((e) => {\n log.error(`Error sending metrics ${e}`);\n });\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing, Value } from '@dd/core/types';\nimport { formatModuleName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport type { PluginBuild } from 'esbuild';\nimport { performance } from 'perf_hooks';\n\nconst FN_TO_WRAP = ['onStart', 'onLoad', 'onResolve', 'onEnd'] as const;\n\nconst loadersMap: Map<string, Timing> = new Map();\nconst pluginsMap: TimingsMap = new Map();\nconst modulesMap: TimingsMap = new Map();\n\nexport const wrapPlugins = (build: PluginBuild, context: string) => {\n const plugins = build.initialOptions.plugins;\n if (plugins) {\n // We clone plugins so we don't pass modified options to other plugins.\n const initialPlugins = plugins.map((plugin) => {\n return {\n ...plugin,\n };\n });\n for (const plugin of plugins) {\n const oldSetup = plugin.setup;\n plugin.setup = async (esbuild) => {\n const newBuildObject = getNewBuildObject(esbuild, plugin.name, context);\n await oldSetup({\n ...newBuildObject,\n // Use non-modified plugins for other plugins\n initialOptions: { ...newBuildObject.initialOptions, plugins: initialPlugins },\n });\n };\n }\n }\n};\n\nconst getNewBuildObject = (\n build: PluginBuild,\n pluginName: string,\n context: string,\n): PluginBuild => {\n const newBuildObject: any = Object.assign({}, build);\n for (const fn of FN_TO_WRAP) {\n newBuildObject[fn] = async (opts: any, cb: any) => {\n const pluginTiming: Timing = pluginsMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n pluginTiming.events[fn] = pluginTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const isLoader = fn === 'onLoad';\n const initialFunction: any = build[fn];\n return initialFunction(opts, async (...args: any[]) => {\n const modulePath = formatModuleName(args[0].path, context);\n const moduleTiming: Timing = modulesMap.get(modulePath) || {\n name: modulePath,\n increment: 0,\n duration: 0,\n events: {},\n };\n moduleTiming.events[fn] = moduleTiming.events[fn] || {\n name: fn,\n values: [],\n };\n const start = performance.now();\n\n try {\n return await cb(...args);\n } finally {\n const end = performance.now();\n const duration = end - start;\n const statsObject: Value = {\n start,\n end,\n duration,\n context: getValueContext(args),\n };\n\n pluginTiming.events[fn].values.push(statsObject);\n pluginTiming.duration += duration;\n pluginTiming.increment += 1;\n pluginsMap.set(pluginName, pluginTiming);\n\n moduleTiming.events[fn].values.push(statsObject);\n moduleTiming.duration += duration;\n moduleTiming.increment += 1;\n modulesMap.set(modulePath, moduleTiming);\n\n // Only if we're in a loader function.\n if (isLoader) {\n const loaderTiming: Timing = loadersMap.get(pluginName) || {\n name: pluginName,\n increment: 0,\n duration: 0,\n events: {},\n };\n loaderTiming.events[fn] = loaderTiming.events[fn] || {\n name: fn,\n values: [],\n };\n loaderTiming.events[fn].values.push(statsObject);\n loaderTiming.duration += duration;\n loaderTiming.increment += 1;\n loadersMap.set(pluginName, loaderTiming);\n }\n }\n });\n };\n }\n return newBuildObject;\n};\n\nexport const getResults = () => ({ plugins: pluginsMap, modules: modulesMap, loaders: loadersMap });\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { BuildResult } from 'esbuild';\n\nimport { wrapPlugins, getResults as getPluginsResults } from './plugins';\n\nexport const getEsbuildPlugin = (\n globalContext: GlobalContext,\n logger: Logger,\n): PluginOptions['esbuild'] => {\n return {\n setup: (build) => {\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n const timeWrap = logger.time('wrapping plugins');\n wrapPlugins(build, globalContext.buildRoot);\n timeWrap.end();\n build.onEnd(async (result: BuildResult) => {\n if (!result.metafile) {\n logger.warn(\"Missing metafile, can't proceed with modules data.\");\n return;\n }\n\n const timeResult = logger.time('getting plugins results');\n const { plugins, loaders, modules } = getPluginsResults();\n timeResult.end();\n\n await globalContext.asyncHook('timings', {\n tapables: plugins,\n loaders,\n modules,\n });\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, Timing } from '@dd/core/types';\nimport { getDisplayName, getModuleName, getLoaderNames } from '@dd/metrics-plugin/common/helpers';\nimport type { Module, Event, Compilation } from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Loaders {\n constructor(cwd: string) {\n this.cwd = cwd;\n }\n cwd: string;\n started: { [key: string]: Event } = {};\n finished: Event[] = [];\n\n startModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n const loaders = getLoaderNames(module);\n\n if (!loaders.length) {\n // Keep a track of modules without a loader.\n loaders.push('no-loader');\n }\n\n // Store the event until the module is complete.\n this.started[moduleName] = {\n module: getDisplayName(moduleName),\n timings: {\n start: performance.now(),\n duration: 0,\n end: 0,\n },\n loaders,\n };\n }\n\n doneModule(module: Module, compilation: Compilation): void {\n const moduleName = getModuleName(module, compilation, this.cwd);\n // Get the event for this module.\n const event = this.started[moduleName];\n\n if (!event) {\n return;\n }\n\n event.timings.end = performance.now();\n event.timings.duration = event.timings.end - event.timings.start;\n\n // Store the event.\n this.finished.push(event);\n\n // Delete the entry so another import\n // of the same module can be also reported.\n delete this.started[moduleName];\n }\n\n getResults(): {\n modules: TimingsMap;\n loaders: TimingsMap;\n } {\n const loaders: Map<string, Timing> = new Map();\n const modules: Map<string, Timing> = new Map();\n for (const event of this.finished) {\n const duration = event.timings.end! - event.timings.start;\n\n // Aggregate module timings\n const moduleTiming = modules.get(event.module) || {\n name: event.module,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n const eventName = event.loaders.join(',');\n moduleTiming.events[eventName] = moduleTiming.events[eventName] || {\n name: eventName,\n values: [],\n };\n\n moduleTiming.events[eventName].values.push(event.timings);\n moduleTiming.increment += 1;\n moduleTiming.duration += duration;\n modules.set(event.module, moduleTiming);\n\n // Aggregate loader timings\n for (const loader of event.loaders) {\n const loaderTiming = loaders.get(loader) || {\n name: loader,\n increment: 0,\n duration: 0,\n events: {},\n };\n\n loaderTiming.increment += 1;\n loaderTiming.duration += duration;\n loaders.set(loader, loaderTiming);\n }\n }\n\n return { loaders, modules };\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { TimingsMap, ValueContext, TAP_TYPES, Timing } from '@dd/core/types';\nimport { getPluginName, getValueContext } from '@dd/metrics-plugin/common/helpers';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type {\n MonitoredTaps,\n Tapable,\n Hooks,\n TapablesResult,\n TapPromise,\n TapAsync,\n Tap,\n Hook,\n} from '@dd/metrics-plugin/types';\nimport { performance } from 'perf_hooks';\n\nexport class Tapables {\n constructor(cwd: Tapables['cwd']) {\n this.cwd = cwd;\n }\n cwd: string;\n monitoredTaps: MonitoredTaps = {};\n tapables: Tapable[] = [];\n hooks: Hooks = {};\n timings: TimingsMap = new Map();\n ignoredHooks = [\n // This one triggers a DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK warning.\n 'normalModuleLoader',\n ];\n\n saveResult(\n type: TAP_TYPES,\n pluginName: string,\n hookName: string,\n context: ValueContext[],\n start: number,\n end: number,\n ) {\n const timing: Timing = this.timings.get(pluginName) || {\n name: pluginName,\n duration: 0,\n increment: 0,\n events: {},\n };\n if (!timing.events[hookName]) {\n timing.events[hookName] = {\n name: hookName,\n values: [],\n };\n }\n\n timing.events[hookName].values.push({\n start,\n end,\n duration: end - start,\n context,\n type,\n });\n timing.duration += end - start;\n timing.increment += 1;\n this.timings.set(pluginName, timing);\n }\n\n getResults(): TapablesResult {\n const timings = this.timings;\n\n // Aggregate the durations for each plugin.\n for (const [tapableName, tapable] of this.timings) {\n const timing = tapable;\n timing.duration = Object.values(tapable.events)\n .map((hookArray) =>\n hookArray.values.reduce((previous, current) => {\n return previous + current.end - current.start;\n }, 0),\n )\n .reduce((previous, current) => previous + current, 0);\n timings.set(tapableName, timing);\n }\n\n return {\n monitoredTaps: this.monitoredTaps,\n tapables: this.tapables,\n hooks: this.hooks,\n timings,\n };\n }\n\n getPromiseTapPatch(type: TAP_TYPES, fn: TapPromise, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n const cb = () => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n };\n // Save the result whether it succeeds or not.\n returnValue.then(cb, cb);\n return returnValue;\n };\n }\n\n getAsyncTapPatch(type: TAP_TYPES, fn: TapAsync, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n // Callback is the last argument.\n const originalCB = args.pop();\n const newCB = (...a: [any]) => {\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return originalCB(...a);\n };\n return fn.apply(this, [...args, newCB]);\n };\n }\n\n getDefaultTapPatch(type: TAP_TYPES, fn: Tap, pluginName: string, hookName: string) {\n return (...args: [any]) => {\n // Find new hooks\n this.checkNewHooks();\n const startTime = performance.now();\n const returnValue = fn.apply(this, args);\n this.saveResult(\n type,\n pluginName,\n hookName,\n getValueContext(args),\n startTime,\n performance.now(),\n );\n return returnValue;\n };\n }\n\n // Patch the tap so we can report its execution duration.\n getTapPatch(type: TAP_TYPES, fn: (args: any) => any, pluginName: string, hookName: string) {\n switch (type) {\n case 'promise':\n return this.getPromiseTapPatch(type, fn, pluginName, hookName);\n case 'async':\n return this.getAsyncTapPatch(type, fn, pluginName, hookName);\n case 'default':\n default:\n return this.getDefaultTapPatch(type, fn, pluginName, hookName);\n }\n }\n\n newTap(\n type: TAP_TYPES,\n hookName: string,\n originalTap: Tap | TapAsync | TapPromise,\n scope: any,\n ) {\n return (options: any, fn: (args: any) => any) => {\n const pluginName = getPluginName(options);\n const key = `${hookName}-${pluginName}`;\n if (this.monitoredTaps[key]) {\n // Since it's monitored, fn is already patched.\n return originalTap.call(scope, options, fn);\n }\n this.monitoredTaps[key] = true;\n const newFn = this.getTapPatch(type, fn, pluginName, hookName);\n return originalTap.call(scope, options, newFn);\n };\n }\n\n replaceTaps(hookName: string, hook: Hook) {\n // Cover three types of tap.\n hook.tap = this.newTap('default', hookName, hook.tap!, hook);\n hook.tapAsync = this.newTap('async', hookName, hook.tapAsync!, hook);\n hook.tapPromise = this.newTap('promise', hookName, hook.tapPromise!, hook);\n }\n\n patchHook(tapableName: string, hookName: string, hook: Hook) {\n // Webpack specific, these _fakeHook are not writable.\n // eslint-disable-next-line no-underscore-dangle\n if (hook._fakeHook) {\n return;\n }\n\n // Skip the current plugin.\n if (tapableName.includes(PLUGIN_NAME)) {\n return;\n }\n\n if (!this.hooks[tapableName]) {\n this.hooks[tapableName] = [];\n }\n\n if (this.hooks[tapableName].includes(hookName)) {\n return;\n }\n\n this.hooks[tapableName].push(hookName);\n this.replaceTaps(hookName, hook);\n }\n\n patchHooks(tapable: Tapable) {\n const name = tapable.constructor.name;\n const hooksToPatch = Object.keys(tapable.hooks).filter((hookName) => {\n // Skip the ignored hooks.\n if (this.ignoredHooks.includes(hookName)) {\n return false;\n }\n\n // Skip the already patched hooks.\n if (this.hooks[name]?.includes(hookName)) {\n return false;\n }\n\n return true;\n });\n\n for (const hookName of hooksToPatch) {\n this.patchHook(name, hookName, tapable.hooks[hookName]);\n }\n }\n\n checkNewHooks() {\n // We reparse hooks in case new ones arrived.\n for (const tapable of this.tapables) {\n this.patchHooks(tapable);\n }\n }\n\n // Let's navigate through all the hooks we can find.\n throughHooks(tapable: Tapable) {\n if (!this.tapables.includes(tapable)) {\n this.tapables.push(tapable);\n }\n\n this.patchHooks(tapable);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport { PLUGIN_NAME } from '@dd/metrics-plugin/constants';\nimport type { Compilation } from '@dd/metrics-plugin/types';\n\nimport { Loaders } from './loaders';\nimport { Tapables } from './tapables';\n\nexport const getWebpackPlugin = (\n globalContext: GlobalContext,\n): PluginOptions['webpack'] & PluginOptions['rspack'] => {\n return async (compiler) => {\n const log = globalContext.getLogger(PLUGIN_NAME);\n\n const HOOK_OPTIONS = { name: PLUGIN_NAME };\n\n const tapables = new Tapables(globalContext.buildRoot);\n const loaders = new Loaders(globalContext.buildRoot);\n\n const compilerTime = log.time('parse compiler hooks');\n // @ts-expect-error - webpack and rspack reconciliation.\n tapables.throughHooks(compiler);\n compilerTime.end();\n\n // @ts-expect-error - webpack and rspack reconciliation.\n compiler.hooks.thisCompilation.tap(HOOK_OPTIONS, (compilation: Compilation) => {\n const compilationTime = log.time('parse compilation hooks');\n tapables.throughHooks(compilation);\n compilationTime.end();\n\n // TODO: Use log.time() to measure modules.\n compilation.hooks.buildModule.tap(HOOK_OPTIONS, (module) => {\n loaders.startModule(module, compilation);\n });\n\n compilation.hooks.succeedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n\n // NOTE: compilation.hooks.failedModule is not available in rspack as of 1.2.8\n // https://rspack.dev/api/plugin-api/compilation-hooks\n if (compilation.hooks.failedModule) {\n compilation.hooks.failedModule.tap(HOOK_OPTIONS, (module) => {\n loaders.doneModule(module, compilation);\n });\n }\n });\n\n // We're losing some tracing from plugins by using `afterEmit` instead of `done` but\n // it allows us to centralize the common process better.\n // TODO: Use custom hooks to make this more reliable and not blocked by a race condition.\n compiler.hooks.afterEmit.tapPromise(HOOK_OPTIONS, async () => {\n const { timings: tapableTimings } = tapables.getResults();\n const { loaders: loadersTimings, modules: modulesTimings } = loaders.getResults();\n\n await globalContext.asyncHook('timings', {\n tapables: tapableTimings,\n loaders: loadersTimings,\n modules: modulesTimings,\n });\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, GetPlugins, Metric, PluginOptions, TimingsReport } from '@dd/core/types';\n\nimport { initializeMetricsCollector } from './collector';\nimport { getUniversalMetrics, getPluginMetrics, getLoaderMetrics } from './common/aggregator';\nimport { defaultFilters } from './common/filters';\nimport { getDefaultTags, getMetricsToSend, getTimestamp, validateOptions } from './common/helpers';\nimport { outputTexts } from './common/output/text';\nimport { sendMetrics } from './common/sender';\nimport { PLUGIN_NAME, CONFIG_KEY } from './constants';\nimport { getEsbuildPlugin } from './esbuild-plugin';\nimport type { Filter, MetricsOptions } from './types';\nimport { getWebpackPlugin } from './webpack-plugin';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n filters: defaultFilters,\n};\n\nexport type types = {\n Filter: Filter;\n Metric: Metric;\n MetricsOptions: MetricsOptions;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context, stores }) => {\n const log = context.getLogger(PLUGIN_NAME);\n let realBuildEnd: number = 0;\n initializeMetricsCollector(context, stores);\n\n const validatedOptions = validateOptions(options, context.bundler.name);\n const plugins: PluginOptions[] = [];\n\n // Webpack and Esbuild specific plugins.\n // LEGACY\n const legacyPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: getEsbuildPlugin(context, log),\n webpack: getWebpackPlugin(context),\n rspack: getWebpackPlugin(context),\n };\n\n const timeBuild = log.time('build', { start: false });\n // Identify if we need the legacy plugin.\n const needLegacyPlugin =\n validatedOptions.enableTracing &&\n ['esbuild', 'webpack', 'rspack'].includes(context.bundler.name);\n let timingsReport: TimingsReport | undefined;\n let buildReport: BuildReport;\n\n const getMetricsToSendFromCollectedMetrics = () => {\n const metrics = new Set(stores.metrics);\n stores.metrics.clear();\n const defaultTags = getDefaultTags(context, validatedOptions.tags);\n\n return getMetricsToSend(\n metrics,\n validatedOptions.timestamp,\n validatedOptions.filters,\n defaultTags,\n validatedOptions.prefix,\n );\n };\n\n const sendCollectedMetrics = async () => {\n if (!stores.metrics.size) {\n return;\n }\n\n const timeMetrics = log.time(`aggregating collected metrics`);\n const metricsToSend = getMetricsToSendFromCollectedMetrics();\n\n await context.asyncHook('metrics', metricsToSend);\n timeMetrics.end();\n\n const timeSend = log.time('sending collected metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n const computeMetrics = async () => {\n context.build.end = Date.now();\n context.build.duration = context.build.end - context.build.start!;\n context.build.writeDuration = context.build.end - realBuildEnd;\n\n const timeMetrics = log.time(`aggregating metrics`);\n const timestamp = validatedOptions.timestamp;\n\n const timeUniversal = log.time(`aggregate universal metrics`);\n const universalMetrics = getUniversalMetrics(buildReport, timestamp);\n timeUniversal.end();\n const timePlugin = log.time(`aggregate plugins metrics`);\n const pluginMetrics = getPluginMetrics(timingsReport?.tapables, timestamp);\n timePlugin.end();\n const timeLoader = log.time(`aggregate loaders metrics`);\n const loaderMetrics = getLoaderMetrics(timingsReport?.loaders, timestamp);\n timeLoader.end();\n\n const allMetrics = new Set([...universalMetrics, ...pluginMetrics, ...loaderMetrics]);\n const defaultTags = getDefaultTags(context, validatedOptions.tags);\n\n const metricsToSend = getMetricsToSend(\n allMetrics,\n timestamp,\n validatedOptions.filters,\n defaultTags,\n validatedOptions.prefix,\n );\n\n await context.asyncHook('metrics', metricsToSend);\n\n timeMetrics.end();\n\n const timeReport = log.time('outputing report');\n outputTexts(context, log, timingsReport);\n timeReport.end();\n\n const timeSend = log.time('sending metrics to Datadog');\n await sendMetrics(\n metricsToSend,\n { apiKey: context.auth.apiKey, site: context.auth.site },\n log,\n );\n timeSend.end();\n };\n\n // Universal plugin.\n const universalPlugin: PluginOptions = {\n name: 'datadog-universal-metrics-plugin',\n enforce: 'post',\n buildStart() {\n timeBuild.resume();\n context.build.start = context.build.start || Date.now();\n // Set the timestamp to the build start if not provided.\n if (!options[CONFIG_KEY]?.timestamp) {\n validatedOptions.timestamp = getTimestamp(context.build.start);\n }\n },\n buildEnd() {\n timeBuild.end();\n realBuildEnd = Date.now();\n },\n\n async timings(timings) {\n timingsReport = timings;\n // Once we have both reports, we can compute the metrics.\n if (buildReport) {\n await computeMetrics();\n }\n },\n\n async buildReport(report) {\n buildReport = report;\n // Once we have both reports (or we don't need the legacy plugin),\n // we can compute the metrics.\n if (timingsReport || !needLegacyPlugin) {\n await computeMetrics();\n }\n },\n async flush() {\n await sendCollectedMetrics();\n },\n };\n\n if (validatedOptions.enableTracing) {\n plugins.push(legacyPlugin);\n }\n\n plugins.push(universalPlugin);\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BuildReport, Metric, TimingsMap } from '@dd/core/types';\n\nexport const getUniversalMetrics = (buildReport: BuildReport, timestamp: number): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n const inputs = buildReport.inputs || [];\n const outputs = buildReport.outputs || [];\n const entries = buildReport.entries || [];\n const nbWarnings = buildReport.warnings.length;\n const nbErrors = buildReport.errors.length;\n const duration = buildReport.duration;\n\n // Create some indexes to speed up the process.\n const entriesPerInput = new Map<string, string[]>();\n const assetsPerInput = new Map<string, string[]>();\n const entriesPerAsset = new Map<string, string[]>();\n\n for (const entry of entries) {\n for (const input of entry.inputs) {\n if (!entriesPerInput.has(input.filepath)) {\n entriesPerInput.set(input.filepath, []);\n }\n entriesPerInput.get(input.filepath)!.push(entry.name);\n }\n for (const output of entry.outputs) {\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (!entriesPerAsset.has(cleanAssetName)) {\n entriesPerAsset.set(cleanAssetName, []);\n }\n entriesPerAsset.get(cleanAssetName)!.push(entry.name);\n }\n }\n\n for (const output of outputs) {\n for (const input of output.inputs) {\n if (!assetsPerInput.has(input.filepath)) {\n assetsPerInput.set(input.filepath, []);\n }\n assetsPerInput.get(input.filepath)!.push(output.name);\n }\n }\n\n // Counts\n metrics\n .add({\n metric: 'assets.count',\n type: 'count',\n points: [[timestamp, outputs.length]],\n tags: [],\n })\n .add({\n metric: 'entries.count',\n type: 'count',\n points: [[timestamp, entries.length]],\n tags: [],\n })\n .add({\n metric: 'errors.count',\n type: 'count',\n points: [[timestamp, nbErrors]],\n tags: [],\n })\n .add({\n metric: 'modules.count',\n type: 'count',\n points: [[timestamp, inputs.length]],\n tags: [],\n })\n .add({\n metric: 'warnings.count',\n type: 'count',\n points: [[timestamp, nbWarnings]],\n tags: [],\n });\n\n if (duration) {\n metrics.add({\n metric: 'compilation.duration',\n type: 'duration',\n points: [[timestamp, duration]],\n tags: [],\n });\n }\n\n // Modules\n for (const input of inputs) {\n const tags = [`moduleName:${input.name}`, `moduleType:${input.type}`];\n if (entriesPerInput.has(input.filepath)) {\n tags.push(\n ...entriesPerInput\n .get(input.filepath)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n\n if (assetsPerInput.has(input.filepath)) {\n tags.push(\n ...assetsPerInput.get(input.filepath)!.map((assetName) => `assetName:${assetName}`),\n );\n }\n metrics\n .add({\n metric: 'modules.size',\n type: 'size',\n points: [[timestamp, input.size]],\n tags,\n })\n .add({\n metric: 'modules.dependencies',\n type: 'count',\n points: [[timestamp, input.dependencies.size]],\n tags,\n })\n .add({\n metric: 'modules.dependents',\n type: 'count',\n points: [[timestamp, input.dependents.size]],\n tags,\n });\n }\n\n // Assets\n for (const output of outputs) {\n const tags = [`assetName:${output.name}`, `assetType:${output.type}`];\n const cleanAssetName = output.filepath.replace(/\\.map$/, '');\n if (entriesPerAsset.has(cleanAssetName)) {\n tags.push(\n ...entriesPerAsset\n .get(cleanAssetName)!\n .map((entryName) => `entryName:${entryName}`),\n );\n }\n metrics\n .add({\n metric: 'assets.size',\n type: 'size',\n points: [[timestamp, output.size]],\n tags,\n })\n .add({\n metric: 'assets.modules.count',\n type: 'count',\n points: [[timestamp, output.inputs.length]],\n tags,\n });\n }\n\n // Entries\n for (const entry of entries) {\n const tags = [`entryName:${entry.name}`];\n metrics\n .add({\n metric: 'entries.size',\n type: 'size',\n points: [[timestamp, entry.size]],\n tags,\n })\n .add({\n metric: 'entries.modules.count',\n type: 'count',\n points: [[timestamp, entry.inputs.length]],\n tags,\n })\n .add({\n metric: 'entries.assets.count',\n type: 'count',\n points: [[timestamp, entry.outputs.length]],\n tags,\n });\n }\n\n return metrics;\n};\n\nexport const getPluginMetrics = (\n plugins: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!plugins) {\n return metrics;\n }\n\n metrics.add({\n metric: 'plugins.count',\n type: 'count',\n points: [[timestamp, plugins.size]],\n tags: [],\n });\n\n for (const plugin of plugins.values()) {\n let pluginDuration = 0;\n let pluginCount = 0;\n\n for (const hook of Object.values(plugin.events)) {\n let hookDuration = 0;\n pluginCount += hook.values.length;\n for (const v of hook.values) {\n const duration = v.end - v.start;\n hookDuration += duration;\n pluginDuration += duration;\n }\n metrics\n .add({\n metric: 'plugins.hooks.duration',\n type: 'duration',\n points: [[timestamp, hookDuration]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n })\n .add({\n metric: 'plugins.hooks.increment',\n type: 'count',\n points: [[timestamp, hook.values.length]],\n tags: [`pluginName:${plugin.name}`, `hookName:${hook.name}`],\n });\n }\n\n metrics\n .add({\n metric: 'plugins.duration',\n type: 'duration',\n points: [[timestamp, pluginDuration]],\n tags: [`pluginName:${plugin.name}`],\n })\n .add({\n metric: 'plugins.increment',\n type: 'count',\n points: [[timestamp, pluginCount]],\n tags: [`pluginName:${plugin.name}`],\n });\n }\n\n return metrics;\n};\n\nexport const getLoaderMetrics = (\n loaders: TimingsMap | undefined,\n timestamp: number,\n): Set<Metric> => {\n const metrics: Set<Metric> = new Set();\n\n if (!loaders) {\n return metrics;\n }\n\n metrics.add({\n metric: 'loaders.count',\n type: 'count',\n points: [[timestamp, loaders.size]],\n tags: [],\n });\n\n for (const loader of loaders.values()) {\n metrics\n .add({\n metric: 'loaders.duration',\n type: 'duration',\n points: [[timestamp, loader.duration]],\n tags: [`loaderName:${loader.name}`],\n })\n .add({\n metric: 'loaders.increment',\n type: 'count',\n points: [[timestamp, loader.increment]],\n tags: [`loaderName:${loader.name}`],\n });\n }\n\n return metrics;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const CONFIG_KEY = 'output' as const;\nexport const PLUGIN_NAME: PluginName = 'datadog-output-plugin' as const;\nexport const FILE_KEYS = [\n 'build',\n 'bundler',\n 'dependencies',\n 'errors',\n 'logs',\n 'metrics',\n 'timings',\n 'warnings',\n] as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Options } from '@dd/core/types';\n\nimport { CONFIG_KEY } from './constants';\nimport type { FileKey, OutputOptions, OutputOptionsWithDefaults } from './types';\n\n// Sanitize the output path.\nconst sanitizeOutputPath = (key: FileKey, value: boolean | string) => {\n if (typeof value === 'string') {\n // Ensure we end with the correct extension.\n return value.replace(/(\\.json)?$/, '.json');\n }\n\n // Transform the value into a path.\n return value === true ? `${key}.json` : value;\n};\n\nconst validateFilesOptions = (\n files: OutputOptions['files'],\n): OutputOptionsWithDefaults['files'] => {\n // If no files object is provided, we'll output all files.\n const defaultValue = typeof files === 'undefined';\n\n const validatedFiles: OutputOptionsWithDefaults['files'] = {\n // Listing everything to keep TS happy.\n build: sanitizeOutputPath('build', files?.build ?? defaultValue),\n bundler: sanitizeOutputPath('bundler', files?.bundler ?? defaultValue),\n dependencies: sanitizeOutputPath('dependencies', files?.dependencies ?? defaultValue),\n errors: sanitizeOutputPath('errors', files?.errors ?? defaultValue),\n logs: sanitizeOutputPath('logs', files?.logs ?? defaultValue),\n metrics: sanitizeOutputPath('metrics', files?.metrics ?? defaultValue),\n timings: sanitizeOutputPath('timings', files?.timings ?? defaultValue),\n warnings: sanitizeOutputPath('warnings', files?.warnings ?? defaultValue),\n };\n\n return validatedFiles;\n};\n\n// Deal with validation and defaults here.\nexport const validateOptions = (options: Options): OutputOptionsWithDefaults => {\n return {\n path: './',\n ...options[CONFIG_KEY],\n files: validateFilesOptions(options[CONFIG_KEY]?.files),\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 { serializeBuildReport } from '@dd/core/helpers/plugins';\nimport type { GetPlugins, Logger, PluginOptions } from '@dd/core/types';\nimport path from 'path';\nimport type { OutputBundle } from 'rollup';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { FileKey, FileValue, OutputOptions } from './types';\nimport { validateOptions } from './validate';\n\nexport { CONFIG_KEY, PLUGIN_NAME };\n\nexport const helpers = {\n // Add the helpers you'd like to expose here.\n};\n\nexport type types = {\n // Add the types you'd like to expose here.\n OutputOptions: OutputOptions;\n};\n\nconst getXpackPlugin =\n (\n log: Logger,\n write: (getStats: () => any) => void,\n ): PluginOptions['webpack'] & PluginOptions['rspack'] =>\n (compiler) => {\n type Stats = Parameters<Parameters<typeof compiler.hooks.done.tap>[1]>[0];\n compiler.hooks.done.tap('bundler-outputs', (stats: Stats) => {\n write(() => {\n const statsTimer = log.time('stats serialization');\n const statsJson = stats.toJson({\n all: false,\n assets: true,\n children: true,\n chunks: true,\n chunkGroupAuxiliary: true,\n chunkGroupChildren: true,\n chunkGroups: true,\n chunkRelations: true,\n entrypoints: true,\n errors: true,\n ids: true,\n modules: true,\n nestedModules: true,\n relatedAssets: true,\n warnings: true,\n // These two add a massive amount of time to the serialization on big builds.\n reasons: false,\n chunkModules: false,\n });\n statsTimer.end();\n return statsJson;\n });\n });\n };\n\nconst getRollupPlugin = (\n write: (getOutputs: () => OutputBundle[]) => void,\n): PluginOptions['rollup'] & PluginOptions['vite'] => {\n const outputs: Set<OutputBundle> = new Set();\n return {\n buildStart() {\n // Clear set on build start.\n outputs.clear();\n },\n writeBundle(opts, bundle) {\n outputs.add(bundle);\n },\n closeBundle() {\n write(() => Array.from(outputs));\n },\n };\n};\n\nexport const getFilePath = (outDir: string, pathOption: string, filename: string): string => {\n // If we have an absolute path, we use it as is.\n const outputPath = path.isAbsolute(pathOption)\n ? pathOption\n : // Otherwise, we resolve it relative to the bundler output directory.\n path.resolve(outDir, pathOption);\n return path.resolve(outputPath, filename);\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options);\n\n const writeFile = (name: FileKey, data: any) => {\n const fileValue: FileValue = validatedOptions.files[name];\n if (!data || fileValue === false) {\n return;\n }\n\n const queuedWrite = async () => {\n const timeWrite = log.time(`output ${fileValue}`);\n const filePath = getFilePath(context.bundler.outDir, validatedOptions.path, fileValue);\n let error: unknown;\n\n try {\n const dataToWrite = typeof data === 'function' ? await data() : data;\n await outputJson(filePath, dataToWrite);\n } catch (e) {\n error = e;\n }\n\n if (error) {\n log.error(`Failed writing ${fileValue}: ${error}`);\n } else {\n log.debug(`Wrote \"./${path.relative(context.buildRoot, filePath)}\"`);\n }\n\n timeWrite.end();\n };\n // Do not make the file creations blocking.\n context.queue(queuedWrite());\n };\n\n return [\n {\n name: PLUGIN_NAME,\n buildReport(report) {\n const timeSerialization = log.time(`serialize report`);\n const serializedReport = serializeBuildReport(report);\n timeSerialization.end();\n writeFile('build', {\n bundler: serializedReport.bundler,\n metadata: serializedReport.metadata,\n start: serializedReport.start,\n end: serializedReport.end,\n duration: serializedReport.duration,\n writeDuration: serializedReport.writeDuration,\n entries: serializedReport.entries,\n outputs: serializedReport.outputs,\n });\n writeFile('logs', serializedReport.logs);\n writeFile('timings', serializedReport.timings);\n writeFile('dependencies', serializedReport.inputs);\n writeFile('errors', serializedReport.errors);\n writeFile('warnings', serializedReport.warnings);\n },\n metrics(metrics) {\n writeFile('metrics', () => Array.from(metrics));\n },\n esbuild: {\n setup(build) {\n build.onEnd((result) => {\n writeFile('bundler', result.metafile);\n });\n },\n },\n rspack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n rollup: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n vite: getRollupPlugin((getOutputs) => {\n writeFile('bundler', getOutputs);\n }),\n webpack: getXpackPlugin(log, (getStats) => {\n writeFile('bundler', getStats);\n }),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\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 { createHash } from 'crypto';\n\nconst VARIANT_CHARS = ['8', '9', 'a', 'b'] as const;\n\n// SHA-256(input) truncated to 128 bits → deterministic UUID-v4-shaped identifier.\n// SHA-256 is used instead of MD5 for FIPS 140-2/3 compliance.\nexport const stringToUUID = (input: string): string => {\n const hash = createHash('sha256').update(input).digest('hex').slice(0, 32);\n const withVersion = `${hash.slice(0, 12)}4${hash.slice(13)}`;\n const variantIndex = withVersion.charCodeAt(16) % 4;\n const withVariant = `${withVersion.slice(0, 16)}${VARIANT_CHARS[variantIndex]}${withVersion.slice(17)}`;\n return [\n withVariant.slice(0, 8),\n withVariant.slice(8, 12),\n withVariant.slice(12, 16),\n withVariant.slice(16, 20),\n withVariant.slice(20, 32),\n ].join('-');\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 { ChunkInfo } from '@dd/core/types';\nimport { randomUUID } from 'crypto';\n\nimport { stringToUUID } from './debugId';\nimport type { SourceCodeContextOptions } from './types';\n\nexport const DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE = 'DD_SOURCE_CODE_CONTEXT' as const;\n\n// The source code context snippet - single injection with function definition and call\n// SSR-safe: checks window before accessing, never throws\n//\n// Unminified version:\n// (function(c, n) {\n// try {\n// if (typeof window === 'undefined') return;\n// var w = window,\n// m = w[n] = w[n] || {},\n// s = new Error().stack;\n// s && (m[s] = c)\n// } catch (e) {}\n// })(context, variableName);\n\ntype SourceCodeContext = {\n service?: string;\n version?: string;\n ddDebugId?: string;\n};\n\nexport type SourceCodeContextSnippet = {\n code: string;\n debugId?: string;\n};\n\nexport const getSourceCodeContextSnippet = (\n contextOptions: SourceCodeContextOptions,\n chunk?: ChunkInfo,\n): SourceCodeContextSnippet => {\n // Compute deterministic debug IDs whenever possible to prevent the backend from storing\n // duplicate source maps for identical builds.\n let debugId: string | undefined;\n if (contextOptions.debugId === true) {\n debugId = chunk ? stringToUUID(chunk.sourceOrHash) : randomUUID();\n }\n const context: SourceCodeContext = {\n service: contextOptions.service,\n version: contextOptions.version,\n // The `dd` prefix lets upload tools locate the value and send it as sourcemap metadata.\n ddDebugId: debugId,\n };\n\n const code = `(function(c,n){try{if(typeof window==='undefined')return;var w=window,m=w[n]=w[n]||{},s=new Error().stack;s&&(m[s]=c)}catch(e){}})(${JSON.stringify(context)},${JSON.stringify(DEFAULT_SOURCE_CODE_CONTEXT_VARIABLE)});`;\n\n return { code, debugId };\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-rum-privacy-plugin' as const;\nexport const PRIVACY_HELPERS_FILE_NAME = 'privacy-helpers';\nexport const PRIVACY_HELPERS_MODULE_ID = `\\0datadog:${PRIVACY_HELPERS_FILE_NAME}`;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { instrument } from '@datadog/js-instrumentation-wasm';\nimport type { GlobalContext, PluginOptions } from '@dd/core/types';\nimport type { NativeBuildContext } from 'unplugin';\n\nimport { PLUGIN_NAME } from './constants';\nimport { buildTransformOptions } from './transform';\nimport type { PrivacyOptionsWithDefaults } from './types';\n\nfunction getInputSourceMap(nativeBuildContext: NativeBuildContext | undefined): string | undefined {\n // Only rspack and webpack expose the input source map. Beyond that, we wouldn't want\n // to process it on other bundlers, because they automatically merge the source maps\n // produced by chained loaders.\n if (nativeBuildContext?.framework !== 'rspack' && nativeBuildContext?.framework !== 'webpack') {\n return undefined;\n }\n\n switch (typeof nativeBuildContext.inputSourceMap) {\n case 'undefined': // There's no input source map.\n return undefined;\n case 'string': // There's an input source map in serialized form.\n return nativeBuildContext.inputSourceMap;\n default: // There's an input source map in parsed form; we need to serialize it.\n return JSON.stringify(nativeBuildContext.inputSourceMap);\n }\n}\n\nexport const getPrivacyPlugin = (\n pluginOptions: PrivacyOptionsWithDefaults,\n context: GlobalContext,\n): PluginOptions => {\n const log = context.getLogger(PLUGIN_NAME);\n\n const transformOptions = buildTransformOptions(\n pluginOptions.helperCodeExpression,\n context.bundler.name,\n );\n let dictionaryEntryCount = 0;\n let fileCount = 0;\n return {\n name: PLUGIN_NAME,\n // Enforce when the plugin will be executed.\n // Not supported by Rollup and ESBuild.\n // https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n enforce: 'post',\n transform: {\n filter: {\n id: {\n include: pluginOptions.include,\n exclude: pluginOptions.exclude,\n },\n },\n handler(code, id) {\n try {\n const map = getInputSourceMap(this.getNativeBuildContext?.());\n const result = instrument({ id, code, map }, transformOptions);\n if (result.privacyDictionarySize === 0) {\n return {\n // This should be the same as the result from js-instrumentation-wasm\n // returning the original code only to make it explicit for debugging purposes\n code,\n };\n }\n dictionaryEntryCount += result.privacyDictionarySize;\n fileCount++;\n return result;\n } catch (e) {\n log.error(`Instrumentation Error: ${e}`, { forward: true });\n return {\n code,\n };\n }\n },\n },\n buildEnd: () => {\n log.debug(\n `Privacy dictionary will include ${dictionaryEntryCount} entries across ${fileCount} files`,\n {\n forward: true,\n context: {\n dictionaryEntryCount,\n fileCount,\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 { InstrumentationOptions } from '@datadog/js-instrumentation-wasm';\n\nexport interface TransformOutput {\n code: string;\n map?: string;\n}\n\nexport function buildTransformOptions(\n helperCodeExpression: string,\n bundlerName: string,\n): InstrumentationOptions {\n const transformOptions: InstrumentationOptions = {\n privacy: {\n addToDictionaryHelper: {\n expression: {\n code: helperCodeExpression,\n },\n },\n },\n };\n if (['esbuild', 'webpack', 'rspack'].includes(bundlerName)) {\n transformOptions.output = {\n ...transformOptions.output,\n inlineSourceMap: false,\n embedCodeInSourceMap: true,\n };\n }\n return transformOptions;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { doRequest } from '@dd/core/helpers/request';\nimport type { GlobalContext, InjectedValue } from '@dd/core/types';\n\nimport type { RumOptionsWithDefaults, RumOptionsWithSdk } from './types';\n\ntype RumAppResponse = {\n data: {\n attributes: {\n client_token: string;\n };\n };\n};\n\nconst getContent = (opts: RumOptionsWithDefaults) => {\n return `DD_RUM.init({${JSON.stringify(opts.sdk).replace(/(^{|}$)/g, '')}});\n`;\n};\n\nexport const getInjectionValue = (\n options: RumOptionsWithSdk,\n context: GlobalContext,\n): InjectedValue => {\n const sdkOpts = options.sdk;\n // We already have the clientToken, we can inject it directly.\n if (sdkOpts.clientToken) {\n return getContent(options);\n }\n\n // Let's try and fetch the clientToken from the API.\n if (!context.auth.apiKey || !context.auth.appKey) {\n throw new Error(\n 'Missing \"auth.apiKey\" and/or \"auth.appKey\" to fetch \"rum.sdk.clientToken\".',\n );\n }\n\n // Return the value as an async function so it gets resolved during buildStart.\n return async () => {\n let clientToken: string;\n try {\n // Fetch the client token from the API.\n const appResponse = await doRequest<RumAppResponse>({\n url: `https://api.${context.auth.site}/api/v2/rum/applications/${sdkOpts.applicationId}`,\n type: 'json',\n auth: context.auth,\n });\n\n clientToken = appResponse.data?.attributes?.client_token;\n } catch (e: any) {\n // Could not fetch the clientToken.\n // Let's crash the build.\n throw new Error(`Could not fetch the clientToken: ${e.message}`);\n }\n\n // Still no clientToken.\n if (!clientToken) {\n throw new Error('Missing clientToken in the API response.');\n }\n\n return getContent({\n ...options,\n sdk: {\n clientToken,\n ...sdkOpts,\n },\n });\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { Logger, Options, OptionsWithDefaults } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport type { PrivacyOptionsWithDefaults } from './privacy/types';\nimport type {\n RumOptions,\n RumOptionsWithDefaults,\n SDKOptionsWithDefaults,\n SourceCodeContextOptions,\n} from './types';\n\nexport const validateOptions = (\n options: OptionsWithDefaults,\n log: Logger,\n): RumOptionsWithDefaults => {\n const errors: string[] = [];\n\n // Validate and add defaults sub-options.\n const sdkResults = validateSDKOptions(options);\n const privacyResults = validatePrivacyOptions(options);\n const sourceCodeContextResults = validateSourceCodeContextOptions(options);\n\n errors.push(...sdkResults.errors);\n errors.push(...privacyResults.errors);\n errors.push(...sourceCodeContextResults.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 ...options[CONFIG_KEY],\n sdk: undefined,\n privacy: undefined,\n sourceCodeContext: undefined,\n };\n\n // Fill in the defaults.\n if (sdkResults.config) {\n toReturn.sdk = sdkResults.config;\n }\n\n if (privacyResults.config) {\n toReturn.privacy = privacyResults.config;\n\n log.debug(\n `datadog-rum-privacy plugin options: ${JSON.stringify(toReturn.privacy, (_, value) => {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n })}`,\n { forward: true },\n );\n }\n\n if (sourceCodeContextResults.config) {\n toReturn.sourceCodeContext = sourceCodeContextResults.config;\n }\n\n return toReturn;\n};\n\ntype ToReturn<T> = {\n errors: string[];\n config?: T;\n};\n\nexport const validateSDKOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SDKOptionsWithDefaults> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SDKOptionsWithDefaults> = {\n errors: [],\n };\n if (!validatedOptions.sdk) {\n return toReturn;\n }\n\n // Validate the configuration.\n if (!validatedOptions.sdk.applicationId) {\n toReturn.errors.push(`Missing ${red('applicationId')} in the SDK configuration.`);\n }\n\n // Check if we have all we need to fetch the client token if necessary.\n if ((!options.auth.apiKey || !options.auth.appKey) && !validatedOptions.sdk.clientToken) {\n toReturn.errors.push(\n `Missing ${red('\"auth.apiKey\"')} and/or ${red('\"auth.appKey\"')} to fetch missing client token.`,\n );\n }\n\n const sdkWithDefault: SDKOptionsWithDefaults = {\n applicationId: 'unknown_application_id',\n allowUntrustedEvents: false,\n compressIntakeRequests: false,\n defaultPrivacyLevel: 'mask',\n enablePrivacyForActionName: false,\n sessionReplaySampleRate: 0,\n sessionSampleRate: 100,\n silentMultipleInit: false,\n site: options.auth.site || 'datadoghq.com',\n startSessionReplayRecordingManually: false,\n storeContextsAcrossPages: false,\n telemetrySampleRate: 20,\n traceSampleRate: 100,\n trackingConsent: 'granted',\n trackLongTasks: false,\n trackResources: false,\n trackUserInteractions: false,\n trackViewsManually: false,\n };\n\n // Save the config.\n toReturn.config = {\n ...sdkWithDefault,\n ...validatedOptions.sdk,\n };\n\n return toReturn;\n};\n\nexport const validatePrivacyOptions = (options: Options): ToReturn<PrivacyOptionsWithDefaults> => {\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<PrivacyOptionsWithDefaults> = {\n errors: [],\n };\n\n if (validatedOptions.privacy) {\n const privacyWithDefault: PrivacyOptionsWithDefaults = {\n // Exclude dependencies and preval files from being transformed. Files starting with\n // special characters are likely to be virtual libraries and are excluded to avoid loading them.\n exclude: [/\\/node_modules\\//, /\\.preval\\./, /^[!@#$%^&*()=+~`-]/],\n include: [/\\.(?:c|m)?(?:j|t)sx?$/],\n addToDictionaryFunctionName: '$',\n helperCodeExpression: `/*__PURE__*/((q='$DD_A_Q',g=globalThis)=>(g[q]=g[q]||[],(v=>(g[q].push(v),v))))()`,\n };\n\n toReturn.config = {\n ...privacyWithDefault,\n ...validatedOptions.privacy,\n };\n }\n\n return toReturn;\n};\n\nexport const validateSourceCodeContextOptions = (\n options: OptionsWithDefaults,\n): ToReturn<SourceCodeContextOptions> => {\n const red = chalk.bold.red;\n const validatedOptions: RumOptions = options[CONFIG_KEY] || {};\n const toReturn: ToReturn<SourceCodeContextOptions> = {\n errors: [],\n };\n\n if (!validatedOptions.sourceCodeContext) {\n return toReturn;\n }\n\n const cfg: SourceCodeContextOptions = validatedOptions.sourceCodeContext;\n\n if (cfg.debugId === true) {\n toReturn.config = {\n ...cfg,\n version: cfg.version || (cfg.service ? options.metadata?.version : undefined),\n };\n return toReturn;\n }\n\n if (!cfg.service || typeof cfg.service !== 'string') {\n toReturn.errors.push(`Missing ${red('\"rum.sourceCodeContext.service\"')}.`);\n }\n\n if (toReturn.errors.length === 0) {\n // Resolve `version`: prefer the plugin-specific option, then fall back to\n // the shared top-level `metadata.version`.\n toReturn.config = {\n ...cfg,\n version: cfg.version || options.metadata?.version,\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 type { RumInitConfiguration, RumPublicApi } from './browserSdkTypes';\nimport { CONFIG_KEY, PLUGIN_NAME } from './constants';\nimport { getSourceCodeContextSnippet } from './getSourceCodeContextSnippet';\nimport { getPrivacyPlugin } from './privacy';\nimport { getInjectionValue } from './sdk';\nimport type { RumOptions, RumOptionsWithSdk } 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 RumOptions: RumOptions;\n RumPublicApi: RumPublicApi;\n RumInitConfiguration: RumInitConfiguration;\n};\n\nexport const getPlugins: GetPlugins = ({ options, context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const validatedOptions = validateOptions(options, log);\n const plugins: PluginOptions[] = [];\n const sourceCodeContext = validatedOptions.sourceCodeContext;\n\n if (sourceCodeContext) {\n context.inject({\n type: 'code',\n position: InjectPosition.BEFORE,\n injectIntoAllChunks: true,\n value: (chunk) => {\n // The debug_id is embedded directly in the returned code (see\n // getSourceCodeContextSnippet.ts); error-tracking reads it back out of the\n // built file's content at upload time, so it doesn't need to be tracked here.\n const { code } = getSourceCodeContextSnippet(sourceCodeContext, chunk);\n return code;\n },\n });\n }\n\n // NOTE: These files are built from \"@dd/tools/rollupConfig.mjs\" and available in the distributed package.\n if (validatedOptions.sdk) {\n // Inject the SDK from the CDN.\n context.inject({\n type: 'file',\n // Using MIDDLE otherwise it's not executed in context.\n position: InjectPosition.MIDDLE,\n // This file is being built alongside the bundler plugin.\n value: path.join(__dirname, './rum-browser-sdk.js'),\n });\n\n // Inject the SDK Initialization.\n context.inject({\n type: 'code',\n position: InjectPosition.MIDDLE,\n value: getInjectionValue(validatedOptions as RumOptionsWithSdk, context),\n });\n }\n\n if (validatedOptions.privacy) {\n // Add the privacy plugin.\n context.inject({\n type: 'file',\n position: InjectPosition.BEFORE,\n value: path.join(__dirname, './privacy-helpers.js'),\n });\n const privacyPlugin = getPrivacyPlugin(validatedOptions.privacy, context);\n plugins.push(privacyPlugin);\n }\n\n return plugins;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-analytics-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getAnalyticsPlugins: GetInternalPlugins = ({ context }) => {\n const log = context.getLogger(PLUGIN_NAME);\n const buildStartFn = async () => {\n try {\n await context.sendLog({\n message: 'Build started',\n context: {\n plugins: context.pluginNames,\n },\n });\n } catch (e: unknown) {\n // We don't want to break anything in case of error.\n log.debug(`Could not submit data to Datadog: ${e}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n async buildStart() {\n // Only send logs in production.\n if (context.env !== 'production') {\n return;\n }\n\n // Use the queue so it doesn't block the build process.\n context.queue(buildStartFn());\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-async-queue-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME };\n\nexport const getAsyncQueuePlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context, stores } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n const errors: string[] = [];\n\n // Initialize the queue function\n context.queue = (promise: Promise<any>) => {\n // Wrap the promise to catch errors immediately\n const wrappedPromise = promise.catch((error: any) => {\n errors.push(error.message || error.toString());\n });\n stores.queue.push(wrappedPromise);\n };\n\n return [\n {\n name: PLUGIN_NAME,\n asyncTrueEnd: async () => {\n // Await for all promises to finish processing.\n await Promise.all(stores.queue);\n if (errors.length > 0) {\n log.error(\n `Error occurred while processing async queue:\\n ${errors.join('\\n ')}`,\n );\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { BundlerName, GlobalContext, Logger, ResolvedEntry } from '@dd/core/types';\nimport type { PluginBuild } from 'esbuild';\nimport { glob } from 'glob';\n\n// https://esbuild.github.io/api/#glob-style-entry-points\n// Exported only for testing purposes.\nexport const getAllEntryFiles = (filepath: string): string[] => {\n if (!filepath.includes('*')) {\n return [filepath];\n }\n\n const files = glob.sync(filepath);\n return files;\n};\n\n// Parse, resolve and return all the entries of esbuild.\nexport const getEsbuildEntries = async (\n build: PluginBuild,\n context: GlobalContext,\n log: Logger,\n): Promise<ResolvedEntry[]> => {\n const entries: { name?: string; resolved: string; original: string }[] = [];\n const entryPoints = build.initialOptions.entryPoints;\n const entryPaths: { name?: string; path: string }[] = [];\n const resolutionErrors: string[] = [];\n\n if (Array.isArray(entryPoints)) {\n for (const entry of entryPoints) {\n const fullPath = entry && typeof entry === 'object' ? entry.in : entry;\n entryPaths.push({ path: fullPath });\n }\n } else if (entryPoints && typeof entryPoints === 'object') {\n entryPaths.push(\n ...Object.entries(entryPoints).map(([name, filepath]) => ({ name, path: filepath })),\n );\n }\n\n // Resolve all the paths.\n const proms = entryPaths\n .flatMap((entry) =>\n getAllEntryFiles(entry.path).map<[{ name?: string; path: string }, string]>((p) => [\n entry,\n p,\n ]),\n )\n .map(async ([entry, p]) => {\n const result = await build.resolve(p, {\n kind: 'entry-point',\n resolveDir: context.buildRoot,\n });\n\n if (result.errors.length) {\n resolutionErrors.push(...result.errors.map((e) => e.text));\n }\n\n if (result.path) {\n // Store them for later use.\n entries.push({\n name: entry.name,\n resolved: result.path,\n original: entry.path,\n });\n }\n });\n\n for (const resolutionError of resolutionErrors) {\n log.error(resolutionError);\n }\n\n await Promise.all(proms);\n return entries;\n};\n\n// From a bundler's name, is it part of the \"xpack\" family?\nexport const isXpack = (bundlerName: BundlerName) => ['rspack', 'webpack'].includes(bundlerName);\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\nimport { existsSync } from './fs';\n\n// Will only prepend the cwd if not already there.\nexport const getAbsolutePath = (cwd: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath.startsWith(cwd) || path.isAbsolute(filepath)) {\n return filepath;\n }\n return path.resolve(cwd, filepath);\n};\n\nexport const getClosest = (currentDir: string, filename: string) => {\n let closest;\n let current = getAbsolutePath(process.cwd(), currentDir);\n while (!closest) {\n const filepath = path.resolve(current, filename);\n // Check if it exists in the current directory.\n if (existsSync(filepath)) {\n closest = filepath;\n }\n // Remove the last part of the path.\n current = current.split(path.sep).slice(0, -1).join(path.sep);\n\n // Exit if we reach the root directory.\n if ([path.sep, ''].includes(current)) {\n break;\n }\n }\n return closest;\n};\n\n// Find the closest package.json from the current directory.\nexport const getClosestPackageJson = (currentDir: string): string | undefined => {\n return getClosest(currentDir, 'package.json');\n};\n\n// From a list of path, return the nearest common directory.\nexport const getNearestCommonDirectory = (dirs: string[], cwd?: string) => {\n const dirsToCompare = [...dirs];\n\n const splitPaths = dirsToCompare.map((dir) => {\n const absolutePath = getAbsolutePath(cwd || process.cwd(), dir);\n return absolutePath.split(path.sep);\n });\n\n // Use the shortest length for faster results.\n const minLength = splitPaths.length ? Math.min(...splitPaths.map((parts) => parts.length)) : 0;\n const commonParts = [];\n\n for (let i = 0; i < minLength; i++) {\n // We use the first path as our basis.\n const component = splitPaths[0][i];\n if (splitPaths.every((parts) => parts[i] === component)) {\n commonParts.push(component);\n } else {\n break;\n }\n }\n\n return commonParts.length > 0\n ? // Use \"|| path.sep\" to cover for the [''] case.\n commonParts.join(path.sep) || path.sep\n : path.sep;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport path from 'path';\n\n// Will match any last part of a path after a dot or slash and is a word character.\nconst EXTENSION_RX = /\\.(?!.*(?:\\.|\\/|\\\\))(\\w{1,})/g;\n\n// Will match any type of query characters.\n// \"?\" or \"%3F\" (url encoded \"?\") or \"|\"\nconst QUERY_RX = /(\\?|%3F|\\|)+/gi;\n\nconst getExtension = (filepath: string) => {\n // Reset RX first.\n EXTENSION_RX.lastIndex = 0;\n return EXTENSION_RX.exec(filepath)?.[1];\n};\n\nexport const getType = (name: string): string => {\n if (name === 'unknown') {\n return name;\n }\n\n if (name.includes('webpack/runtime')) {\n return 'runtime';\n }\n\n return getExtension(cleanPath(name)) || 'unknown';\n};\n\nconst BUNDLER_SPECIFICS = ['unknown', 'commonjsHelpers.js', `vite${path.sep}preload-helper.js`];\n// Make list of paths unique, remove the current file and particularities.\nexport const cleanReport = <T = string>(\n report: Set<string>,\n filepath: string,\n filter?: (p: string) => T,\n) => {\n const cleanedReport: Set<T> = new Set();\n for (const reportFilepath of report) {\n const cleanedPath = cleanPath(reportFilepath);\n if (\n // Don't add injections.\n isInjectionFile(reportFilepath) ||\n // Don't add itself into it.\n cleanedPath === filepath ||\n // Remove common specific files injected by bundlers.\n BUNDLER_SPECIFICS.includes(cleanedPath)\n ) {\n continue;\n }\n\n if (filter) {\n const filteredValue = filter(cleanedPath);\n if (filteredValue) {\n cleanedReport.add(filteredValue);\n }\n } else {\n cleanedReport.add(cleanedPath as unknown as T);\n }\n }\n return cleanedReport;\n};\n\n// Clean a path from its query parameters and leading invisible characters.\n// Careful with this and webpack/rspack as loaders may add \"|\" before and after the filepath.\nexport const cleanPath = (filepath: string) => {\n return (\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading, invisible characters,\n // sometimes added in rollup by the commonjs plugin.\n .replace(/^[^\\w\\s.,!@#$%^&*()=+~`\\-/\\\\]+/, '')\n );\n};\n\n// From two file paths, remove the common path prefix.\nexport const removeCommonPrefix = (filepath1: string, filepath2: string) => {\n const filepath2Split = filepath2.split(path.sep);\n const commonPath = filepath1\n .split(path.sep)\n .filter((part, index) => part === filepath2Split[index])\n .join(path.sep);\n return filepath1.replace(commonPath, '');\n};\n\n// Extract a name from a path based on the context (outDir and cwd).\nexport const cleanName = (absoluteOutDir: string, filepath: string) => {\n if (isInjectionFile(filepath)) {\n return INJECTED_FILE;\n }\n\n if (filepath === 'unknown') {\n return filepath;\n }\n\n if (filepath.includes('webpack/runtime')) {\n return filepath.replace('webpack/runtime/', '').replace(/ +/g, '-');\n }\n\n return (\n removeCommonPrefix(\n filepath\n // [webpack] Only keep the loaded part of a loader query.\n .split('!')\n .pop()!,\n absoluteOutDir,\n )\n // Remove node_modules path.\n .split('node_modules')\n .pop()!\n // Remove query parameters.\n .split(QUERY_RX)\n .shift()!\n // Remove leading dots and slashes.\n .replace(/^((\\.\\.?)?[/\\\\])+/g, '')\n );\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n Output,\n PluginOptions,\n ResolvedEntry,\n} from '@dd/core/types';\nimport path from 'path';\n\nimport { cleanName, getType } from './helpers';\n\n// Re-index metafile data for easier access.\nconst reIndexMeta = <T>(obj: Record<string, T>, buildRoot: string) =>\n Object.fromEntries(\n Object.entries(obj).map(([key, value]) => {\n const newKey = getAbsolutePath(buildRoot, key);\n return [newKey, value];\n }),\n );\n\nexport const getEsbuildPlugin = (context: GlobalContext, log: Logger): PluginOptions['esbuild'] => {\n return {\n setup(build) {\n const entryNames = new Map();\n let resolvedEntries: ResolvedEntry[] = [];\n const timeBuildReport = log.time('build report', { start: false });\n\n build.onStart(async () => {\n // Start from a clean slate.\n entryNames.clear();\n resolvedEntries = [];\n\n timeBuildReport.resume();\n const timeEntries = log.time('process entries');\n // Store entry names based on the configuration.\n resolvedEntries.push(...(await getEsbuildEntries(build, context, log)));\n for (const entry of resolvedEntries) {\n const cleanedName = cleanName(context.bundler.outDir, entry.resolved);\n if (entry.name) {\n entryNames.set(cleanedName, entry.name);\n } else {\n entryNames.set(cleanedName, cleanedName);\n }\n }\n timeEntries.end();\n timeBuildReport.pause();\n });\n\n build.onEnd(async (result) => {\n timeBuildReport.resume();\n const timeCollect = log.time('collecting errors and warnings');\n const outDir = context.bundler.outDir;\n const buildRoot = context.buildRoot;\n for (const error of result.errors) {\n context.build.errors.push(error.text);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.text);\n }\n timeCollect.end();\n\n if (!result.metafile) {\n const warning = 'Missing metafile from build report.';\n context.build.warnings.push(warning);\n log.warn(warning);\n return;\n }\n\n const inputs: Input[] = [];\n const outputs: Output[] = [];\n const tempEntryFiles: Entry[] = [];\n const tempSourcemaps: Output[] = [];\n const entries: Entry[] = [];\n\n const reportInputsIndexed: Record<string, Input> = {};\n const reportOutputsIndexed: Record<string, Output> = {};\n\n const timeIndex = log.time('indexing metafile data');\n const metaInputsIndexed = reIndexMeta(result.metafile.inputs, buildRoot);\n const metaOutputsIndexed = reIndexMeta(result.metafile.outputs, buildRoot);\n timeIndex.end();\n\n // From a proxy entry point, created by our injection plugin, get the real path.\n const getRealPathFromInjectionProxy = (entryPoint: string): string => {\n if (!isInjectionFile(entryPoint)) {\n return entryPoint;\n }\n\n const metaInput = metaInputsIndexed[getAbsolutePath(buildRoot, entryPoint)];\n if (!metaInput) {\n return entryPoint;\n }\n\n // Get the first non-injection import.\n const actualImport = metaInput.imports.find(\n (imp) => !isInjectionFile(imp.path),\n );\n if (!actualImport) {\n return entryPoint;\n }\n\n return actualImport.path;\n };\n\n // Loop through inputs.\n const timeInputs = log.time('looping through inputs');\n for (const [filename, input] of Object.entries(result.metafile.inputs)) {\n if (isInjectionFile(filename)) {\n continue;\n }\n\n const filepath = getAbsolutePath(buildRoot, filename);\n const name = cleanName(outDir, filename);\n\n const file: Input = {\n name,\n filepath,\n dependents: new Set(),\n dependencies: new Set(),\n size: input.bytes,\n type: getType(filename),\n };\n reportInputsIndexed[filepath] = file;\n inputs.push(file);\n }\n timeInputs.end();\n\n // Loop through outputs.\n const timeOutputs = log.time('looping through outputs');\n for (const [filename, output] of Object.entries(result.metafile.outputs)) {\n const fullPath = getAbsolutePath(buildRoot, filename);\n const cleanedName = cleanName(outDir, fullPath);\n // Get inputs of this output.\n const inputFiles: Input[] = [];\n for (const inputName of Object.keys(output.inputs)) {\n if (isInjectionFile(inputName)) {\n continue;\n }\n\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, inputName)];\n if (!inputFound) {\n log.debug(`Input ${inputName} not found for output ${cleanedName}`);\n continue;\n }\n\n inputFiles.push(inputFound);\n }\n\n // When splitting, esbuild creates an empty entryPoint wrapper for the chunk.\n // It has no inputs, but still relates to its entryPoint.\n if (output.entryPoint && !inputFiles.length) {\n const inputFound =\n reportInputsIndexed[getAbsolutePath(buildRoot, output.entryPoint)];\n if (!inputFound) {\n log.debug(\n `Input ${output.entryPoint} not found for output ${cleanedName}`,\n );\n continue;\n }\n inputFiles.push(inputFound);\n }\n\n const file: Output = {\n name: cleanedName,\n filepath: fullPath,\n inputs: inputFiles,\n size: output.bytes,\n type: getType(fullPath),\n };\n\n reportOutputsIndexed[fullPath] = file;\n\n // Store sourcemaps for later filling.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n }\n\n outputs.push(file);\n\n if (!output.entryPoint) {\n continue;\n }\n\n // The entryPoint may have been altered by our injection plugin.\n const inputFile =\n reportInputsIndexed[\n getAbsolutePath(\n buildRoot,\n getRealPathFromInjectionProxy(output.entryPoint),\n )\n ];\n\n if (inputFile) {\n // In the case of \"splitting: true\", all the files are considered entries to esbuild.\n // Not to us.\n // Verify we have listed it as an entry earlier.\n if (!entryNames.get(inputFile.name)) {\n continue;\n }\n\n const entry = {\n ...file,\n name: entryNames.get(inputFile.name) || inputFile.name,\n outputs: [file],\n size: file.size,\n };\n\n tempEntryFiles.push(entry);\n }\n }\n timeOutputs.end();\n\n // Loop through sourcemaps.\n const timeSourcemaps = log.time('looping through sourcemaps');\n for (const sourcemap of tempSourcemaps) {\n const outputFilepath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = reportOutputsIndexed[outputFilepath];\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n\n // Build our references for the entries.\n const references = {\n inputs: {\n report: reportInputsIndexed,\n meta: metaInputsIndexed,\n },\n outputs: {\n report: reportOutputsIndexed,\n meta: metaOutputsIndexed,\n },\n };\n\n // There are some exceptions we want to ignore.\n const FILE_EXCEPTIONS_RX = /(<runtime>|https:|file:|data:|#)/g;\n const isFileSupported = (filePath: string) => {\n if (isInjectionFile(filePath) || filePath.match(FILE_EXCEPTIONS_RX)) {\n return false;\n }\n return true;\n };\n\n // Go through all imports.\n const getAllImports = <T extends Input | Output>(\n filePath: string,\n ref: typeof references.inputs | typeof references.outputs,\n allImports: Record<string, T> = {},\n ): Record<string, T> => {\n if (!isFileSupported(filePath)) {\n return allImports;\n }\n\n const file = ref.report[filePath];\n if (!file) {\n log.debug(`Could not find report's ${filePath}`);\n return allImports;\n }\n\n // Check if we already have processed it.\n if (allImports[file.filepath]) {\n return allImports;\n }\n\n allImports[file.filepath] = file as T;\n\n const metaFile = ref.meta[filePath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${filePath}`);\n return allImports;\n }\n\n // If there are no imports, we can return what we have.\n if (!metaFile.imports || !metaFile.imports.length) {\n return allImports;\n }\n\n for (const imported of metaFile.imports) {\n const isRelative = imported.path.match(/^\\.\\.?\\//);\n const root = isRelative ? path.dirname(filePath) : buildRoot;\n const absoluteImportPath = getAbsolutePath(root, imported.path);\n\n // We need to register external imports, as this is the first time we see them.\n if (imported.external) {\n if (isFileSupported(imported.path)) {\n // If it's an absolute external import,\n // we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteImportPath : imported.path;\n\n // But we can still add it to the report.\n const inputFile: Input = references.inputs.report[filepath] || {\n filepath,\n name: cleanName(outDir, imported.path),\n size: 0,\n type: 'external',\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if ('dependencies' in file) {\n // file is an Input, so we add the external to its dependencies,\n // and we add file to the external's dependents.\n inputFile.dependents.add(file);\n file.dependencies.add(inputFile);\n }\n\n if ('inputs' in file && !file.inputs.includes(inputFile)) {\n // file is an Output, so we add the external to its inputs.\n file.inputs.push(inputFile);\n }\n\n if (!inputs.includes(inputFile)) {\n inputs.push(inputFile);\n }\n\n references.inputs.report[filepath] = inputFile;\n allImports[inputFile.filepath] = inputFile as T;\n }\n // We can't follow external imports.\n continue;\n }\n\n // Look for the other inputs.\n getAllImports<T>(absoluteImportPath, ref, allImports);\n }\n\n return allImports;\n };\n\n // Loop through entries.\n const timeEntries = log.time('looping through entries');\n // TODO This is slightly underperformant due to getAllImports' recursivity.\n for (const entryFile of tempEntryFiles) {\n const entryInputs: Record<string, Input> = {};\n const entryOutputs: Record<string, Output> = {};\n\n // Do inputs for this entry.\n for (const input of entryFile.inputs) {\n getAllImports<Input>(input.filepath, references.inputs, entryInputs);\n }\n\n // Do outputs for this entry.\n for (const outputFile of entryFile.outputs) {\n getAllImports<Output>(\n outputFile.filepath,\n references.outputs,\n entryOutputs,\n );\n }\n\n entryFile.inputs = Object.values(entryInputs);\n entryFile.outputs = Object.values(entryOutputs);\n entryFile.size = entryFile.outputs.reduce(\n (acc, output) => acc + output.size,\n 0,\n );\n\n entries.push(entryFile);\n }\n timeEntries.end();\n\n // Loop through all inputs to aggregate dependencies and dependents.\n const timeDeps = log.time('aggregate dependencies and dependents');\n for (const input of inputs) {\n // The metafile does not contain external dependencies.\n // So we can only fill in their dependents.\n if (input.type === 'external') {\n continue;\n }\n\n const metaFile = references.inputs.meta[input.filepath];\n if (!metaFile) {\n log.debug(`Could not find metafile's ${input.name}`);\n continue;\n }\n\n for (const dependency of metaFile.imports) {\n if (!isFileSupported(dependency.path)) {\n continue;\n }\n\n const isRelative = dependency.path.match(/^\\.?\\.\\//);\n const root = isRelative ? path.dirname(input.filepath) : buildRoot;\n const absoluteDependencyPath = getAbsolutePath(root, dependency.path);\n\n let dependencyFile: Input | undefined;\n if (dependency.external) {\n // If it's an absolute external import, we can't trust our own getAbsolutePath().\n // We can't know what its \"root\" could be.\n const filepath = isRelative ? absoluteDependencyPath : dependency.path;\n // In case of externals, we use their path directly.\n dependencyFile = references.inputs.report[filepath];\n } else {\n dependencyFile = references.inputs.report[absoluteDependencyPath];\n }\n\n if (!dependencyFile) {\n log.debug(\n `Could not find input file of ${dependency.path} imported from ${input.name}`,\n );\n continue;\n }\n\n input.dependencies.add(dependencyFile);\n // Add itself to the dependency's dependents.\n dependencyFile.dependents.add(input);\n }\n }\n timeDeps.end();\n\n context.build.outputs = outputs;\n context.build.inputs = inputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, Entry, GlobalContext, Input, Output, PluginOptions } from '@dd/core/types';\nimport fs from 'fs';\n\nimport { cleanName, cleanPath, cleanReport, getType } from './helpers';\n\nexport const getRollupPlugin = (context: GlobalContext, log: Logger): PluginOptions['rollup'] => {\n const timeModuleParsing = log.time('module parsing', { start: false });\n const timeBuildReport = log.time('build report', { start: false });\n const timeEntries = log.time('filling entries', { start: false });\n const timeInputsOutputs = log.time('filling inputs and outputs', { start: false });\n const timeCompleteDeps = log.time('completing dependencies and dependents', { start: false });\n const timeDeps = log.time('filling dependencies and dependents', { start: false });\n const timeSourcemaps = log.time('filling sourcemaps inputs', { start: false });\n\n const inputs: Map<string, Input> = new Map();\n const outputs: Map<string, Output> = new Map();\n const entries: Map<string, Entry> = new Map();\n const importsReport: Map<\n string,\n {\n dependencies: Set<string>;\n dependents: Set<string>;\n }\n > = new Map();\n\n return {\n buildStart() {\n // Start clean to avoid build up in case of multiple builds.\n // It's useful with a dev server or a build with multiple outputs.\n importsReport.clear();\n inputs.clear();\n outputs.clear();\n entries.clear();\n },\n onLog(level, logItem) {\n if (level === 'warn') {\n context.build.warnings.push(logItem.message || logItem.toString());\n }\n },\n renderError(error) {\n if (error) {\n context.build.errors.push(error.message);\n }\n },\n moduleParsed(info) {\n timeModuleParsing.resume();\n // Store import infos.\n const cleanId = cleanPath(info.id);\n const report = importsReport.get(cleanId) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n // Clean new dependencies and dependents.\n const newDependencies = cleanReport(\n new Set([...info.dynamicallyImportedIds, ...info.importedIds]),\n cleanId,\n );\n\n const newDependents = cleanReport(\n new Set([...info.dynamicImporters, ...info.importers]),\n cleanId,\n );\n\n for (const dependent of newDependents) {\n report.dependents.add(dependent);\n }\n\n for (const dependency of newDependencies) {\n report.dependencies.add(dependency);\n }\n\n importsReport.set(cleanId, report);\n timeModuleParsing.tag([`module:${cleanId}`], { span: true });\n timeModuleParsing.pause();\n },\n // This can be called multiple times depending on the number of output configured.\n writeBundle(options, bundle) {\n timeBuildReport.resume();\n const outDir = options.dir\n ? getAbsolutePath(context.buildRoot, options.dir)\n : context.bundler.outDir;\n\n const tempEntryFiles: Set<Entry> = new Set();\n const tempSourcemaps: Set<Output> = new Set();\n const tempOutputsImports: Map<string, Output> = new Map();\n\n // Complete the importsReport with missing dependents and dependencies.\n timeCompleteDeps.resume();\n for (const [filepath, { dependencies, dependents }] of importsReport) {\n for (const dependency of dependencies) {\n const cleanedDependency = cleanPath(dependency);\n const report = importsReport.get(cleanedDependency) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependents.has(filepath)) {\n continue;\n }\n\n report.dependents.add(filepath);\n importsReport.set(cleanedDependency, report);\n }\n\n for (const dependent of dependents) {\n const cleanedDependent = cleanPath(dependent);\n const report = importsReport.get(cleanedDependent) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n\n if (report.dependencies.has(filepath)) {\n continue;\n }\n\n report.dependencies.add(filepath);\n importsReport.set(cleanedDependent, report);\n }\n }\n timeCompleteDeps.end();\n\n // Fill in inputs and outputs.\n timeInputsOutputs.resume();\n for (const [filename, asset] of Object.entries(bundle)) {\n const filepath = getAbsolutePath(outDir, filename);\n const size =\n 'code' in asset\n ? Buffer.byteLength(asset.code, 'utf8')\n : Buffer.byteLength(asset.source, 'utf8');\n\n const file: Output = outputs.get(filepath) || {\n name: filename,\n filepath,\n inputs: [],\n size,\n type: getType(filename),\n };\n\n // Store sourcemaps for later filling.\n // Because we may not have reported its input yet.\n if (file.type === 'map') {\n tempSourcemaps.add(file);\n }\n\n if ('modules' in asset) {\n for (const [modulepath, module] of Object.entries(asset.modules)) {\n // We don't want to include commonjs wrappers and proxies that are like:\n // \\u0000{{path}}?commonjs-proxy\n if (cleanPath(modulepath) !== modulepath) {\n continue;\n }\n\n // Since we store as input, we use the originalLength.\n let moduleSize = module.originalLength;\n if (!moduleSize && moduleSize !== 0) {\n // We don't have the size, let's get it.\n // This happens in rolldown, the API doesn't give us the original length.\n try {\n moduleSize = fs.statSync(modulepath).size;\n } catch (e) {\n // Nevermind, we tried our best, fallback to the rendered length (built).\n moduleSize = module.renderedLength;\n }\n }\n\n const moduleFile: Input = inputs.get(modulepath) || {\n name: cleanName(outDir, modulepath),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: modulepath,\n size: moduleSize,\n type: getType(modulepath),\n };\n file.inputs.push(moduleFile);\n inputs.set(moduleFile.filepath, moduleFile);\n }\n }\n\n // Add imports as inputs.\n // These are external imports since they are declared in the output file.\n if ('imports' in asset) {\n for (const importName of asset.imports) {\n const cleanedImport = cleanPath(importName);\n if (!importsReport.has(cleanedImport)) {\n // We may not have this yet as it could be one of the chunks\n // produced by the current build.\n tempOutputsImports.set(getAbsolutePath(outDir, cleanedImport), file);\n continue;\n }\n\n if (inputs.has(cleanedImport)) {\n log.debug(\n `Input report already there for ${cleanedImport} from ${file.name}.`,\n );\n continue;\n }\n\n const importFile: Input = inputs.get(cleanedImport) || {\n name: cleanName(outDir, importName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: cleanedImport,\n // Since it's external, we don't have the size.\n size: 0,\n type: 'external',\n };\n file.inputs.push(importFile);\n inputs.set(importFile.filepath, importFile);\n }\n }\n\n // Store entries for later filling.\n // As we may not have reported its outputs and inputs yet.\n if ('isEntry' in asset && asset.isEntry) {\n tempEntryFiles.add({ ...file, name: asset.name, size: 0, outputs: [file] });\n }\n\n outputs.set(file.filepath, file);\n }\n timeInputsOutputs.end();\n\n for (const [filepath, output] of tempOutputsImports) {\n const outputReport = outputs.get(filepath);\n if (!outputReport) {\n log.debug(`Could not find the output report for ${filepath}.`);\n continue;\n }\n\n if (!output.inputs.includes(outputReport)) {\n output.inputs.push(outputReport);\n }\n }\n\n // Fill in inputs' dependencies and dependents.\n timeDeps.resume();\n for (const [filepath, input] of inputs) {\n const importReport = importsReport.get(filepath);\n if (!importReport) {\n log.debug(`Could not find the import report for ${input.name}.`);\n continue;\n }\n\n for (const dependency of importReport.dependencies) {\n const foundInput = inputs.get(dependency);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependency ${cleanName(outDir, dependency)} of ${input.name}`,\n );\n continue;\n }\n input.dependencies.add(foundInput);\n }\n\n for (const dependent of importReport.dependents) {\n const foundInput = inputs.get(dependent);\n if (!foundInput) {\n log.debug(\n `Could not find input for dependent ${cleanName(outDir, dependent)} of ${input.name}`,\n );\n continue;\n }\n input.dependents.add(foundInput);\n }\n }\n timeDeps.end();\n\n // Fill in sourcemaps' inputs if necessary\n if (tempSourcemaps.size) {\n timeSourcemaps.resume();\n for (const sourcemap of tempSourcemaps) {\n const outputPath = sourcemap.filepath.replace(/\\.map$/, '');\n const foundOutput = outputs.get(outputPath);\n\n if (!foundOutput) {\n log.debug(`Could not find output for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(foundOutput);\n }\n timeSourcemaps.end();\n }\n\n // Gather all outputs from a filepath, following imports.\n const getAllOutputs = (\n filepath: string,\n allOutputs: Map<string, Output> = new Map(),\n ) => {\n // We already processed it.\n if (allOutputs.has(filepath)) {\n return allOutputs;\n }\n const filename = cleanName(outDir, filepath);\n\n // Get its output.\n const foundOutput = outputs.get(filepath);\n if (!foundOutput) {\n // If it's been reported in the inputs, it means it's an external here.\n // Do not log about externals, we don't expect to find them.\n if (!inputs.has(filename)) {\n log.debug(`Could not find output for ${filename}`);\n }\n return allOutputs;\n }\n allOutputs.set(filepath, foundOutput);\n\n // Rollup indexes on the filepath relative to the outDir.\n const asset = bundle[cleanName(outDir, filepath)];\n if (!asset) {\n log.debug(`Could not find asset for ${filename}`);\n return allOutputs;\n }\n\n // Imports are stored in two different places.\n const imports = [];\n if ('imports' in asset) {\n imports.push(...asset.imports);\n }\n if ('dynamicImports' in asset) {\n imports.push(...asset.dynamicImports);\n }\n\n for (const importName of imports) {\n getAllOutputs(getAbsolutePath(outDir, importName), allOutputs);\n }\n\n return allOutputs;\n };\n\n // Fill in entries\n timeEntries.resume();\n for (const entryFile of tempEntryFiles) {\n const entryOutputs = getAllOutputs(entryFile.filepath);\n entryFile.outputs = Array.from(entryOutputs.values());\n\n // NOTE: This might not be as accurate as expected, some inputs could be side-effects.\n // Rollup doesn't provide a way to get the imports of an input.\n entryFile.inputs = Array.from(\n new Set(entryFile.outputs.flatMap((output) => output.inputs)),\n );\n entryFile.size = entryFile.outputs.reduce((acc, output) => acc + output.size, 0);\n\n if (entries.has(entryFile.filepath)) {\n log.debug(\n `Entry \"${entryFile.name}\":\"${cleanName(outDir, entryFile.filepath)}\" already reported.`,\n );\n }\n\n entries.set(entryFile.filepath, entryFile);\n }\n timeEntries.pause();\n timeBuildReport.pause();\n },\n async closeBundle() {\n context.build.inputs = Array.from(inputs.values());\n context.build.outputs = Array.from(outputs.values());\n context.build.entries = Array.from(entries.values());\n\n timeEntries.end();\n timeBuildReport.end();\n\n await context.asyncHook('buildReport', context.build);\n },\n };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type {\n Logger,\n Entry,\n GlobalContext,\n Input,\n IterableElement,\n Output,\n PluginOptions,\n} from '@dd/core/types';\n\nimport { cleanName, cleanPath, getType } from './helpers';\n\nexport const getXpackPlugin =\n (\n context: GlobalContext,\n PLUGIN_NAME: string,\n log: Logger,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n let inputs: Input[] = [];\n let outputs: Output[] = [];\n let entries: Entry[] = [];\n\n // Types for the xpack hooks.\n type Compilation = Parameters<Parameters<typeof compiler.hooks.thisCompilation.tap>[1]>[0];\n type Module = IterableElement<Compilation['modules']>;\n type Dependency = IterableElement<IterableElement<Module['blocks']>['dependencies']>;\n type Chunk = IterableElement<Compilation['chunks']>;\n type IndexedModule = {\n identifier: Module['identifier'];\n dependencies: Dependency[];\n blocks: any[];\n externalType: unknown;\n external: unknown;\n };\n\n // Some indexes to help with the report generation.\n const reportInputsIndexed: Map<string, Input> = new Map();\n const reportOutputsIndexed: Map<string, Output> = new Map();\n const modulesPerFile: Map<string, Set<string>> = new Map();\n const moduleIndex: Map<string, IndexedModule> = new Map();\n\n // Some temporary holders to later fill in more data.\n const tempSourcemaps: Output[] = [];\n const tempDeps: Map<string, { dependencies: Set<string>; dependents: Set<string> }> =\n new Map();\n\n const timeBuildReport = log.time('build report', { start: false });\n\n const isModuleSupported = (moduleIdentifier?: string): boolean => {\n return (\n // Ignore unidentified modules and runtimes.\n !!moduleIdentifier &&\n !moduleIdentifier.startsWith('webpack/runtime') &&\n !moduleIdentifier.startsWith('multi ') &&\n !isInjectionFile(moduleIdentifier)\n );\n };\n\n /**\n * Let's get build data from webpack.\n * 1. Build a dependency graph from all the initial modules once they're finished\n * In afterEmit, modules are concatenated and obfuscated.\n * 2. Once the build is finished and emitted, we can compute the outputs and the entries.\n */\n\n // Clear the data in case we have multiple compilations (dev server, etc...).\n const clear = () => {\n inputs = [];\n outputs = [];\n entries = [];\n reportInputsIndexed.clear();\n reportOutputsIndexed.clear();\n moduleIndex.clear();\n tempDeps.clear();\n };\n\n const cleanExternalName = (name: string) => {\n // Removes \"external \" prefix and surrounding quotes from external dependency names\n // Example: 'external var \"lodash\"' -> 'lodash'\n return name.replace(/(^external[^\"]+\"|\"$)/g, '');\n };\n\n // Index the module by its identifier, resource, request, rawRequest, and userRequest.\n const getKeysToIndex = (mod: Module): Set<string> => {\n const indexes = new Set<string>();\n\n const keysOfModuleToIndexOn: string[] = [\n 'rawRequest',\n 'resource',\n 'request',\n 'userRequest',\n ];\n\n const indexValue = (value: string) => {\n const valueToIndex = cleanPath(value);\n indexes.add(valueToIndex);\n // RSpack only use \"external ...\" for external dependencies.\n // So we need to clean and add the actual name to the index too.\n if (valueToIndex.startsWith('external ')) {\n indexes.add(cleanExternalName(valueToIndex));\n }\n };\n\n // Start by indexing the identifier.\n indexValue(mod.identifier());\n\n // Then index all the other keys.\n for (const key of keysOfModuleToIndexOn) {\n const value = mod[key as keyof Module];\n if (key && key in mod && typeof value === 'string') {\n indexValue(value);\n }\n }\n\n return indexes;\n };\n\n const createIndexedModule = (mod: Module): IndexedModule => {\n const id = mod.identifier();\n return {\n identifier: () => id,\n dependencies: 'dependencies' in mod ? [...mod.dependencies] : [],\n blocks: 'blocks' in mod ? [...mod.blocks] : [],\n externalType: 'externalType' in mod ? mod.externalType : undefined,\n external: 'external' in mod ? mod.external : undefined,\n };\n };\n\n const indexModule = (mod: Module) => {\n const moduleToIndex = createIndexedModule(mod);\n const keysToIndex = getKeysToIndex(mod);\n for (const key of keysToIndex) {\n if (moduleIndex.has(key)) {\n // Update the existing module.\n const previousModule = moduleIndex.get(key)!;\n previousModule.dependencies.push(...(moduleToIndex.dependencies || []));\n previousModule.blocks.push(...(moduleToIndex.blocks || []));\n } else {\n moduleIndex.set(key, moduleToIndex);\n }\n }\n };\n\n // Aggregate all dependencies from a module.\n const getAllDependencies = (\n module: Module | Dependency | Module['blocks'][number],\n dependencies: Dependency[] = [],\n ) => {\n if ('dependencies' in module) {\n for (const dependency of module.dependencies) {\n dependencies.push(dependency);\n getAllDependencies(dependency, dependencies);\n }\n }\n\n if ('blocks' in module) {\n for (const block of module.blocks) {\n getAllDependencies(block, dependencies);\n }\n }\n\n return dependencies;\n };\n\n const getModuleFromDep = (mod: Module, dep: Dependency): IndexedModule | undefined => {\n if ('request' in dep && dep.request) {\n const cleanRequest = cleanPath(dep.request);\n if (moduleIndex.has(cleanRequest)) {\n return moduleIndex.get(cleanRequest);\n }\n if (mod.context) {\n const cleanedPath = getAbsolutePath(cleanPath(mod.context), cleanRequest);\n if (moduleIndex.has(cleanedPath)) {\n return moduleIndex.get(cleanedPath);\n }\n }\n }\n };\n\n const isExternal = (mod: Module | IndexedModule) => {\n if ('externalType' in mod && mod.externalType) {\n return true;\n }\n if ('external' in mod && mod.external) {\n return true;\n }\n if (mod.identifier?.().startsWith('external ')) {\n return true;\n }\n return false;\n };\n\n // Intercept the compilation to then get the modules.\n compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {\n clear();\n // Intercept the modules to build the dependency graph.\n compilation.hooks.finishModules.tap(\n PLUGIN_NAME,\n (finishedModules: Iterable<Module>) => {\n timeBuildReport.resume();\n const timeGraph = log.time('dependency graph');\n // First loop to create indexes.\n const timeIndex = log.time('indexing modules');\n for (const module of finishedModules) {\n indexModule(module);\n }\n timeIndex.end();\n\n // Second loop to create the dependency graph.\n const timeInputs = log.time('building inputs');\n for (const module of finishedModules) {\n const moduleIdentifier = module.identifier();\n const moduleName = cleanName(context.bundler.outDir, moduleIdentifier);\n const dependencies: Set<string> = new Set(\n getAllDependencies(module)\n .map((dep) => {\n const mod = getModuleFromDep(module, dep);\n\n // Ignore those we can't identify.\n if (!mod?.identifier()) {\n return false;\n }\n\n const identifier = mod.identifier();\n\n // Only what we support.\n if (!isModuleSupported(identifier)) {\n return false;\n }\n\n // Don't add itself as a dependency.\n if (identifier === moduleIdentifier) {\n return false;\n }\n\n return isExternal(mod)\n ? cleanExternalName(identifier)\n : identifier;\n })\n .filter(Boolean) as string[],\n );\n\n if (!isModuleSupported(moduleIdentifier)) {\n continue;\n }\n\n // Create dependents relationships.\n const moduleDeps = tempDeps.get(moduleIdentifier) || {\n dependents: new Set(),\n dependencies: new Set(),\n };\n for (const depIdentifier of dependencies) {\n const depDeps = tempDeps.get(depIdentifier) || {\n dependencies: new Set(),\n dependents: new Set(),\n };\n depDeps.dependents.add(moduleIdentifier);\n moduleDeps.dependencies.add(depIdentifier);\n tempDeps.set(depIdentifier, depDeps);\n }\n\n // Store the dependencies.\n tempDeps.set(moduleIdentifier, moduleDeps);\n\n // Store the inputs.\n const file: Input = isExternal(module)\n ? {\n size: 0,\n name: cleanExternalName(moduleName),\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: 'external',\n }\n : {\n size: module.size() || 0,\n name: moduleName,\n dependencies: new Set(),\n dependents: new Set(),\n filepath: moduleIdentifier,\n type: getType(moduleIdentifier),\n };\n\n inputs.push(file);\n reportInputsIndexed.set(moduleIdentifier, file);\n\n // If it's an external dependency, we also need to index it by its cleaned name.\n if (isExternal(module)) {\n reportInputsIndexed.set(cleanExternalName(moduleIdentifier), file);\n }\n }\n timeInputs.end();\n\n // Assign dependencies and dependents.\n const timeAssign = log.time('assigning dependencies and dependents');\n for (const input of inputs) {\n const depsReport = tempDeps.get(input.filepath);\n\n if (!depsReport) {\n log.debug(`Could not find dependency report for ${input.name}`);\n continue;\n }\n\n for (const dependency of depsReport.dependencies) {\n const depInput = reportInputsIndexed.get(dependency);\n if (!depInput) {\n log.debug(`Could not find input of dependency ${dependency}`);\n continue;\n }\n input.dependencies.add(depInput);\n }\n\n for (const dependent of depsReport.dependents) {\n const depInput = reportInputsIndexed.get(dependent);\n if (!depInput) {\n log.debug(`Could not find input of dependent ${dependent}`);\n continue;\n }\n input.dependents.add(depInput);\n }\n }\n timeAssign.end();\n timeGraph.end();\n timeBuildReport.pause();\n },\n );\n });\n\n compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async (result: Compilation) => {\n timeBuildReport.resume();\n const chunks = result.chunks;\n const assets = result.getAssets();\n\n const getChunkFiles = (chunk: Chunk) => {\n return [...(chunk.files || []), ...(chunk.auxiliaryFiles || [])].map((f: string) =>\n getAbsolutePath(context.bundler.outDir, f),\n );\n };\n\n const timeChunks = log.time('indexing chunks');\n const chunkGraph = result.chunkGraph;\n for (const chunk of chunks) {\n const files = getChunkFiles(chunk);\n\n const chunkModules =\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n (chunkGraph?.getChunkModules(chunk) || [])\n .flatMap((m) => {\n // modules exists but isn't in the types.\n return 'modules' in m && Array.isArray(m.modules)\n ? m.modules.map((m2) => m2.identifier())\n : m.identifier();\n })\n .filter(isModuleSupported);\n\n for (const file of files) {\n if (getType(file) === 'map') {\n continue;\n }\n const fileModules = modulesPerFile.get(file) || new Set();\n for (const module of chunkModules) {\n fileModules.add(module);\n }\n modulesPerFile.set(file, fileModules);\n }\n }\n timeChunks.end();\n\n // Build outputs\n const timeOutputs = log.time('building outputs');\n for (const asset of assets) {\n const file: Output = {\n size: asset.source.size() || 0,\n name: asset.name,\n inputs: [],\n filepath: getAbsolutePath(context.bundler.outDir, asset.name),\n type: getType(asset.name),\n };\n\n reportOutputsIndexed.set(file.filepath, file);\n outputs.push(file);\n\n // If it's a sourcemap, store it, we'll fill its input when we'll have\n // referenced all the outputs.\n if (file.type === 'map') {\n tempSourcemaps.push(file);\n continue;\n }\n\n // Add the inputs.\n const fileModules = modulesPerFile.get(file.filepath);\n if (!fileModules) {\n log.debug(`Could not find modules for ${file.name}`);\n continue;\n }\n\n for (const moduleIdentifier of fileModules) {\n const inputFound = reportInputsIndexed.get(moduleIdentifier);\n if (!inputFound) {\n log.debug(`Could not find input of ${moduleIdentifier}`);\n continue;\n }\n file.inputs.push(inputFound);\n }\n }\n timeOutputs.end();\n\n // Fill in inputs for sourcemaps.\n const timeSourcemaps = log.time('filling sourcemaps inputs');\n for (const sourcemap of tempSourcemaps) {\n const outputFound = reportOutputsIndexed.get(\n sourcemap.filepath.replace(/\\.map$/, ''),\n );\n\n if (!outputFound) {\n log.debug(`Output not found for sourcemap ${sourcemap.name}`);\n continue;\n }\n\n sourcemap.inputs.push(outputFound);\n }\n timeSourcemaps.end();\n\n // Build entries\n const timeEntries = log.time('building entries');\n\n // Helper to recursively get all chunks from a chunk group, including async chunks.\n const getAllChunksFromGroup = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunkGroup: any,\n visited: Set<unknown> = new Set(),\n ): Set<Chunk> => {\n if (visited.has(chunkGroup)) {\n return new Set();\n }\n visited.add(chunkGroup);\n\n const allChunks: Set<Chunk> = new Set(chunkGroup.chunks);\n\n // Recursively get chunks from child chunk groups (async chunks).\n for (const childGroup of chunkGroup.childrenIterable || []) {\n const childChunks = getAllChunksFromGroup(childGroup, visited);\n for (const chunk of childChunks) {\n allChunks.add(chunk);\n }\n }\n\n return allChunks;\n };\n\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 // Get all chunks including async chunks from child chunk groups.\n const allChunks = getAllChunksFromGroup(entrypoint);\n const entryFiles = Array.from(allChunks).flatMap(getChunkFiles);\n\n // FIXME This is not a 100% reliable way to get the entry filename.\n const entryFilename = entrypoint.chunks\n // Get the chunks that have entry modules.\n .filter(\n (chunk: Chunk) =>\n // @ts-expect-error: Reconciliating Webpack 5 and Rspack is hard.\n chunkGraph.getChunkEntryModulesIterable(chunk) || false,\n )\n // Get the files of those chunks.\n .flatMap((c) => Array.from(c.files))\n // Filter the ones that includes the entry name.\n .filter(\n (f) => f.includes(name) || (entrypoint.name && f.includes(entrypoint.name)),\n )\n // Only keep JS files.\n .find((f) => getType(f) === 'js');\n\n for (const file of entryFiles) {\n const outputFound = reportOutputsIndexed.get(file);\n if (!file || !outputFound) {\n log.debug(`Could not find output of ${JSON.stringify(file)}`);\n continue;\n }\n if (outputFound.type !== 'map' && !entryOutputs.has(outputFound.name)) {\n entryOutputs.set(outputFound.name, outputFound);\n // We know it's not a map, so we cast it.\n for (const input of outputFound.inputs as Input[]) {\n if (!entryInputs.has(input.filepath)) {\n entryInputs.set(input.filepath, input);\n }\n }\n // We don't want to include sourcemaps in the sizing.\n size += outputFound.size;\n }\n }\n\n const file: Entry = {\n name,\n filepath: entryFilename\n ? getAbsolutePath(context.bundler.outDir, entryFilename)\n : 'unknown',\n size,\n inputs: Array.from(entryInputs.values()),\n outputs: Array.from(entryOutputs.values()),\n type: entryFilename ? getType(entryFilename) : 'unknown',\n };\n entries.push(file);\n }\n timeEntries.end();\n\n // Save everything in the context.\n for (const error of result.errors) {\n context.build.errors.push(error.message);\n }\n for (const warning of result.warnings) {\n context.build.warnings.push(warning.message);\n }\n context.build.inputs = inputs;\n context.build.outputs = outputs;\n context.build.entries = entries;\n\n timeBuildReport.end();\n await context.asyncHook('buildReport', context.build);\n });\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, PluginOptions } from '@dd/core/types';\n\nimport { getEsbuildPlugin } from './esbuild';\nimport { getRollupPlugin } from './rollup';\nimport { getXpackPlugin } from './xpack';\n\nexport const PLUGIN_NAME = 'datadog-build-report-plugin';\n\nexport const getBuildReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n esbuild: getEsbuildPlugin(context, log),\n rspack: getXpackPlugin(context, PLUGIN_NAME, log),\n webpack: getXpackPlugin(context, PLUGIN_NAME, log),\n // Vite and Rollup have the same API.\n vite: getRollupPlugin(context, log) as PluginOptions['vite'],\n rollup: getRollupPlugin(context, log),\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getAbsolutePath, getNearestCommonDirectory } from '@dd/core/helpers/paths';\nimport type {\n GetInternalPlugins,\n GetPluginsArg,\n GlobalContext,\n PluginOptions,\n} from '@dd/core/types';\nimport path from 'path';\nimport type { InputOptions, OutputOptions } from 'rollup';\n\nexport const PLUGIN_NAME = 'datadog-bundler-report-plugin';\n\nexport const getAbsoluteOutDir = (buildRoot: string, outDir?: string) => {\n if (!outDir) {\n return '';\n }\n\n return path.isAbsolute(outDir) ? outDir : path.resolve(buildRoot, outDir);\n};\n\nexport const getOutDirsFromOutputs = (\n outputOptions?: OutputOptions | OutputOptions[],\n): string[] => {\n if (!outputOptions) {\n return [];\n }\n\n const normalizedOutput = Array.isArray(outputOptions) ? outputOptions : [outputOptions];\n return normalizedOutput\n .map((o) => {\n if (o.dir) {\n return o.dir;\n }\n if (o.file) {\n return path.dirname(o.file);\n }\n })\n .filter(Boolean) as string[];\n};\n\nexport const getIndirsFromInputs = (options: InputOptions) => {\n const inDirs: Set<string> = new Set();\n\n if (options.input) {\n const normalizedInput = Array.isArray(options.input)\n ? options.input\n : typeof options.input === 'object'\n ? Object.values(options.input)\n : [options.input];\n\n for (const input of normalizedInput) {\n if (typeof input !== 'string') {\n throw new Error('Invalid input type');\n }\n inDirs.add(path.dirname(input));\n }\n }\n\n return Array.from(inDirs);\n};\n\nconst xpackPlugin: (context: GlobalContext) => PluginOptions['webpack'] & PluginOptions['rspack'] =\n (context) => (compiler) => {\n context.bundler.rawConfig = compiler.options;\n\n if (compiler.options.output?.path) {\n // While webpack doesn't allow for non-absolute paths,\n // rspack does, and will fallback to use process.cwd().\n context.bundler.outDir = getAbsoluteOutDir(process.cwd(), compiler.options.output.path);\n }\n context.hook('bundlerReport', context.bundler);\n\n if (compiler.options.context) {\n context.buildRoot = compiler.options.context;\n }\n context.hook('buildRoot', context.buildRoot);\n };\n\nconst vitePlugin = (context: GlobalContext): PluginOptions['vite'] => {\n return {\n configResolved(config) {\n context.bundler.rawConfig = config;\n // If we have the outDir configuration from Vite.\n let outDir = config.build?.outDir ?? 'dist';\n // We need to know if we have a rollup output configuration.\n // As it will override Vite's outDir and root.\n const output = config.build?.rollupOptions?.output as\n | OutputOptions\n | OutputOptions[]\n | undefined;\n\n const outDirs = getOutDirsFromOutputs(output);\n\n // Vite will fallback to process.cwd() if no root is provided.\n context.buildRoot = config.root ?? process.cwd();\n // Vite will fallback to process.cwd() if we have an output configuration with dirs.\n if (output && outDirs.length) {\n // Now compute the nearest common directory from the output directories.\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Make sure the outDir is absolute.\n context.bundler.outDir = getAbsoluteOutDir(context.buildRoot, outDir);\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n },\n };\n};\n\n// TODO: Add universal config report with list of plugins (names), loaders.\nexport const getBundlerReportPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const bundlerReportPlugin: PluginOptions = {\n name: PLUGIN_NAME,\n enforce: 'pre',\n esbuild: {\n setup(build) {\n context.bundler.rawConfig = build.initialOptions;\n\n if (build.initialOptions.absWorkingDir) {\n context.buildRoot = build.initialOptions.absWorkingDir;\n }\n\n if (build.initialOptions.outdir) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n build.initialOptions.outdir,\n );\n }\n\n if (build.initialOptions.outfile) {\n context.bundler.outDir = getAbsoluteOutDir(\n context.buildRoot,\n path.dirname(build.initialOptions.outfile),\n );\n }\n\n context.hook('buildRoot', context.buildRoot);\n context.hook('bundlerReport', context.bundler);\n\n // We force esbuild to produce its metafile.\n build.initialOptions.metafile = true;\n },\n },\n webpack: xpackPlugin(context),\n rspack: xpackPlugin(context),\n vite: vitePlugin(context),\n rollup: {\n options(options) {\n // By default, with relative paths, rollup will use process.cwd() as the CWD.\n let outDir;\n if ('output' in options) {\n const outDirs = getOutDirsFromOutputs(\n options.output as OutputOptions | OutputOptions[],\n );\n outDir = getNearestCommonDirectory(outDirs, process.cwd());\n }\n\n // Compute input directories if possible.\n const inDirs = getIndirsFromInputs(options);\n\n if (outDir) {\n context.bundler.outDir = getAbsolutePath(process.cwd(), outDir);\n const computedCwd = getNearestCommonDirectory(\n [outDir, ...inDirs],\n process.cwd(),\n );\n // If the computed CWD is the root directory, it means we could not compute it,\n // so we fallback to process.cwd().\n context.buildRoot = computedCwd === path.sep ? process.cwd() : computedCwd;\n } else {\n // Fallback to process.cwd()/dist as it is rollup's default.\n context.buildRoot = getNearestCommonDirectory(inDirs, process.cwd());\n context.bundler.outDir = path.resolve(process.cwd(), 'dist');\n }\n\n context.hook('buildRoot', context.buildRoot);\n },\n buildStart(options) {\n // Save the resolved options.\n context.bundler.rawConfig = options;\n },\n renderStart(outputOptions) {\n // Save the resolved options.\n context.bundler.rawConfig.outputs = context.bundler.rawConfig.outputs || [];\n context.bundler.rawConfig.outputs.push(outputOptions);\n context.hook('bundlerReport', context.bundler);\n\n // Verify that the output directory is the same as the one computed in the options hook.\n const outDirs = getOutDirsFromOutputs(outputOptions);\n // Rollup always uses process.cwd() as the CWD.\n const outDir = getNearestCommonDirectory(outDirs, process.cwd());\n if (!outDir.startsWith(context.bundler.outDir)) {\n log.warn(\n 'The output directory has been changed by a plugin and may introduce some inconsistencies in the build report.',\n );\n }\n },\n },\n };\n\n return [bundlerReportPlugin];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { PluginName } from '@dd/core/types';\n\nexport const PLUGIN_NAME: PluginName = 'datadog-custom-hooks-plugin' as const;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport type { GetInternalPlugins, GetPluginsArg, TriggerHook } from '@dd/core/types';\n\nimport { PLUGIN_NAME } from './constants';\n\nexport { PLUGIN_NAME } from './constants';\n\nexport const getCustomHooksPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { context } = arg;\n const log = context.getLogger(PLUGIN_NAME);\n\n const executeHooks =\n (async: boolean): TriggerHook<Promise<void[]> | void> =>\n (hookName, ...hookArgs) => {\n const timeHook = log.time(`execution | ${hookName}`, {\n tags: ['type:custom-hook', `hook:${hookName}`],\n });\n const errors: string[] = [];\n const proms: Promise<void>[] = [];\n\n for (const plugin of context.plugins) {\n if (!(hookName in plugin)) {\n continue;\n }\n\n const hookFn = plugin[hookName];\n if (typeof hookFn !== 'function') {\n errors.push(\n `Plugin \"${plugin.name}\" has an invalid hook type for \"${hookName}\". [${typeof hookFn}]`,\n );\n continue;\n }\n\n try {\n // Re-typing to take over typechecking.\n const result: any = hookFn(...(hookArgs as any[]));\n\n if (result instanceof Promise) {\n // Confirm that the result is not an unsupported Promise.\n if (!async) {\n errors.push(\n `Plugin \"${plugin.name}\" returned a promise on the non async hook \"${hookName}\".`,\n );\n }\n proms.push(result);\n }\n } catch (e) {\n errors.push(`Plugin \"${plugin.name}\" errored on hook \"${hookName}\". [${e}]`);\n }\n }\n\n if (errors.length > 0) {\n for (const error of errors) {\n log.error(error);\n }\n throw new Error(`Some plugins errored during the hook execution.`);\n }\n\n return Promise.all(proms).finally(() => timeHook.end());\n };\n\n // Define the hook functions.\n context.hook = executeHooks(false);\n // Define the asyncHook functions.\n context.asyncHook = executeHooks(true) as TriggerHook<Promise<void[]>>;\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { readFileSync } from '@dd/core/helpers/fs';\n\n// TrackedFilesMatcher can compute the list of tracked files related to a particular sourcemap.\n// The current implementation simply returns all tracked files whose filename is found inside\n// the sourcemap 'sources' field.\n// It is used so that we don't send every tracked files to the backend since most won't be of any use\n// for a particular sourcemap.\nexport class TrackedFilesMatcher {\n // A map with tracked filenames as key and the related tracked file paths as value.\n private trackedFilenames: Map<string, string[]>;\n\n constructor(trackedFiles: string[]) {\n this.trackedFilenames = new Map<string, string[]>();\n for (const f of trackedFiles) {\n const filename = this.getFilename(f);\n const list = this.trackedFilenames.get(filename);\n if (list) {\n list.push(f);\n } else {\n this.trackedFilenames.set(filename, new Array<string>(f));\n }\n }\n }\n\n private displaySource(src: string) {\n if (src.length <= 40) {\n return src;\n }\n return `[...]${src.slice(-35)}`;\n }\n\n // Looks up the sources declared in the sourcemap and return a list of related tracked files.\n public matchSourcemap(\n srcmapPath: string,\n onSourcesNotFound: (reason: string) => void,\n ): string[] | undefined {\n const buff = readFileSync(srcmapPath);\n const srcmapObj = JSON.parse(buff);\n if (!srcmapObj.sources) {\n onSourcesNotFound(`Missing 'sources' field in sourcemap.`);\n return undefined;\n }\n const sources = srcmapObj.sources as string[];\n if (sources.length === 0) {\n onSourcesNotFound(`Empty 'sources' field in sourcemap.`);\n return undefined;\n }\n const filtered = this.matchSources(sources);\n if (filtered.length === 0) {\n onSourcesNotFound(\n `${sources.map(this.displaySource).join(', ')} not in the tracked files.`,\n );\n return undefined;\n }\n\n return filtered;\n }\n\n public matchSources(sources: string[]): string[] {\n let filtered: string[] = [];\n const filenameAlreadyMatched = new Set<string>();\n for (const source of sources) {\n const filename = this.getFilename(source);\n if (filenameAlreadyMatched.has(filename)) {\n continue;\n }\n filenameAlreadyMatched.add(filename);\n const trackedFiles = this.trackedFilenames.get(filename);\n if (trackedFiles) {\n filtered = filtered.concat(trackedFiles);\n }\n }\n\n return filtered;\n }\n\n // Return a list of all tracked files\n public rawTrackedFilesList() {\n let rawList: string[] = [];\n this.trackedFilenames.forEach((value) => {\n rawList = rawList.concat(value);\n });\n\n return rawList;\n }\n\n // Extract the filename from a path.\n //\n // We are removing any suffix that is after the character '?'. The only reason this is done\n // is because we noticed that a non-negligible (~5%) amount of source paths from our customers\n // source maps contained query parameters.\n // We are assuming that the files may not actually be named with the interrogation mark but that\n // it is only an artifact of the build process. The query parameters look random. It looks\n // like it may be used as a trick to force a web browser to reload the file content.\n // The only side effect of doing that operation is that more tracked files paths may be sent\n // alongside the sourcemap which is not a problem.\n // Example: webpack:///./src/folder/ui/select.vue?821e\n private getFilename(s: string): string {\n let start = s.lastIndexOf('/');\n if (start === -1) {\n start = 0;\n } else {\n start++;\n }\n let end = s.lastIndexOf('?');\n if (end === -1 || end <= start) {\n end = s.length;\n }\n\n return s.substring(start, end);\n }\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { filterSensitiveInfoFromRepositoryUrl } from '@dd/core/helpers/strings';\nimport type { RepositoryData } from '@dd/core/types';\nimport type { SimpleGit, BranchSummary } from 'simple-git';\nimport { simpleGit } from 'simple-git';\n\nimport { TrackedFilesMatcher } from './trackedFilesMatcher';\n\n// Returns a configured SimpleGit.\nexport const newSimpleGit = async (cwd?: string): Promise<SimpleGit> => {\n const options = {\n baseDir: cwd || process.cwd(),\n binary: 'git',\n // We are invoking at most 3 git commands at the same time.\n maxConcurrentProcesses: 3,\n };\n try {\n // Attempt to set the baseDir to the root of the repository so the 'git ls-files' command\n // returns the tracked files paths relative to the root of the repository.\n const git = simpleGit(options);\n const root = await git.revparse('--show-toplevel');\n options.baseDir = root;\n } catch {\n // Ignore exception as it will fail if we are not inside a git repository.\n }\n\n return simpleGit(options);\n};\n\n// Returns the remote of the current repository.\nexport const gitRemote = async (git: SimpleGit): Promise<string> => {\n const remotes = await git.getRemotes(true);\n if (remotes.length === 0) {\n throw new Error('No git remotes available');\n }\n const defaultRemote = await getDefaultRemoteName(git);\n\n for (const remote of remotes) {\n if (remote.name === defaultRemote) {\n return filterSensitiveInfoFromRepositoryUrl(remote.refs.push);\n }\n }\n\n // Falling back to picking the first remote in the list if the default remote is not found.\n return filterSensitiveInfoFromRepositoryUrl(remotes[0].refs.push);\n};\n\nexport const getDefaultRemoteName = async (git: SimpleGit): Promise<string> => {\n try {\n return (await git.getConfig('clone.defaultRemoteName'))?.value ?? 'origin';\n } catch (e) {\n return 'origin';\n }\n};\n\n// Returns the hash of the current repository.\nexport const gitHash = async (git: SimpleGit): Promise<string> => git.revparse('HEAD');\n\n// Returns the tracked files of the current repository.\nexport const gitTrackedFiles = async (git: SimpleGit): Promise<string[]> => {\n const files = await git.raw('ls-files');\n\n return files.split(/\\r\\n|\\r|\\n/);\n};\n\nexport const gitBranch = async (git: SimpleGit): Promise<BranchSummary> => git.branch();\n\nexport const gitMessage = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%s']);\n\nexport const gitAuthorAndCommitter = async (git: SimpleGit): Promise<string> =>\n git.show(['-s', '--format=%an,%ae,%aI,%cn,%ce,%cI']);\n\nexport const gitRepositoryURL = async (git: SimpleGit): Promise<string> =>\n git.listRemote(['--get-url']);\n\n// Returns the current hash and remote as well as a TrackedFilesMatcher.\n//\n// To obtain the list of tracked files paths tied to a specific sourcemap, invoke the 'matchSourcemap' method.\nexport const getRepositoryData = async (\n git: SimpleGit,\n repositoryUrl?: string,\n): Promise<RepositoryData> => {\n const remoteOverride = repositoryUrl?.trim();\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 remoteOverride\n ? Promise.resolve(filterSensitiveInfoFromRepositoryUrl(remoteOverride))\n : gitRemote(git),\n ];\n\n const [hash, branch, message, authorAndCommitter, trackedFiles, remote] =\n await Promise.all(proms);\n\n const [authorName, authorEmail, authorDate, committerName, committerEmail, committerDate] =\n authorAndCommitter.split(',').map((item) => item.trim());\n\n const data: RepositoryData = {\n commit: {\n author: {\n name: authorName,\n email: authorEmail,\n date: authorDate,\n },\n committer: {\n name: committerName,\n email: committerEmail,\n date: committerDate,\n },\n message: message.trim(),\n hash,\n },\n hash,\n branch: branch.current,\n remote: remote.trim(),\n trackedFilesMatcher: new TrackedFilesMatcher(trackedFiles),\n };\n\n return data;\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getClosest } from '@dd/core/helpers/paths';\nimport { shouldGetGitInfo } from '@dd/core/helpers/plugins';\nimport type { GetInternalPlugins, GetPluginsArg } from '@dd/core/types';\nimport path from 'path';\n\nimport { getRepositoryData, newSimpleGit } from './helpers';\n\nexport const PLUGIN_NAME = 'datadog-git-plugin';\n\nexport const getGitPlugins: GetInternalPlugins = (arg: GetPluginsArg) => {\n const { options, context } = arg;\n const repositoryUrl = options.gitRepositoryUrl?.trim();\n const log = context.getLogger(PLUGIN_NAME);\n const timeGit = log.time('get git information', { start: false });\n const processGit = async (gitDir: string) => {\n try {\n const git = await newSimpleGit(path.dirname(gitDir));\n if (!repositoryUrl && (await git.getRemotes(true)).length === 0) {\n log.warn(\n 'No git remotes available, skipping git plugin. ' +\n 'This is expected for a repository that has not been pushed yet.',\n );\n timeGit.end();\n return;\n }\n\n const repositoryData = await getRepositoryData(git, repositoryUrl);\n context.git = repositoryData;\n\n timeGit.end();\n await context.asyncHook('git', context.git);\n } catch (e: any) {\n log.error(`Could not get git information: ${e.message}`);\n }\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'pre',\n buildRoot(buildRoot) {\n if (!shouldGetGitInfo(options)) {\n return;\n }\n\n try {\n timeGit.resume();\n // Add git information to the context.\n const gitDir = getClosest(buildRoot, '.git');\n if (!gitDir) {\n log.warn('No .git directory found, skipping git plugin.');\n timeGit.end();\n return;\n }\n\n // buildRoot hook is sync because xpack can't make it async.\n // So we queue the async part of the plugin.\n context.queue(processGit(gitDir));\n } catch (e: any) {\n // We don't want to have the build fail for this.\n log.error(`Could not get git information: ${e.message}`);\n }\n },\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nexport const PLUGIN_NAME = 'datadog-injection-plugin';\nexport const DISTANT_FILE_RX = /^https?:\\/\\//;\nexport const BEFORE_INJECTION = `// begin injection by Datadog build plugins`;\nexport const AFTER_INJECTION = `// end injection by Datadog build plugins`;\nexport const SUPPORTED_EXTENSIONS = ['.mjs', '.mjsx', '.js', '.ts', '.tsx', '.jsx'];\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 { ChunkInfo, Logger, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport chalk from 'chalk';\n\nimport {\n AFTER_INJECTION,\n BEFORE_INJECTION,\n DISTANT_FILE_RX,\n SUPPORTED_EXTENSIONS,\n} from './constants';\nimport type { ContentsToInject, ContentToInject } from './types';\n\nconst yellow = chalk.bold.yellow;\n\nconst MAX_TIMEOUT_IN_MS = 5000;\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 function hasBeforeAfterInjection(contentsToInject: ContentToInject[]) {\n return contentsToInject.some(\n (content) =>\n content.position === InjectPosition.BEFORE || content.position === InjectPosition.AFTER,\n );\n}\n\nexport function hasChunkInjection(contentsToInject: ContentToInject[]) {\n return contentsToInject.some((content) => content.injectIntoAllChunks);\n}\n\nexport const getContentToInject = (\n contentToInject: ContentToInject[],\n position: InjectPosition,\n chunk?: ChunkInfo,\n) => {\n const filtered = contentToInject.filter((content) => {\n return (\n content.position === position &&\n (!chunk || chunk.isEntry || content.injectIntoAllChunks)\n );\n });\n\n // Resolve function-valued content against the current chunk, drop empties.\n const values = filtered\n .map((content) => (isFunction(content.value) ? content.value(chunk!) : content.value))\n .filter(Boolean);\n\n if (values.length === 0) {\n return '';\n }\n\n const stringToInject = values\n // Wrapping it in order to avoid variable name collisions.\n .map((value) => `(() => {${value}})();`)\n .join('\\n\\n');\n return `${BEFORE_INJECTION}\\n${stringToInject}\\n${AFTER_INJECTION}`;\n};\n\nexport const resolveWithFallback = async (\n item: ToInjectItem,\n log: Logger,\n cwd: string = process.cwd(),\n): Promise<string> => {\n const value = isFunction(item.value) ? await item.value() : item.value;\n\n try {\n if (item.type === 'file') {\n const filePath = value;\n return await (filePath.match(DISTANT_FILE_RX)\n ? processDistantFile(filePath)\n : processLocalFile(filePath, cwd));\n }\n return value;\n } catch (error: any) {\n const itemId = `${item.type} - ${truncateString(value)}`;\n if (item.fallback) {\n log.debug(`Fallback for \"${itemId}\": ${error.toString()}`);\n return resolveWithFallback(item.fallback, log, cwd);\n }\n log.warn(`Failed \"${itemId}\": ${error.toString()}`);\n return '';\n }\n};\nexport const prepareInjections = async (\n log: Logger,\n toInject: ToInjectItem[],\n contentsToInject: ContentsToInject,\n cwd: string = process.cwd(),\n) => {\n // Per-chunk functions receive the full ChunkInfo for the chunk they're injected into.\n const dynamicPerChunk = toInject.filter(isPerChunk).map((item) => {\n const userFn = item.value as (chunk?: ChunkInfo) => string;\n return { ...item, value: (chunk: ChunkInfo) => userFn(chunk) };\n });\n\n // Static items (strings and async loaders) are resolved once per build.\n const staticInject = toInject.filter((item) => !isPerChunk(item));\n const resolvedStaticInject = await Promise.all(\n staticInject.map(async (item) => ({\n ...item,\n value: await resolveWithFallback(item, log, cwd),\n })),\n );\n\n const normalize = <T extends { position?: InjectPosition }>(item: T) => ({\n ...item,\n position: item.position ?? InjectPosition.BEFORE,\n });\n contentsToInject.push(\n ...dynamicPerChunk.map(normalize),\n ...resolvedStaticInject.map(normalize),\n );\n};\n\nexport interface NodeSystemError extends Error {\n code: string;\n}\n\nexport const isNodeSystemError = (e: unknown): e is NodeSystemError => {\n return e instanceof Error && 'code' in e;\n};\n\nexport const isFileSupported = (ext: string): boolean => {\n return SUPPORTED_EXTENSIONS.includes(ext);\n};\n\nexport const warnUnsupportedFile = (log: Logger, ext: string, filename: string): void => {\n log.warn(`\"${yellow(ext)}\" files are not supported (${yellow(filename)}).`);\n};\n\nconst isPerChunk = (\n item: ToInjectItem,\n): item is ToInjectItem & { value: (chunk: ChunkInfo) => string } =>\n typeof item.value === 'function' && item.value.length === 1;\n\nconst isFunction = (value: any): value is Function => typeof value === 'function';\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { getEsbuildEntries } from '@dd/core/helpers/bundlers';\nimport { outputFile } from '@dd/core/helpers/fs';\nimport { getAbsolutePath } from '@dd/core/helpers/paths';\nimport type { Logger, PluginOptions, GlobalContext, ResolvedEntry } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport {\n getContentToInject,\n hasChunkInjection,\n isNodeSystemError,\n isFileSupported,\n warnUnsupportedFile,\n hasBeforeAfterInjection,\n} from './helpers';\nimport type { ContentsToInject } from './types';\n\nconst fsp = fs.promises;\n\nexport const getEsbuildPlugin = (\n log: Logger,\n context: GlobalContext,\n contentsToInject: ContentsToInject,\n): PluginOptions['esbuild'] => ({\n setup(build) {\n const { onStart, onResolve, onLoad, onEnd, esbuild, initialOptions } = build;\n const entries: ResolvedEntry[] = [];\n // Use a narrower identifier to avoid cross build collisions.\n const id = context.bundler.name;\n const filePath = `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`;\n const tmpDir = fs.realpathSync(os.tmpdir());\n const absoluteFilePath = path.resolve(tmpDir, filePath);\n const injectionRx = new RegExp(`${filePath}$`);\n\n // InjectPosition.MIDDLE\n // Inject the file in the build using the \"inject\" option.\n // NOTE: This is made \"safer\" for sub-builds by actually creating the file.\n const initialInject = initialOptions.inject;\n initialOptions.inject = initialInject ? [...initialInject] : [];\n initialOptions.inject.push(absoluteFilePath);\n\n onStart(async () => {\n // Get all the entry points for later reference.\n entries.push(...(await getEsbuildEntries(build, context, log)));\n\n // Remove our injected file from the config, so we reduce our chances to leak our changes.\n build.initialOptions.inject = initialInject;\n\n try {\n // Create the MIDDLE file because esbuild will crash if it doesn't exist.\n // It seems to load entries outside of the onLoad hook once.\n await outputFile(absoluteFilePath, '');\n } catch (e: any) {\n log.error(`Could not create the files: ${e.message}`);\n }\n });\n\n onResolve(\n {\n filter: injectionRx,\n },\n async (args) => {\n // Mark the file as being injected by us.\n return { path: args.path, namespace: PLUGIN_NAME };\n },\n );\n\n onLoad(\n {\n filter: injectionRx,\n namespace: PLUGIN_NAME,\n },\n async () => {\n const content = getContentToInject(contentsToInject, InjectPosition.MIDDLE);\n\n return {\n // We can't use an empty string otherwise esbuild will crash.\n contents: content || ' ',\n // Resolve the imports from the project's root.\n resolveDir: context.buildRoot,\n loader: 'js',\n };\n },\n );\n\n // InjectPosition.START and InjectPosition.END\n onEnd(async (result) => {\n if (!result.metafile) {\n const error = new Error('Missing metafile from build result.');\n log.warn(error.message);\n context.markArtifactsReady(error);\n return;\n }\n\n if (!hasBeforeAfterInjection(contentsToInject)) {\n return;\n }\n\n try {\n const proms: Promise<void>[] = [];\n\n // Process all output files\n for (const [p, o] of Object.entries(result.metafile.outputs)) {\n // Determine if this is an entry point\n const isEntry = Boolean(\n o.entryPoint && entries.some((e) => e.resolved.endsWith(o.entryPoint!)),\n );\n\n if (!isEntry && !hasChunkInjection(contentsToInject)) {\n continue;\n }\n\n const absolutePath = getAbsolutePath(context.buildRoot, p);\n const { base, ext } = path.parse(absolutePath);\n\n // Check if file type is supported\n if (!isFileSupported(ext)) {\n warnUnsupportedFile(log, ext, base);\n continue;\n }\n\n // Inject content\n proms.push(\n (async () => {\n try {\n const mapPath = `${absolutePath}.map`;\n const sourceOrHash = await fsp.readFile(absolutePath, 'utf-8');\n const sourcemap = await fsp\n .readFile(mapPath, 'utf-8')\n .catch(() => false as const);\n const fileName = path.basename(absolutePath);\n // Resolve static and per-chunk content in one pass.\n const banner = getContentToInject(\n contentsToInject,\n InjectPosition.BEFORE,\n { sourceOrHash, fileName, isEntry },\n );\n const footer = getContentToInject(\n contentsToInject,\n InjectPosition.AFTER,\n { sourceOrHash, fileName, isEntry },\n );\n\n if (!banner && !footer) {\n return;\n }\n\n // Strip existing sourceMappingURL and inline the map so esbuild chains it.\n const cleaned = sourceOrHash.replace(\n /\\n?\\/\\/# sourceMappingURL=.*$/m,\n '',\n );\n const input = sourcemap\n ? `${cleaned}\\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(sourcemap!).toString('base64')}`\n : cleaned;\n\n const data = await esbuild.transform(input, {\n loader: 'default',\n banner,\n footer,\n sourcemap: sourcemap ? 'external' : undefined,\n sourcefile: fileName,\n });\n\n await Promise.all([\n fsp.writeFile(absolutePath, data.code),\n sourcemap && data.map ? fsp.writeFile(mapPath, data.map) : null,\n ]);\n } catch (e) {\n if (isNodeSystemError(e) && e.code === 'ENOENT') {\n // When we are using sub-builds, the entry file of sub-builds may not exist\n // Hence we should skip the file injection in this case.\n log.warn(`Could not inject content in ${absolutePath}: ${e}`);\n } else {\n throw e;\n }\n }\n })(),\n );\n }\n\n await Promise.all(proms);\n context.markArtifactsReady();\n } catch (error) {\n context.markArtifactsReady(error);\n throw error;\n }\n });\n },\n});\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { isInjectionFile } from '@dd/core/helpers/plugins';\nimport type { Logger, PluginOptions } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport MagicString from 'magic-string';\nimport path from 'path';\nimport type { RenderedChunk } from 'rollup';\n\nimport { getContentToInject, isFileSupported, warnUnsupportedFile } 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 = (\n log: Logger,\n contentsToInject: ContentsToInject,\n): PluginOptions['rollup'] => {\n return {\n renderChunk: {\n // Keep BEFORE and AFTER injections in their requested positions even when another\n // plugin, such as Terser, transforms or reorders the chunk.\n order: 'post',\n handler(code, chunk: RenderedChunk) {\n const { base, ext } = path.parse(chunk.fileName);\n if (!isFileSupported(ext)) {\n warnUnsupportedFile(log, ext, base);\n return null;\n }\n\n const banner = getContentToInject(contentsToInject, InjectPosition.BEFORE, {\n sourceOrHash: code,\n fileName: chunk.fileName,\n isEntry: chunk.isEntry,\n });\n const footer = getContentToInject(contentsToInject, InjectPosition.AFTER, {\n sourceOrHash: code,\n fileName: chunk.fileName,\n isEntry: chunk.isEntry,\n });\n\n if (!banner && !footer) {\n return null;\n }\n\n const s = new MagicString(code);\n\n if (banner) {\n s.prepend(`${banner}\\n`);\n }\n if (footer) {\n s.append(`\\n${footer}`);\n }\n\n return {\n code: s.toString(),\n map: s.generateMap({ file: chunk.fileName, hires: 'boundary' }),\n };\n },\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 // Skip HTML entries - Vite handles these specially via transformIndexHtml\n // The proxy mechanism breaks Vite's HTML->module tracking\n if (source.endsWith('.html')) {\n return null;\n }\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 };\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE } from '@dd/core/constants';\nimport { outputFileSync, rmSync } from '@dd/core/helpers/fs';\nimport type { GlobalContext, Logger, PluginOptions, ToInjectItem } from '@dd/core/types';\nimport { InjectPosition } from '@dd/core/types';\nimport path from 'path';\n\nimport { PLUGIN_NAME } from './constants';\nimport {\n getContentToInject,\n prepareInjections,\n isFileSupported,\n warnUnsupportedFile,\n} from './helpers';\nimport type { ContentsToInject } from './types';\n\nexport const getXpackPlugin =\n (\n bundler: any,\n log: Logger,\n context: GlobalContext,\n toInject: ToInjectItem[],\n contentsToInject: ContentsToInject,\n ): PluginOptions['rspack'] & PluginOptions['webpack'] =>\n (compiler) => {\n const cache = new WeakMap();\n // Use a narrower identifier to avoid cross build collisions.\n const ConcatSource = bundler.sources.ConcatSource;\n const id = context.bundler.name;\n // Use a cache directory within the project root instead of outDir,\n // so that webpack's output.clean option doesn't delete the file\n // before it can be resolved as an entry point.\n // https://github.com/DataDog/build-plugins/issues/304\n const filePath = path.resolve(\n context.buildRoot,\n 'node_modules',\n '.cache',\n 'datadog-build-plugins',\n `${id}.${InjectPosition.MIDDLE}.${INJECTED_FILE}.js`,\n );\n\n // NOTE: RSpack MAY try to resolve the entry points before the loader is ready.\n // There must be some race condition around this, because it's not always failing.\n outputFileSync(filePath, '');\n // WARNING: Can't use shutdown.tapPromise as rspack would randomly crash the process.\n // Seems to be fixed in rspack@1.2.*\n // We also do it for webpack, as it fixes some resolution edge cases.\n const hookFn = () => {\n // Delete the file we created.\n rmSync(filePath);\n };\n compiler.hooks.shutdown.tap(PLUGIN_NAME, hookFn);\n\n // Handle the InjectPosition.MIDDLE.\n type Entry = typeof compiler.options.entry;\n // TODO: Move this into @dd/core, add rspack/webpack types and tests.\n const injectEntry = (initialEntry: Entry): Entry => {\n const injectedEntry = {\n import: [filePath],\n };\n\n const objectInjection = (entry: Entry) => {\n for (const [entryKey, entryValue] of Object.entries(entry)) {\n if (typeof entryValue === 'object') {\n entryValue.import = entryValue.import || [];\n entryValue.import.unshift(filePath);\n } else if (typeof entryValue === 'string') {\n // @ts-expect-error - Badly typed for strings.\n entry[entryKey] = [filePath, entryValue];\n } else if (Array.isArray(entryValue)) {\n entryValue.unshift(filePath);\n } else {\n log.error(`Invalid entry type: ${typeof entryValue}`);\n }\n }\n };\n\n if (!initialEntry) {\n return {\n ddHelper: injectedEntry,\n };\n } else if (typeof initialEntry === 'function') {\n // @ts-expect-error - This is webpack / rspack typing conflict.\n return async () => {\n const originEntry = await initialEntry();\n objectInjection(originEntry);\n return originEntry;\n };\n } else if (typeof initialEntry === 'object') {\n objectInjection(initialEntry);\n } else if (typeof initialEntry === 'string') {\n // @ts-expect-error - Badly typed for strings.\n return [injectedEntry, initialEntry];\n } else {\n log.error(`Invalid entry type: ${typeof initialEntry}`);\n return initialEntry;\n }\n return initialEntry;\n };\n\n // We need to prepare the injections before the build starts.\n // Otherwise they'll be empty once resolved.\n const setupInjections = async () => {\n // Prepare the injections.\n await prepareInjections(log, toInject, contentsToInject, context.buildRoot);\n };\n\n // For one-time builds (production mode)\n compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, setupInjections);\n\n // For watch mode / dev server (webpack dev mode)\n compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, setupInjections);\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 for (const chunk of compilation.chunks) {\n const isEntry = chunk.canBeInitial();\n // Per-chunk content (e.g. context snippets) keys off the chunk\n // content hash, the only chunk source available at this stage.\n const chunkSource = chunk.contentHash?.javascript ?? chunk.hash;\n\n for (const file of chunk.files) {\n const { base, ext } = path.parse(file);\n const isOutputSupported = isFileSupported(ext);\n if (!isOutputSupported) {\n warnUnsupportedFile(log, ext, base);\n continue;\n }\n\n const fileName = base;\n // Resolve static and per-chunk content in one pass.\n const banner = getContentToInject(contentsToInject, InjectPosition.BEFORE, {\n sourceOrHash: chunkSource,\n fileName,\n isEntry,\n });\n const footer = getContentToInject(contentsToInject, InjectPosition.AFTER, {\n sourceOrHash: chunkSource,\n fileName,\n isEntry,\n });\n\n if (banner === '' && footer === '') {\n continue;\n }\n\n compilation.updateAsset(file, (old) => {\n const cached = cache.get(old);\n\n // If anything changed, we need to re-create the source.\n if (!cached || cached.banner !== banner || cached.footer !== footer) {\n const source = new ConcatSource(banner, '\\n', old, '\\n', footer);\n\n // Cache the result.\n cache.set(old, { source, banner, footer });\n return source;\n }\n\n return cached.source;\n });\n }\n }\n };\n\n const stage = bundler.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;\n compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage }, hookCb);\n });\n\n // We inject the new entry.\n const newEntry = injectEntry(compiler.options.entry);\n compiler.options.entry = newEntry;\n };\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { INJECTED_FILE_RX } from '@dd/core/constants';\nimport { isXpack } from '@dd/core/helpers/bundlers';\nimport {\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 { prepareInjections, getContentToInject, hasBeforeAfterInjection } 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: ToInjectItem[] = [];\n\n // Storage for all the positional contents we want to inject.\n const contentsToInject: ContentsToInject = [];\n\n context.inject = (item: ToInjectItem) => {\n injections.push(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(log, contentsToInject),\n vite: {\n ...(getRollupPlugin(log, contentsToInject) as PluginOptions['vite']),\n enforce: 'pre',\n transformIndexHtml: {\n order: 'pre',\n handler() {\n // For Vite, we inject MIDDLE content by adding a script tag\n // that references the virtual injected file\n const middleContent = getContentToInject(\n contentsToInject,\n InjectPosition.MIDDLE,\n );\n if (middleContent) {\n // Return a tag descriptor instead of modifying HTML directly\n return [\n {\n tag: 'script',\n attrs: {\n type: 'module',\n src: `/@id/__datadog-helper-file`,\n },\n injectTo: 'head-prepend',\n },\n ];\n }\n return [];\n },\n },\n },\n };\n\n // We need to handle the resolution in xpack,\n // and it's easier to use unplugin's hooks for it.\n if (isXpack(context.bundler.name)) {\n plugin.load = {\n filter: {\n id: INJECTED_FILE_RX,\n },\n handler() {\n return {\n code: getContentToInject(contentsToInject, InjectPosition.MIDDLE),\n };\n },\n };\n } else {\n // In xpack, we need to prepare the injections BEFORE the build starts.\n // Otherwise, the bundler doesn't have the content when it needs it.\n // So we do it in their specific plugin.\n // Here for all the other non-xpack bundlers.\n plugin.buildStart = async () => {\n // Prepare the injections.\n await prepareInjections(log, injections, contentsToInject, context.buildRoot);\n\n if (context.bundler.name === 'esbuild' && hasBeforeAfterInjection(contentsToInject)) {\n context.markArtifactsPending();\n }\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 // TODO: Reconsider the lifecycle names around trueEnd and flush together.\n // Having a final hook after \"trueEnd\" is confusing, so these likely need a broader rename.\n const asyncHookFn = async () => {\n await context.asyncHook('asyncTrueEnd');\n };\n const flushHookFn = async () => {\n await context.asyncHook('flush');\n };\n const syncHookFn = () => {\n context.hook('syncTrueEnd');\n };\n const bothHookFns = async () => {\n syncHookFn();\n await asyncHookFn();\n await flushHookFn();\n };\n\n const xpackPlugin: PluginOptions['rspack'] & PluginOptions['webpack'] = (compiler) => {\n // NOTE: rspack prior to 1.2.* will randomly crash on shutdown.tapPromise.\n compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, bothHookFns);\n };\n\n const rollupPlugin: PluginOptions['rollup'] & PluginOptions['vite'] = {\n async writeBundle() {\n // TODO: Need to fallback here in case the closeBundle isn't called.\n },\n async closeBundle() {\n await bothHookFns();\n },\n };\n\n return [\n {\n name: PLUGIN_NAME,\n enforce: 'post',\n webpack: xpackPlugin,\n esbuild: {\n setup(build) {\n // NOTE: \"onEnd\" is the best we can do for esbuild, but it's very far from being the \"true end\" of the build.\n build.onEnd(async () => {\n await asyncHookFn();\n await flushHookFn();\n });\n // NOTE: \"onDispose\" is strictly synchronous.\n build.onDispose(() => {\n syncHookFn();\n });\n },\n },\n vite: rollupPlugin,\n rollup: rollupPlugin,\n rspack: xpackPlugin,\n },\n ];\n};\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\n/* eslint-disable arca/import-ordering, arca/newline-after-import-section */\n// This file is mostly generated.\n// Anything between\n// - #imports-injection-marker\n// - #types-export-injection-marker\n// - #internal-plugins-injection-marker\n// - #helpers-injection-marker\n// - #configs-injection-marker\n// will be updated using the 'yarn cli integrity' command.\n\nimport type {\n BundlerName,\n Env,\n FactoryMeta,\n GetCustomPlugins,\n GetInternalPlugins,\n GetPlugins,\n GlobalContext,\n GlobalData,\n GlobalStores,\n Options,\n OptionsWithDefaults,\n} from '@dd/core/types';\nimport type { UnpluginContextMeta, UnpluginInstance } from 'unplugin';\nimport { createUnplugin } from 'unplugin';\nimport chalk from 'chalk';\n\nimport { validateOptions } from './validate';\nimport { getContext } from './helpers/context';\nimport { wrapGetPlugins } from './helpers/wrapPlugins';\nimport { ALL_ENVS, HOST_NAME } from '@dd/core/constants';\nimport { notifyOnEnvOverrides } from '@dd/core/helpers/env';\nimport { resolveEnable } from '@dd/core/helpers/options';\n// #imports-injection-marker\nimport * as apps from '@dd/apps-plugin';\nimport * as errorTracking from '@dd/error-tracking-plugin';\nimport * as liveDebugger from '@dd/live-debugger-plugin';\nimport * as metrics from '@dd/metrics-plugin';\nimport * as output from '@dd/output-plugin';\nimport * as rum from '@dd/rum-plugin';\nimport { getAnalyticsPlugins } from '@dd/internal-analytics-plugin';\nimport { getAsyncQueuePlugins } from '@dd/internal-async-queue-plugin';\nimport { getBuildReportPlugins } from '@dd/internal-build-report-plugin';\nimport { getBundlerReportPlugins } from '@dd/internal-bundler-report-plugin';\nimport { getCustomHooksPlugins } from '@dd/internal-custom-hooks-plugin';\nimport { getGitPlugins } from '@dd/internal-git-plugin';\nimport { getInjectionPlugins } from '@dd/internal-injection-plugin';\nimport { getTrueEndPlugins } from '@dd/internal-true-end-plugin';\n// #imports-injection-marker\n// #types-export-injection-marker\nexport type { types as AppsTypes } from '@dd/apps-plugin';\nexport type { types as ErrorTrackingTypes } from '@dd/error-tracking-plugin';\nexport type { types as LiveDebuggerTypes } from '@dd/live-debugger-plugin';\nexport type { types as MetricsTypes } from '@dd/metrics-plugin';\nexport type { types as OutputTypes } from '@dd/output-plugin';\nexport type { types as RumTypes } from '@dd/rum-plugin';\n// #types-export-injection-marker\n\nexport const helpers = {\n // Each product should have a unique entry.\n // #helpers-injection-marker\n [metrics.CONFIG_KEY]: metrics.helpers,\n // #helpers-injection-marker\n};\n\nconst red = chalk.bold.red;\n\nconst blockOnDuplicateNames = (names: string[]) => {\n const duplicates = new Set(names.filter((name) => names.filter((n) => n === name).length > 1));\n if (duplicates.size > 0) {\n throw new Error(`Duplicate plugin names: ${red(Array.from(duplicates).join(', '))}`);\n }\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 const pluginStart = Date.now();\n // TODO: Implement config overrides with environment variables.\n // TODO: Validate API Key and endpoint.\n // TODO: Inject a metric logger into the global context.\n\n const options: OptionsWithDefaults = validateOptions(opts);\n\n // Set the host name for the esbuild plugin.\n if (unpluginMetaContext.framework === 'esbuild') {\n unpluginMetaContext.esbuildHostName = HOST_NAME;\n }\n\n // Use \"production\" if there is no env passed.\n const passedEnv: Env = (process.env.BUILD_PLUGINS_ENV as Env) || 'production';\n // Fallback to \"development\" if the passed env is wrong.\n const env = ALL_ENVS.includes(passedEnv) ? passedEnv : 'development';\n // We need to account for how each bundler exposes its version.\n // - (webpack|esbuild|vite).version\n // - rollup.VERSION\n // - rspack.rspackVersion\n const bundlerVersion = bundler.rspackVersion || bundler.version || bundler.VERSION;\n const bundlerName = unpluginMetaContext.framework as BundlerName;\n\n const data: GlobalData = {\n bundler: {\n name: bundlerName,\n version: bundlerVersion,\n },\n env,\n metadata: options.metadata || {},\n packageName: `@datadog/${bundlerName}-plugin`,\n version,\n };\n\n const stores: GlobalStores = {\n errors: [],\n logs: [],\n metrics: new Set(),\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: pluginStart });\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 // Customer-facing plugins are gated by their `<configKey>.enable` flag.\n // Resolving here lets every plugin share the same semantics:\n // - config key absent → disabled\n // - config key present without `enable` → enabled\n // - non-boolean `enable` → coerced, with a single deprecation warning\n const userFacingPlugins: [name: string, configKey: string, GetPlugins][] = [\n // #configs-injection-marker\n ['apps', apps.CONFIG_KEY, apps.getPlugins],\n ['error-tracking', errorTracking.CONFIG_KEY, errorTracking.getPlugins],\n ['live-debugger', liveDebugger.CONFIG_KEY, liveDebugger.getPlugins],\n ['metrics', metrics.CONFIG_KEY, metrics.getPlugins],\n ['output', output.CONFIG_KEY, output.getPlugins],\n ['rum', rum.CONFIG_KEY, rum.getPlugins],\n // #configs-injection-marker\n ];\n\n for (const [name, configKey, getPlugins] of userFacingPlugins) {\n if (resolveEnable(options, configKey, log)) {\n pluginsToAdd.push([name, getPlugins]);\n }\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 // Verify and notify about any overrides from the environment.\n notifyOnEnvOverrides(log);\n // List all our plugins in the context.\n context.pluginNames.push(...context.plugins.map((plugin) => plugin.name));\n // Verify we don't have plugins with the same name, as they would override each other.\n blockOnDuplicateNames(context.pluginNames);\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 AppsTypes,\n ErrorTrackingTypes,\n LiveDebuggerTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n} from '@dd/factory';\nimport * as factory from '@dd/factory';\nimport webpack from 'webpack';\n\nimport pkg from '../package.json';\n\nexport type WebpackPluginOptions = Options;\nexport type {\n // #types-export-injection-marker\n AppsTypes,\n ErrorTrackingTypes,\n LiveDebuggerTypes,\n MetricsTypes,\n OutputTypes,\n RumTypes,\n // #types-export-injection-marker\n};\n\nexport const datadogWebpackPlugin = factory.buildPluginFactory({\n bundler: webpack,\n version: pkg.version,\n}).webpack;\n\nexport const version = pkg.version;\nexport const helpers = factory.helpers;\n","// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.\n// This product includes software developed at Datadog (https://www.datadoghq.com/).\n// Copyright 2019-Present Datadog, Inc.\n\nimport { getSendLog } from '@dd/core/helpers/log';\nimport type {\n BuildReport,\n GlobalContext,\n GlobalData,\n GlobalStores,\n OptionsWithDefaults,\n} from '@dd/core/types';\n\nimport { getLoggerFactory } from './logger';\n\nexport const getContext = ({\n start,\n options,\n data,\n stores,\n}: {\n start: number;\n options: OptionsWithDefaults;\n data: GlobalData;\n stores: GlobalStores;\n}): GlobalContext => {\n const buildRoot = process.cwd();\n const build: BuildReport = {\n errors: stores.errors,\n warnings: stores.warnings,\n logs: stores.logs,\n metadata: data.metadata,\n timings: stores.timings,\n bundler: data.bundler,\n };\n const context: GlobalContext = {\n // This will be updated in the metrics plugin on initialization.\n addMetric: () => {\n throw new Error('AddMetric function called before it was initialized.');\n },\n artifactsPending: false,\n artifactsReady: Promise.resolve(),\n auth: options.auth,\n pluginNames: [],\n bundler: {\n ...build.bundler,\n // This will be updated in the bundler-report plugin once we have the configuration.\n outDir: buildRoot,\n },\n build,\n // This will be updated in the bundler-report plugin once we have the configuration.\n buildRoot,\n env: data.env,\n getLogger: getLoggerFactory(data, stores, options.logLevel),\n // This will be updated in the injection plugin on initialization.\n asyncHook: () => {\n throw new Error('AsyncHook function called before it was initialized.');\n },\n hook: () => {\n throw new Error('Hook function called before it was initialized.');\n },\n // This will be updated in the injection plugin on initialization.\n inject: () => {\n throw new Error('Inject function called before it was initialized.');\n },\n markArtifactsPending: () => {},\n markArtifactsReady: () => {},\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 let resolveArtifacts: (() => void) | undefined;\n let rejectArtifacts: ((error: unknown) => void) | undefined;\n\n context.markArtifactsPending = () => {\n if (resolveArtifacts || rejectArtifacts) {\n return;\n }\n\n context.artifactsReady = new Promise<void>((resolve, reject) => {\n resolveArtifacts = resolve;\n rejectArtifacts = reject;\n });\n context.artifactsPending = true;\n context.artifactsReady.catch(() => undefined);\n };\n\n context.markArtifactsReady = (error?: unknown) => {\n const resolve = resolveArtifacts;\n const reject = rejectArtifacts;\n resolveArtifacts = undefined;\n rejectArtifacts = undefined;\n context.artifactsPending = false;\n\n if (error === undefined) {\n resolve?.();\n } else {\n reject?.(error);\n }\n };\n\n return context;\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// Shared `this`-forwarding wrapper: calls through when `shouldBlock` returns false, else signals\n// failure per `onBlocked` ('reject' also converts a `shouldBlock` throw into a rejection).\n// `getReal` is a lazy getter so a runtime swap of the real implementation (spyOn/restoreMock) is\n// picked up on the next call, not frozen at wrap time. `shouldBlock` takes `unknown[]`, not F's own\n// Parameters, since F is unresolved at every call site — a new entry point whose relevant arg isn't\n// in position 0 needs manual review as a result.\nexport function makeGuardWrapper<F extends (...args: never[]) => unknown>(\n getReal: () => F,\n shouldBlock: (...args: unknown[]) => boolean,\n blockedMessage: string,\n onBlocked: 'throw' | 'reject',\n): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n let blocked: boolean;\n if (onBlocked === 'reject') {\n try {\n blocked = shouldBlock(...args);\n } catch (error) {\n return Promise.reject(error);\n }\n } else {\n blocked = shouldBlock(...args);\n }\n if (!blocked) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n if (onBlocked === 'reject') {\n return Promise.reject(new Error(blockedMessage));\n }\n throw new Error(blockedMessage);\n };\n return wrapper as unknown as F;\n}\n\n// The last argument is a function in every real call this wraps (fs.readFile/open/copyFile/cp all\n// require their callback), so no other heuristic is needed to find it. Exported for env-guard.ts's\n// own hand-rolled cp wrappers, which need this same callback-reporting behavior for a guard failure\n// that isn't just a fixed shouldBlock() result (see their own comment).\nexport function invokeCallbackArg(args: unknown[], error: Error): void {\n const maybeCallback = args[args.length - 1];\n if (typeof maybeCallback === 'function') {\n // Deferred, not called synchronously: every real error-first-callback fs function reports\n // failure on a later tick, and a caller relying on that ordering (e.g. attaching state right\n // after the call, before the callback can possibly run) would otherwise observe this guard's\n // rejection out of sequence with a real one.\n process.nextTick(maybeCallback as (...cbArgs: unknown[]) => void, error);\n }\n}\n\n// For callback-style APIs whose real contract reports failure via an error-first callback, never a\n// synchronous throw (fs.readFile/open/copyFile/cp) — makeGuardWrapper's 'throw' mode would break\n// that contract. A `shouldBlock` throw is routed through the same callback for the same reason.\nexport function makeGuardCallbackWrapper<F extends (...args: never[]) => unknown>(\n getReal: () => F,\n shouldBlock: (...args: unknown[]) => boolean,\n blockedMessage: string,\n): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n let blocked: boolean;\n try {\n blocked = shouldBlock(...args);\n } catch (error) {\n invokeCallbackArg(args, error instanceof Error ? error : new Error(String(error)));\n return undefined;\n }\n if (!blocked) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n invokeCallbackArg(args, new Error(blockedMessage));\n return undefined;\n };\n return wrapper as unknown as F;\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/**\n * Stashes a value on a stable Node core module (e.g. `fs`, `net`) keyed by `Symbol.for(key)`, so\n * every re-evaluation of a guard file (bundled copies, Jest's per-test-file isolation) resolves the\n * same instance instead of populating its own private one. `Symbol.for`, not `Symbol()`, so a\n * second evaluation recognizes the first evaluation's installed value. Non-configurable/\n * non-writable so no code holding a reference to `hostModule` can swap in a fake value.\n */\nexport function getOrCreateShared<T>(hostModule: object, key: string, factory: () => T): T {\n const symbol = Symbol.for(key);\n const registry = hostModule as Record<symbol, T | undefined>;\n // An own-property check, not `in` (which walks the prototype chain — an inherited symbol would\n // short-circuit this as already-installed) or a falsy check (`!registry[symbol]`, which misses a\n // legitimately falsy factory result and re-defines an already configurable:false property).\n if (!Object.prototype.hasOwnProperty.call(registry, symbol)) {\n Object.defineProperty(registry, symbol, {\n value: factory(),\n writable: false,\n configurable: false,\n enumerable: false,\n });\n }\n return registry[symbol] as T;\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/* global globalThis, Proxy */\n\nimport child_process from 'child_process';\nimport dgram from 'dgram';\nimport dns from 'dns';\nimport net from 'net';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { EventEmitter } from 'node:events';\nimport { syncBuiltinESMExports } from 'node:module';\nimport { Readable, Writable } from 'node:stream';\nimport { promisify } from 'node:util';\nimport worker_threads from 'worker_threads';\n\nimport { createEpochGuard } from './execution-epoch';\nimport { makeGuardWrapper } from './guarded-wrapper';\nimport { getOrCreateShared } from './shared-module-singleton';\n\n// No OS sandbox here (unlike prod's Deno) — blocks net/subprocess at the JS level, scoped per-call via AsyncLocalStorage, not a global toggle.\n\nconst NETWORK_BLOCKED_MESSAGE =\n 'Network access is not allowed directly in backend functions — use $.Actions instead.';\nconst SUBPROCESS_BLOCKED_MESSAGE = 'Spawning a subprocess is not allowed in backend functions.';\nconst WORKER_THREAD_BLOCKED_MESSAGE =\n 'Spawning a worker thread is not allowed in backend functions.';\n\ninterface GuardedAsyncContext {\n isActive(): boolean;\n run<T>(fn: () => T): T;\n}\n\n// Keyed on the real `net` module, not a per-module `new AsyncLocalStorage()`: this file gets\n// evaluated more than once (bundled copies, Jest's per-test-file isolation), and every evaluation\n// needs the same store — `globalThis`/`process` are sandboxed per test file, core modules aren't.\n// Returns isActive()/run() rather than the raw instance, since any code with `require('net')` can\n// read whatever this stores, and a raw instance's own `.disable()` would kill this guard's scope\n// detection process-wide.\nfunction getSharedContext(key: string): GuardedAsyncContext {\n return getOrCreateShared(net, `@dd/apps-plugin/network-guard ${key}`, () => {\n const context = new AsyncLocalStorage<true>();\n return {\n isActive: () => context.getStore() === true,\n run: <T>(fn: () => T) => context.run(true, fn),\n };\n });\n}\n\n// Scoped to the active `runBlocked` call's async chain, not process-wide, so unrelated concurrent callers aren't blocked too.\nconst blockedContext = getSharedContext('blockedContext');\n\n// Scoped to the active `runAllowed` call's async chain, not process-wide, so a sibling call stays blocked during the exemption.\nconst allowedContext = getSharedContext('allowedContext');\n\nfunction isCurrentlyBlocked(): boolean {\n return blockedContext.isActive() && !allowedContext.isActive();\n}\n\n// `Symbol.for`, not `Symbol()`, so every re-evaluation of this file recognizes an already-installed guard instead of minting its own.\nconst ALREADY_GUARDED = Symbol.for('@dd/apps-plugin/network-guard installed');\n\n// Jest's globalThis Proxy can't produce a non-configurable property without throwing, and by then\n// it's already mutated the real object — so relax configurability under Jest (detected via this\n// env var) instead of hitting that failure. Production never sets it.\nconst RUNNING_UNDER_JEST = process.env.JEST_WORKER_ID !== undefined;\n\n// Module objects (net/dgram/dns) stay non-configurable even under Jest, or dd-trace's CI\n// Visibility instrumentation could swap in its own unguarded function. globalThis is relaxed so\n// Jest's environment can still touch it. write/end need their own carve-out: CI pipes\n// stdout/stderr into real net.Socket instances, and jest-mock's spyOn/restoreMock needs\n// `configurable` to restore them.\nfunction shouldAllowConfigurableUnderJest(target: object, prop: string): boolean {\n if (!RUNNING_UNDER_JEST) {\n return false;\n }\n return (\n target === globalThis ||\n (target === net.Socket.prototype && (prop === 'write' || prop === 'end'))\n );\n}\n\n/**\n * Permanent getter/setter — a detached callback can still fire after `runBlocked` resolves and\n * must stay blocked. The setter rebuilds the guard on every write since some libraries (e.g. MSW)\n * mark the last function object they saw as \"already patched,\" and reusing one frozen object\n * collides. Non-configurable except `globalThis` under Jest (see `shouldAllowConfigurableUnderJest`),\n * so a dependency can't swap the whole descriptor; plain reassignment still works. Re-installing on\n * an already-guarded property is a no-op via `ALREADY_GUARDED`.\n */\nexport function installGuardedProperty<T>(\n target: object,\n prop: string,\n makeGuard: (getReal: () => T) => T,\n): void {\n const existingGetter = Object.getOwnPropertyDescriptor(target, prop)?.get as\n | { [ALREADY_GUARDED]?: true }\n | undefined;\n if (existingGetter?.[ALREADY_GUARDED]) {\n return;\n }\n\n let real = (target as Record<string, T>)[prop];\n if (real === undefined) {\n // Nothing to guard — this runtime doesn't expose this method/global (e.g. dns.resolveTlsa\n // on Node 20). A wrapper here would make feature-detection lie.\n return;\n }\n // Tracks which `real` was active when each guard was built — the \"const original = x; x =\n // mock; x = original;\" idiom hands the guard itself back on restore, and without this map that\n // would make the guard call itself forever.\n const realAtGuardCreation = new WeakMap<object, T>();\n\n function buildGuard(): T {\n // Closes over its own snapshot of `real`, not the shared variable — a wrapper-closure\n // restore would otherwise read whatever `real` currently holds and recurse forever.\n const capturedReal = real;\n const guard = makeGuard(() => capturedReal);\n // WeakMap.set() throws on a non-object key; makeGuard can return one (e.g. guardWebSocket\n // returns undefined when the real global doesn't exist).\n if (guard !== null && (typeof guard === 'object' || typeof guard === 'function')) {\n realAtGuardCreation.set(guard as object, real);\n }\n return guard;\n }\n\n let currentGuard = buildGuard();\n const getter = (): T => currentGuard;\n (getter as unknown as { [ALREADY_GUARDED]: true })[ALREADY_GUARDED] = true;\n Object.defineProperty(target, prop, {\n configurable: shouldAllowConfigurableUnderJest(target, prop),\n enumerable: true,\n get: getter,\n // A plain `function`, not an arrow, so `this` is the real receiver — needed to tell\n // `net.Socket.prototype.write = mock` (every socket) apart from `someSocket.write = mock`\n // (one socket) when `target` is a shared prototype.\n set: function (this: unknown, value: T) {\n if (\n this !== target &&\n this !== null &&\n (typeof this === 'object' || typeof this === 'function')\n ) {\n // `target` is a shared prototype — shadow the guard on this instance only, like an\n // unguarded assignment would, instead of repointing the delegate every other\n // instance's guard calls through. Some Node/Jest internals call this setter with a\n // non-object receiver; fall through to the shared-delegate path for those.\n Object.defineProperty(this, prop, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n return;\n }\n real = realAtGuardCreation.has(value as object)\n ? (realAtGuardCreation.get(value as object) as T)\n : value;\n currentGuard = buildGuard();\n },\n });\n}\n\n// write/end signal failure by erroring/destroying the stream, not throwing — a synchronous throw\n// would surface as an uncaught exception in Node internals that call write() without a try/catch\n// (e.g. http's request-flush code, the exact path a reused keep-alive socket takes). destroy() is\n// only safe when something listens for 'error' — Node's default for an unlistened 'error' is to\n// crash the process. A completion callback is always invoked either way.\nfunction isFunction(value: unknown): value is (...args: unknown[]) => void {\n return typeof value === 'function';\n}\n\n// Node's error-first callback is always the last argument. Shared by signalBlockedSocketOp,\n// guardCallbackMethod, and guardExecFactory. Returns whether one was found, so a caller can fall\n// back to an 'error' event.\nfunction invokeCallbackArg(args: unknown[], err: Error, ...extraArgs: unknown[]): boolean {\n const maybeCallback = args[args.length - 1];\n if (isFunction(maybeCallback)) {\n process.nextTick(maybeCallback, err, ...extraArgs);\n return true;\n }\n return false;\n}\n\n// Deferred via process.nextTick so a listener attached right after the call still sees it,\n// matching a real socket's error-emission timing. Shared by guardBindMethod,\n// guardCallbackMethod's EventEmitter fallback, guardChildProcessSpawnMethod, and\n// createBlockedChildProcessStub.\nfunction emitAsyncErrorIfListened(target: EventEmitter, err: Error): void {\n process.nextTick(() => {\n if (target.listenerCount('error') > 0) {\n target.emit('error', err);\n }\n });\n}\n\nfunction signalBlockedSocketOp(socket: net.Socket, args: unknown[]): void {\n const err = new Error(NETWORK_BLOCKED_MESSAGE);\n invokeCallbackArg(args, err);\n // Deferred to match a real socket's error timing — checking listenerCount synchronously here\n // would miss a listener attached on the next line.\n process.nextTick(() => {\n if (socket.listenerCount('error') > 0) {\n socket.destroy(err);\n }\n });\n}\n\n// The dev server's own stdout/stderr are real net.Socket instances whenever the process is piped —\n// not a network-exfiltration vector, so exempting them only saves the developer's console.log\n// during a blocked scope. Captured once at module load, which local-execution.ts's\n// loadCustomerModuleEntry always awaits before evaluating any customer module's top-level code, so\n// this can never capture a value a customer module already repointed via\n// `Object.defineProperty(process, 'stdout', ...)` — the live `process.stdout`/`stderr` getters are\n// reassignable, and a customer function could otherwise repoint them at an attacker-controlled\n// socket to exfiltrate past the block.\nconst trustedStdout: unknown = process.stdout;\nconst trustedStderr: unknown = process.stderr;\nfunction isProcessStdio(socket: net.Socket): boolean {\n return socket === trustedStdout || socket === trustedStderr;\n}\n\n// Same reasoning as trustedStdout/trustedStderr above, captured before installGuardedProperty\n// patches `globalThis.fetch` below: the dev server's own authenticated request (packages/core's\n// request.ts, used for $.Actions calls and runtime-context hydration) must reach the real network\n// stack even if a customer function already reassigned `globalThis.fetch` to an attacker-controlled\n// wrapper before triggering that call — a plain reassignment goes through installGuardedProperty's\n// setter and rewrites the guard's own delegate, which the authenticated request would otherwise call\n// through to while inside runAllowed. Callers that need this must be threaded explicitly (e.g. via\n// RequestOpts.fetchImpl) rather than relying on a fresh `globalThis.fetch` lookup at call time.\nexport const trustedFetch: typeof fetch = globalThis.fetch;\n\n// Shared by guardSocketWrite/guardSocketEnd, which differ only in the blocked-path return value\n// (write() returns a boolean, end() returns `this` for chaining).\nfunction guardSocketOp<R>(\n getReal: () => (this: net.Socket, ...args: never[]) => R,\n blockedReturn: (socket: net.Socket) => R,\n): (this: net.Socket, ...args: never[]) => R {\n const wrapper = function (this: net.Socket, ...args: unknown[]): R {\n if (!isCurrentlyBlocked() || isProcessStdio(this)) {\n return (getReal() as unknown as (...a: unknown[]) => R).apply(this, args);\n }\n signalBlockedSocketOp(this, args);\n return blockedReturn(this);\n };\n return wrapper as unknown as (this: net.Socket, ...args: never[]) => R;\n}\n\nfunction guardSocketWrite<F extends (this: net.Socket, ...args: never[]) => boolean>(\n getReal: () => F,\n): F {\n return guardSocketOp<boolean>(getReal, () => false) as unknown as F;\n}\n\n// Same as guardSocketWrite, but end() returns `this` for chaining.\nfunction guardSocketEnd<F extends (this: net.Socket, ...args: never[]) => net.Socket>(\n getReal: () => F,\n): F {\n return guardSocketOp<net.Socket>(getReal, (socket) => socket) as unknown as F;\n}\n\n// net.Server.listen/dgram.Socket.bind/connect: their optional callback is a success-only shorthand\n// for the 'listening'/'connect' event (no error parameter per @types/node) — real failures only\n// ever reach the async 'error' event, so a synchronous throw here would surface as an uncaught\n// exception in the idiomatic `server.on('error', cb); server.listen(port)` pattern. Deferred via\n// process.nextTick for the same same-tick-safety reason as signalBlockedSocketOp.\nfunction guardBindMethod<F extends (this: EventEmitter, ...args: never[]) => unknown>(\n getReal: () => F,\n): F {\n const wrapper = function (this: EventEmitter, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n emitAsyncErrorIfListened(this, new Error(NETWORK_BLOCKED_MESSAGE));\n return this;\n };\n return wrapper as unknown as F;\n}\n\n// dgram.Socket.send and the callback-style dns.resolve* surfaces report failure via an error-first\n// callback (dns.resolve*'s is mandatory, dgram's optional, falling back to an async 'error' event).\n// Deferred via process.nextTick for the same reason as guardBindMethod.\nfunction guardCallbackMethod<F extends (...args: never[]) => unknown>(getReal: () => F): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n const err = new Error(NETWORK_BLOCKED_MESSAGE);\n if (!invokeCallbackArg(args, err) && this instanceof EventEmitter) {\n emitAsyncErrorIfListened(this, err);\n }\n return undefined;\n };\n return wrapper as unknown as F;\n}\n\n// dns.promises.*/dns.promises.Resolver.prototype.* always return a Promise, so a `.catch()`-chaining\n// caller needs a rejection, not a thrown exception.\nfunction guardNetworkPromiseMethod<F extends (...args: never[]) => Promise<unknown>>(\n getReal: () => F,\n): F {\n return makeGuardWrapper(getReal, () => isCurrentlyBlocked(), NETWORK_BLOCKED_MESSAGE, 'reject');\n}\n\n// Shared by guardWebSocket/guardEventSource/guardWorker. A Proxy construct trap, not a subclass,\n// so a runtime swap via installGuardedProperty's setter is picked up on the next `new`. Forwards\n// the caller's real `newTarget` into Reflect.construct so subclassing (`class Foo extends\n// WebSocket {}`) still works instead of always producing a base instance.\nfunction guardConstructibleGlobal(\n getReal: () => unknown,\n blockedMessage: string = NETWORK_BLOCKED_MESSAGE,\n): unknown {\n const real = getReal();\n if (real === undefined) {\n // This repo's supported Node range spans versions where these globals don't exist yet.\n return undefined;\n }\n return new Proxy(real as object, {\n construct(_target, args, newTarget) {\n if (isCurrentlyBlocked()) {\n throw new Error(blockedMessage);\n }\n const RealCtor = getReal() as new (...a: unknown[]) => object;\n return Reflect.construct(RealCtor, args, newTarget);\n },\n });\n}\n\nexport function guardWebSocket(getReal: () => unknown): unknown {\n return guardConstructibleGlobal(getReal);\n}\n\n// EventSource's transport bypasses the patched net.Socket.connect the same way WebSocket does.\n// Not reachable without --experimental-eventsource on this repo's Node versions, but guarding it\n// unconditionally means it's already correct once a runtime exposes it.\nexport function guardEventSource(getReal: () => unknown): unknown {\n return guardConstructibleGlobal(getReal);\n}\n\n// A worker gets a fresh V8 realm with its own module registry, so nothing inside it inherits this\n// file's monkeypatches — blocking construction is the only enforceable boundary.\nexport function guardWorker(getReal: () => unknown): unknown {\n return guardConstructibleGlobal(getReal, WORKER_THREAD_BLOCKED_MESSAGE);\n}\n\n// execSync/execFileSync genuinely throw synchronously on failure — this guard is for those two\n// only. The rest have their own guards below matching each one's real (never-throws) contract.\nfunction guardSubprocess<F extends (...args: never[]) => unknown>(getReal: () => F): F {\n return makeGuardWrapper(\n getReal,\n () => isCurrentlyBlocked(),\n SUBPROCESS_BLOCKED_MESSAGE,\n 'throw',\n );\n}\n\n// spawn()/fork() return a brand-new ChildProcess with no existing `this` to emit 'error' on, so\n// the guard fabricates a stub shaped like the real return value instead of `undefined` (which\n// would TypeError on `spawn(...).stdout.on(...)`). stdout/stderr/stdin are real inert streams, not\n// null, matching a real launch failure. send()/disconnect() are included even for spawn/exec/\n// execFile (which lack IPC by default) — this guard is dev-loop safety, not a hard security\n// boundary, and avoiding a crash matters more than exact fidelity.\nfunction createBlockedChildProcessStub(err: Error): EventEmitter & Record<string, unknown> {\n const stub = new EventEmitter() as EventEmitter & Record<string, unknown>;\n stub.pid = undefined;\n stub.exitCode = null;\n stub.signalCode = null;\n stub.killed = false;\n stub.connected = false;\n stub.channel = undefined;\n const stdout = new Readable({ read() {} });\n stdout.push(null);\n const stderr = new Readable({ read() {} });\n stderr.push(null);\n stub.stdout = stdout;\n stub.stderr = stderr;\n stub.stdin = new Writable({\n write(_chunk, _encoding, callback) {\n callback();\n },\n });\n stub.kill = () => false;\n stub.ref = () => stub;\n stub.unref = () => stub;\n stub.disconnect = () => {};\n stub.send = (...sendArgs: unknown[]) => {\n const sendErr = new Error('channel closed');\n if (!invokeCallbackArg(sendArgs, sendErr)) {\n // No callback given — fall back to the 'error' event a real disconnected channel uses.\n emitAsyncErrorIfListened(stub, sendErr);\n }\n return false;\n };\n emitAsyncErrorIfListened(stub, err);\n return stub;\n}\n\nfunction guardSpawnFactory<F extends (...args: never[]) => unknown>(getReal: () => F): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n return createBlockedChildProcessStub(new Error(SUBPROCESS_BLOCKED_MESSAGE));\n };\n return wrapper as unknown as F;\n}\n\n// exec/execFile report failure via an error-first callback and always return a ChildProcess\n// synchronously. Real Node sets stdout/stderr to empty strings, not undefined, even on a launch\n// failure — a caller doing `err.stderr.trim()` would otherwise TypeError.\nfunction guardExecFactory<F extends (...args: never[]) => unknown>(getReal: () => F): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n const err = new Error(SUBPROCESS_BLOCKED_MESSAGE);\n invokeCallbackArg(args, err, '', '');\n return createBlockedChildProcessStub(err);\n };\n return wrapper as unknown as F;\n}\n\n// ChildProcess.prototype.spawn() configures an existing instance, so there's no factory return\n// value to fabricate — just this instance's async 'error' event. The real method returns a\n// synchronous integer (0 success, negative errno on failure), so the blocked path returns a\n// negative placeholder. Kept separate from guardBindMethod since this method's `this` type isn't\n// part of @types/node's public surface (see the childProcessPrototype cast below).\nfunction guardChildProcessSpawnMethod<F extends (...args: never[]) => unknown>(\n getReal: () => F,\n): F {\n const wrapper = function (this: EventEmitter, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n emitAsyncErrorIfListened(this, new Error(SUBPROCESS_BLOCKED_MESSAGE));\n return -1;\n };\n return wrapper as unknown as F;\n}\n\n// spawnSync never throws either — it returns a SpawnSyncReturns-shaped object with `.error` set,\n// so the guard mirrors that shape. `output` is null on a real launch failure, not an array — a\n// caller doing `result.output[1].toString()` would otherwise TypeError against a naive stub.\nfunction guardSpawnSyncResult<F extends (...args: never[]) => unknown>(getReal: () => F): F {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n if (!isCurrentlyBlocked()) {\n return (getReal() as unknown as (...a: unknown[]) => unknown).apply(this, args);\n }\n return {\n pid: 0,\n output: null,\n stdout: undefined,\n stderr: undefined,\n status: null,\n signal: null,\n error: new Error(SUBPROCESS_BLOCKED_MESSAGE),\n };\n };\n return wrapper as unknown as F;\n}\n\n/**\n * exec/execFile's native `promisify.custom` lives on the specific function object, so a fresh\n * wrapper silently drops it, while reusing the original symbol would bypass the guard. Calls the\n * already-guarded `wrapper` and attaches `.child` to match Node's real `PromiseWithChild`\n * contract.\n */\nfunction guardExecWithPromisifyCustom<F extends (...args: never[]) => unknown>(\n getReal: () => F,\n): F {\n const wrapper = guardExecFactory(getReal);\n Object.defineProperty(wrapper, promisify.custom, {\n configurable: true,\n writable: true,\n value: (...args: unknown[]) => {\n let child: unknown;\n const promise = new Promise((resolve, reject) => {\n child = (wrapper as unknown as (...a: unknown[]) => unknown)(\n ...args,\n (error: unknown, stdout: unknown, stderr: unknown) => {\n if (error) {\n const errorWithOutput = Object.assign(error as object, {\n stdout,\n stderr,\n });\n reject(errorWithOutput);\n } else {\n resolve({ stdout, stderr });\n }\n },\n );\n });\n (promise as unknown as { child: unknown }).child = child;\n return promise;\n },\n });\n return wrapper;\n}\n\n// net.Socket.connect() genuinely throws synchronously for some argument-validation failures, and\n// runs inside the customer function's own async call stack (see runBlocked in local-execution.ts),\n// where a synchronous throw is safely caught — unlike the detached-callback guards below, left\n// throw-based deliberately.\ninstallGuardedProperty<typeof net.Socket.prototype.connect>(\n net.Socket.prototype,\n 'connect',\n (getReal) =>\n makeGuardWrapper(getReal, () => isCurrentlyBlocked(), NETWORK_BLOCKED_MESSAGE, 'throw'),\n);\n// A reused, already-connected keep-alive socket never calls connect() again for a second request —\n// write()/end() are the choke point every request still goes through, so guarding only connect()\n// would let a module-load-time \"warm-up\" request bypass the guard when reused later.\ninstallGuardedProperty<typeof net.Socket.prototype.write>(\n net.Socket.prototype,\n 'write',\n guardSocketWrite,\n);\ninstallGuardedProperty<typeof net.Socket.prototype.end>(\n net.Socket.prototype,\n 'end',\n guardSocketEnd,\n);\n// A dependency calling `Writable.prototype.write.call(aSocket, data)` directly still reaches the\n// real implementation, since only Socket's own write/end are shadowed above. Guarding\n// `stream.Writable.prototype` itself isn't viable: countless unrelated Writable subclasses each do\n// `SomeClass.prototype.write = ownImpl`, and every such assignment walks up and triggers the same\n// inherited setter on Writable.prototype, corrupting every other subclass's write() with whichever\n// wrote last (breaks Vite's own HTTP client in real bundler tests). Accepted as a residual gap —\n// this guard is dev-time safety, not a hard security boundary (see the \"No OS sandbox\" note above).\ninstallGuardedProperty<typeof fetch>(globalThis, 'fetch', guardNetworkPromiseMethod);\n// dgram (UDP) and the native WebSocket global are separate entry points from fetch/net — neither\n// goes through net.Socket, so they need their own guards.\ninstallGuardedProperty<typeof dgram.Socket.prototype.send>(\n dgram.Socket.prototype,\n 'send',\n guardCallbackMethod,\n);\ninstallGuardedProperty<typeof dgram.Socket.prototype.connect>(\n dgram.Socket.prototype,\n 'connect',\n guardBindMethod,\n);\n// Inbound listeners are a separate entry point from the outbound send/connect above — a dependency\n// can still open a real listening socket via net.createServer().listen(...) or dgram's .bind(...).\ninstallGuardedProperty<typeof net.Server.prototype.listen>(\n net.Server.prototype,\n 'listen',\n guardBindMethod,\n);\ninstallGuardedProperty<typeof dgram.Socket.prototype.bind>(\n dgram.Socket.prototype,\n 'bind',\n guardBindMethod,\n);\ninstallGuardedProperty<unknown>(globalThis, 'WebSocket', guardWebSocket);\ninstallGuardedProperty<unknown>(globalThis, 'EventSource', guardEventSource);\n\n// dns.resolve*/dns.promises.resolve*/dns.Resolver/dns.promises.Resolver go through Node's native\n// c-ares channel, bypassing the net.Socket/dgram.Socket guards above — each is a distinct function\n// object needing its own guard. dns.lookup is deliberately excluded: this threat model is dev-loop\n// safety, not DNS-tunneling exfiltration, and guarding it risks breaking hostname validation.\nconst DNS_RESOLVE_METHODS = [\n 'resolve',\n 'resolve4',\n 'resolve6',\n 'resolveAny',\n 'resolveCaa',\n 'resolveCname',\n 'resolveMx',\n 'resolveNaptr',\n 'resolveNs',\n 'resolvePtr',\n 'resolveSoa',\n 'resolveSrv',\n 'resolveTlsa',\n 'resolveTxt',\n 'reverse',\n] as const;\nfor (const method of DNS_RESOLVE_METHODS) {\n // Each method's real signature differs, so the type argument is pinned to the guard's own\n // constraint instead (same approach as the child_process installs below).\n installGuardedProperty<(...args: never[]) => unknown>(dns, method, guardCallbackMethod);\n installGuardedProperty<(...args: never[]) => unknown>(\n dns.Resolver.prototype,\n method,\n guardCallbackMethod,\n );\n // dns.promises.*/dns.promises.Resolver.prototype.* always return a Promise, so these use the\n // reject-not-throw guard instead.\n installGuardedProperty<(...args: never[]) => Promise<unknown>>(\n dns.promises,\n method,\n guardNetworkPromiseMethod,\n );\n installGuardedProperty<(...args: never[]) => Promise<unknown>>(\n dns.promises.Resolver.prototype,\n method,\n guardNetworkPromiseMethod,\n );\n}\n\ninstallGuardedProperty<typeof child_process.spawn>(child_process, 'spawn', guardSpawnFactory);\ninstallGuardedProperty<typeof child_process.spawnSync>(\n child_process,\n 'spawnSync',\n guardSpawnSyncResult,\n);\n// `unknown` is the correct escape hatch: exec/execFile's `__promisify__` property doesn't structurally satisfy a plain function type.\ninstallGuardedProperty<(...args: never[]) => unknown>(\n child_process,\n 'exec',\n guardExecWithPromisifyCustom,\n);\ninstallGuardedProperty<typeof child_process.execSync>(child_process, 'execSync', guardSubprocess);\ninstallGuardedProperty<(...args: never[]) => unknown>(\n child_process,\n 'execFile',\n guardExecWithPromisifyCustom,\n);\ninstallGuardedProperty<typeof child_process.execFileSync>(\n child_process,\n 'execFileSync',\n guardSubprocess,\n);\ninstallGuardedProperty<(...args: never[]) => unknown>(child_process, 'fork', guardSpawnFactory);\n// Also guards `ChildProcess.prototype.spawn` directly, since the functions above are thin wrappers a dependency could bypass them through.\nconst childProcessPrototype = child_process.ChildProcess.prototype as unknown as Record<\n string,\n unknown\n>;\ninstallGuardedProperty<(...args: never[]) => unknown>(\n childProcessPrototype,\n 'spawn',\n guardChildProcessSpawnMethod,\n);\n\ninstallGuardedProperty<unknown>(worker_threads, 'Worker', guardWorker);\n\n// installGuardedProperty only patches each built-in's CJS default export; Node keeps ESM named\n// bindings (`import { spawn } from 'node:child_process'`) as separate references to the original\n// native values. syncBuiltinESMExports re-syncs them. Not unit-tested — Jest's CJS transform can't\n// reproduce the real ESM-binding divergence.\nsyncBuiltinESMExports();\n\n// Guards against the same abandoned-scope-corrupts-a-newer-one race as `local-execution.ts` — see `execution-epoch.ts`.\nconst blockEpoch = createEpochGuard();\n\nexport interface BlockedScopeHandle {\n // Invalidates this specific `runBlocked` call's scope, but only if it's still the active one —\n // a no-op once a newer call has superseded it. Unlike `forceReset()`, safe to call even while a\n // different scope is running, since it won't un-exempt that other scope's in-flight\n // `runAllowed` call.\n abandonIfCurrent(): void;\n}\n\n// Runs `fn` with network/subprocess access blocked; wraps the customer's function body in `local-execution.ts`'s `runScriptLocally`.\n// `onScopeStarted`, if given, is invoked synchronously with a handle scoped to *this* call, for a\n// caller whose own timeout might fire while `fn` is still pending (see `local-execution.ts`).\nexport async function runBlocked<T>(\n fn: () => Promise<T>,\n onScopeStarted?: (handle: BlockedScopeHandle) => void,\n): Promise<T> {\n const scope = blockEpoch.start();\n onScopeStarted?.({ abandonIfCurrent: () => scope.concludeIfCurrent() });\n try {\n return await blockedContext.run(fn);\n } finally {\n scope.concludeIfCurrent();\n }\n}\n\n// Exempts `fn`'s own async chain (not siblings) from an active `runBlocked` scope; no-ops if that scope was already abandoned.\nexport async function runAllowed<T>(fn: () => Promise<T>): Promise<T> {\n if (!blockEpoch.hasActiveScope()) {\n return fn();\n }\n return allowedContext.run(fn);\n}\n\n// Test-only escape hatch for resetting shared module state between tests — unconditional, unlike\n// `BlockedScopeHandle.abandonIfCurrent()`, since a test fully controls when scopes start and end.\nexport function forceReset(): void {\n blockEpoch.forceInvalidate();\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/* global NodeJS, Proxy */\n\nimport fs from 'fs';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { syncBuiltinESMExports } from 'node:module';\nimport nodePath from 'path';\nimport { fileURLToPath } from 'url';\n\nimport { invokeCallbackArg, makeGuardCallbackWrapper, makeGuardWrapper } from './guarded-wrapper';\nimport { getOrCreateShared } from './shared-module-singleton';\n\n// Captured at module load — before any customer code runs — so a backend function can't replace\n// fs.realpathSync/readlinkSync with a benign-path stub and read /proc/self/environ through this\n// file's own already-wrapped fs.readFileSync, whose forged-path check would otherwise consult the\n// tampered, live fs methods instead of these frozen references.\nconst nativeRealpathSync = fs.realpathSync;\nconst nativeReadlinkSync = fs.readlinkSync;\n\n// Scopes process.env to a from-scratch allowlist during local execution — production isolates\n// each execution in its own Deno subprocess with --allow-env, but local execution has no process\n// boundary, so this also blocks the /proc/.../environ backing-store bypass on Linux that swapping\n// process.env alone wouldn't stop.\n//\n// JS-level defense-in-depth only, not a hard security boundary (matches network-guard.ts): a\n// callback that escapes its own AsyncLocalStorage continuation entirely — a FinalizationRegistry\n// finalizer, for example — can reassign process.env indistinguishably from a legitimate\n// post-scope reload, letting attacker-controlled data become the real-environment fallback for\n// every later execution.\n\nexport const SAFE_ENV_KEYS = ['PATH', 'HOME', 'NODE_ENV', 'TMPDIR'] as const;\n\nexport function buildScopedEnv(customCredentials: Record<string, string>): Record<string, string> {\n const scoped: Record<string, string> = {};\n for (const key of SAFE_ENV_KEYS) {\n const value = process.env[key];\n if (value !== undefined) {\n scoped[key] = value;\n }\n }\n const merged = { ...scoped, ...customCredentials };\n if (process.platform !== 'win32') {\n return merged;\n }\n // On win32, Node's real process.env is case-insensitive (e.g. .Path and .PATH read the same\n // value), but `merged` is a plain object. Without this, customer code reading a SAFE_ENV_KEYS\n // entry under any casing other than its canonical uppercase form gets undefined during local\n // execution even though the same read against the real environment would succeed.\n return new Proxy(merged, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !(prop in target)) {\n const canonicalKey = SAFE_ENV_KEYS.find(\n (key) => key.toLowerCase() === prop.toLowerCase(),\n );\n if (canonicalKey) {\n return Reflect.get(target, canonicalKey, receiver);\n }\n }\n return Reflect.get(target, prop, receiver);\n },\n has(target, prop) {\n if (typeof prop === 'string' && !(prop in target)) {\n return SAFE_ENV_KEYS.some((key) => key.toLowerCase() === prop.toLowerCase());\n }\n return Reflect.has(target, prop);\n },\n // Without this, a write through a non-canonical casing (e.g. .Path when only .PATH exists)\n // falls through to the default set behavior and creates a second, separate own property\n // instead of updating the canonical one — leaving PATH/Path/path to disagree within the\n // same scope, breaking the case-insensitivity the get/has traps above establish for reads.\n set(target, prop, value) {\n if (typeof prop === 'string' && !(prop in target)) {\n const canonicalKey = SAFE_ENV_KEYS.find(\n (key) => key.toLowerCase() === prop.toLowerCase(),\n );\n if (canonicalKey) {\n return Reflect.set(target, canonicalKey, value);\n }\n }\n return Reflect.set(target, prop, value);\n },\n });\n}\n\n/**\n * Shared across every re-evaluation of this file (see getSharedState()). Every member is a\n * function, not a data field, since this object is reachable via any `require('fs')` — a raw\n * `realEnv` field would leak the real environment, and a raw `AsyncLocalStorage` would let a\n * caller kill scope detection process-wide via `.disable()`. Each function re-checks scope itself.\n */\ninterface EnvGuardSharedState {\n getCurrentEnv(): Record<string, string> | NodeJS.ProcessEnv;\n isInsideScope(): boolean;\n setRealEnvIfOutsideScope(newValue: NodeJS.ProcessEnv): void;\n restoreRealEnvFromHistory(): void;\n runInScope<T>(scopedEnv: Record<string, string>, fn: () => Promise<T>): Promise<T>;\n // Symbol() (not Symbol.for), so the token is never attached as a discoverable property anywhere\n // — Object.getOwnPropertySymbols can't reveal it, and it can't be reconstructed from a string.\n // Only the exact token armScope() returned can end the scope it identifies, closing off the\n // \"call the shared decrement directly enough times to zero the count early\" bypass a raw counter\n // would allow any caller with `require('fs')` to trigger.\n armScope(): symbol;\n disarmScope(token: symbol): void;\n forceResetAllScopes(): void;\n getExcludeEnv(): boolean | undefined;\n getCachedNativeFdGetter(): (() => number) | undefined;\n setCachedNativeFdGetterOnce(getter: (() => number) | undefined): void;\n}\n\n// Keyed on the real `fs` module, via the same getOrCreateShared() helper network-guard.ts uses:\n// this file gets evaluated more than once (bundled copies, Jest's per-test-file isolation), and\n// every evaluation must share the same scope/env/count state or a later evaluation's Proxy would\n// never consult the storage an earlier evaluation's scope populates. The factory runs exactly once\n// across every evaluation (see getOrCreateShared), so anything done here — including installing\n// process.report.excludeEnv's accessor below — is inherently a run-once side effect, with no\n// separate \"already installed\" marker needed.\nfunction getSharedState(): EnvGuardSharedState {\n return getOrCreateShared(fs, '@dd/apps-plugin/env-guard shared-state', () => {\n const scopedEnvContext = new AsyncLocalStorage<Record<string, string>>();\n // Bound here, at first-ever creation — before any customer code has had a chance to run —\n // so a later `AsyncLocalStorage.prototype.getStore = () => undefined` from inside a backend\n // function can't make every scoped lookup fall through to the real environment.\n const nativeGetStore = AsyncLocalStorage.prototype.getStore.bind(scopedEnvContext);\n let realEnv: NodeJS.ProcessEnv = process.env;\n // Pushed before each non-proxy reassignment, popped when the proxy itself is assigned back\n // — implements `const saved = process.env; ...; process.env = saved;` correctly for\n // arbitrarily nested save/restore, not just a no-op that leaves realEnv stuck mid-swap.\n const realEnvHistory: NodeJS.ProcessEnv[] = [];\n const activeScopeTokens = new Set<symbol>();\n let savedExcludeEnv: boolean | undefined;\n // Captured once, from the first real FileHandle fs.promises.open() ever returns — the same\n // reference read()/readFile()/readv()'s own guards use, shared here so extractFdNumber's\n // cross-check for fs.promises.readFile(handle) and createReadStream's options.fd survives\n // this file's own re-evaluation (bundled copies, Jest's per-test-file isolation).\n let cachedNativeFdGetter: (() => number) | undefined;\n let nativeFdGetterCaptured = false;\n\n function currentEnv(): Record<string, string> | NodeJS.ProcessEnv {\n return nativeGetStore() ?? realEnv;\n }\n\n // process.report.excludeEnv already has a native getter/setter on Node >=22.13.0 — this\n // wraps it so an armed scope can't be disarmed with `process.report.excludeEnv = false`\n // from inside itself. On older Node (CI pins 20.19.4) there's no real accessor to wrap, but\n // a plain shadow variable still keeps read/write consistent even though it has no effect on\n // report generation on that version either way.\n const nativeExcludeEnvDescriptor = Object.getOwnPropertyDescriptor(\n process.report,\n 'excludeEnv',\n );\n let getExcludeEnv: () => boolean | undefined;\n let applyExcludeEnvValue: (newValue: boolean | undefined) => void;\n if (nativeExcludeEnvDescriptor?.get && nativeExcludeEnvDescriptor.set) {\n getExcludeEnv = nativeExcludeEnvDescriptor.get.bind(process.report);\n applyExcludeEnvValue = nativeExcludeEnvDescriptor.set.bind(process.report);\n } else {\n let excludeEnvValue: boolean | undefined = process.report.excludeEnv;\n getExcludeEnv = () => excludeEnvValue;\n applyExcludeEnvValue = (newValue) => {\n excludeEnvValue = newValue;\n };\n }\n\n function restoreExcludeEnvIfLastScope(): void {\n if (activeScopeTokens.size === 0) {\n applyExcludeEnvValue(savedExcludeEnv);\n savedExcludeEnv = undefined;\n }\n }\n\n Object.defineProperty(process.report, 'excludeEnv', {\n configurable: false,\n enumerable: true,\n get: getExcludeEnv,\n set: (newValue: boolean | undefined) => {\n if (nativeGetStore() !== undefined) {\n throw new Error(\n \"Reassigning process.report.excludeEnv is not allowed in backend functions — it would let a backend function's own diagnostic report include the dev server's real environment. This is armed automatically for the duration of the function's execution.\",\n );\n }\n if (activeScopeTokens.size > 0) {\n // An unrelated caller writing from outside any scope while a DIFFERENT scope is\n // still active elsewhere — applying it immediately would disarm redaction out\n // from under that scope, so it's deferred instead. Applied and immediately\n // reverted here (rather than just stashed) so Node's own setter validation still\n // runs now — an invalid value throws here instead of surfacing later,\n // misattributed to whichever scope's cleanup happens to apply it.\n const currentValue = getExcludeEnv();\n applyExcludeEnvValue(newValue);\n applyExcludeEnvValue(currentValue);\n savedExcludeEnv = newValue;\n return;\n }\n applyExcludeEnvValue(newValue);\n },\n });\n\n return {\n getCurrentEnv: currentEnv,\n isInsideScope: () => nativeGetStore() !== undefined,\n setRealEnvIfOutsideScope: (newValue) => {\n if (nativeGetStore() !== undefined) {\n throw new Error(\n \"Reassigning process.env is not allowed in backend functions — it would corrupt the dev server's real environment for every future execution. Use $.Source or a declared Custom Credential instead.\",\n );\n }\n if (typeof newValue !== 'object' || newValue === null) {\n // isEnvProxy() only ever returns true for an object, so without this check a\n // primitive assignment (process.env = 1, process.env = null) would store that\n // primitive as realEnv — every later unscoped access then calls\n // Reflect.get/ownKeys on it and throws, permanently breaking process.env.\n throw new Error(\n 'Reassigning process.env to a non-object value is not allowed — it would permanently break every future process.env access.',\n );\n }\n realEnvHistory.push(realEnv);\n realEnv = newValue;\n },\n restoreRealEnvFromHistory: () => {\n if (realEnvHistory.length > 0) {\n realEnv = realEnvHistory.pop() as NodeJS.ProcessEnv;\n }\n },\n runInScope: (scopedEnv, fn) => scopedEnvContext.run(scopedEnv, fn),\n armScope: () => {\n const token = Symbol('env-guard scope token');\n if (activeScopeTokens.size === 0) {\n savedExcludeEnv = getExcludeEnv();\n applyExcludeEnvValue(true);\n }\n activeScopeTokens.add(token);\n return token;\n },\n disarmScope: (token) => {\n // Set.delete() returns false when the token is already gone — e.g. forceResetEnv()\n // cleared every token first — meaning this scope's decrement/restore obligation was\n // already forcibly discharged, and the shared state now belongs to a later scope.\n if (activeScopeTokens.delete(token)) {\n restoreExcludeEnvIfLastScope();\n }\n },\n forceResetAllScopes: () => {\n if (activeScopeTokens.size > 0) {\n activeScopeTokens.clear();\n restoreExcludeEnvIfLastScope();\n }\n },\n getExcludeEnv,\n getCachedNativeFdGetter: () => cachedNativeFdGetter,\n setCachedNativeFdGetterOnce: (getter) => {\n if (!nativeFdGetterCaptured) {\n cachedNativeFdGetter = getter;\n nativeFdGetterCaptured = true;\n }\n },\n };\n });\n}\n\nconst sharedState = getSharedState();\n\n// Symbol.for(), not a plain Symbol() or object-identity check — same cross-module-instance reasoning\n// as getSharedState() above: a reference-identity check would fail to recognize another evaluation's\n// already-installed Proxy as \"already one of these,\" and each would wrap the other's, looping the\n// get/ownKeys/etc. traps into each other forever.\nconst ENV_PROXY_MARKER = Symbol.for('@dd/apps-plugin/env-guard/scoped-env-proxy');\n\n// Re-checked on every fs.promises.open() call rather than trusted as a one-time-installed flag — a\n// stray jest.spyOn(...).mockRestore() elsewhere in the process, on the same shared FileHandle\n// prototype, can silently strip one of these wrappers without this file ever re-running to notice.\nconst FILE_HANDLE_READ_GUARD_MARKER = Symbol.for(\n '@dd/apps-plugin/env-guard/file-handle-read-guard',\n);\n\n// Takes `unknown`, not NodeJS.ProcessEnv: the setter below calls this on whatever a caller actually\n// assigns to process.env at runtime, which TypeScript's parameter typing can't constrain — a bare\n// `Reflect.get(value, ...)` throws for null/undefined/primitives, which would surface as a confusing\n// native TypeError instead of either this file's own clear rejection message or a graceful no-op.\nfunction isEnvProxy(value: unknown): boolean {\n return (\n typeof value === 'object' && value !== null && Reflect.get(value, ENV_PROXY_MARKER) === true\n );\n}\n\n// Shared by every Proxy trap below that does nothing but forward to sharedState.getCurrentEnv()\n// with no extra logic of its own — get/has are hand-written instead, since both also\n// short-circuit ENV_PROXY_MARKER.\nfunction forwardToCurrentEnv<Args extends unknown[], R>(\n reflectFn: (env: Record<string, string> | NodeJS.ProcessEnv, ...args: Args) => R,\n): (_target: NodeJS.ProcessEnv, ...args: Args) => R {\n return (_target, ...args) => {\n const env = sharedState.getCurrentEnv();\n return reflectFn(env, ...args);\n };\n}\n\n// util.inspect()/console.log() read a Proxy's target directly via V8's getProxyDetails, bypassing\n// every trap below — with the real env as target, that would leak it straight through a bare\n// console.log(process.env) inside a scope. An always-empty, always-extensible dummy target closes\n// this: Proxy invariants only constrain traps when the target is non-extensible or holds\n// non-configurable properties, never true here, so every trap still resolves through\n// getCurrentEnv() as before.\nconst INERT_PROXY_TARGET = {} as NodeJS.ProcessEnv;\n// Re-checked on every runWithScopedEnv call rather than installed once and assumed permanent, since\n// isEnvProxy() is what actually detects \"is this already installed\" — the accessor property below\n// makes a bare `process.env = X` (rather than a call through this function) impossible to reach the\n// real Proxy install path with, but this function still needs to stay idempotent across every\n// evaluation of this file (bundled copies, Jest's per-test-file isolation) that calls it.\nfunction ensureEnvProxyInstalled(): void {\n if (isEnvProxy(process.env)) {\n return;\n }\n const proxy = new Proxy(INERT_PROXY_TARGET, {\n get: (_target, prop, receiver) => {\n if (prop === ENV_PROXY_MARKER) {\n return true;\n }\n const env = sharedState.getCurrentEnv();\n return Reflect.get(env, prop, receiver);\n },\n // Not forwardToCurrentEnv(Reflect.set): a plain `process.env[key] = value` passes the Proxy\n // itself as `receiver`, which for an existing writable property falls back to a PARTIAL\n // descriptor that Node's native process.env binding rejects outright. Omitting `receiver`\n // from Reflect.set defaults it to `env` itself, resolving as a direct set instead.\n set: (_target, prop, value) => Reflect.set(sharedState.getCurrentEnv(), prop, value),\n has: (_target, prop) => {\n const env = sharedState.getCurrentEnv();\n return prop === ENV_PROXY_MARKER || Reflect.has(env, prop);\n },\n deleteProperty: forwardToCurrentEnv(Reflect.deleteProperty),\n ownKeys: forwardToCurrentEnv(Reflect.ownKeys),\n getOwnPropertyDescriptor: forwardToCurrentEnv(Reflect.getOwnPropertyDescriptor),\n // A non-configurable definition can never be forwarded: the Proxy invariant requires\n // `target` (INERT_PROXY_TARGET, always empty) to carry that exact property afterward, which\n // it deliberately never does. Checked upfront rather than left to surface as Reflect's own\n // invariant-violation TypeError, which gives no hint this guard is involved. Accepted gap:\n // locking an env var non-configurable stops working process-wide once local execution has\n // run once, in exchange for `console.log(process.env)` never bypassing the scope via V8's\n // getProxyDetails (see INERT_PROXY_TARGET's own comment).\n defineProperty: (_target, prop, descriptor) => {\n if (descriptor.configurable === false) {\n throw new Error(\n `Cannot define a non-configurable property (${String(prop)}) on process.env: local execution's environment scoping requires every property to stay configurable.`,\n );\n }\n return Reflect.defineProperty(sharedState.getCurrentEnv(), prop, descriptor);\n },\n // Without this trap, Object.setPrototypeOf(process.env, ...) defaults to forwarding to\n // `target` (INERT_PROXY_TARGET, not the real env) and silently poisons its prototype chain\n // instead, even when called from inside a scope — getCurrentEnv() only affects property\n // access, not the object identity a prototype mutation lands on.\n setPrototypeOf: forwardToCurrentEnv(Reflect.setPrototypeOf),\n // Paired with setPrototypeOf above: without this trap, a customer function that sets a\n // scoped prototype and immediately reads it back would see `target`'s (INERT_PROXY_TARGET's)\n // untouched prototype instead of the one it just set on the scoped view.\n getPrototypeOf: forwardToCurrentEnv(Reflect.getPrototypeOf),\n // Can't forward to getCurrentEnv(): the Proxy invariant only honors this trap returning `true`\n // if `target` (INERT_PROXY_TARGET, not the real env) is also non-extensible, and freezing it\n // would break every other trap's scoped view. Refusing outright is the only option that\n // doesn't leak real-env state or break the proxy.\n preventExtensions: () => false,\n });\n // process.env must be an accessor property, not the plain data property it started as — a bare\n // `process.env = X` replaces `process`'s own `env` property outright, bypassing every Proxy\n // trap above, and the next runWithScopedEnv call would silently adopt that customer-controlled\n // object as the new realEnv fallback for every later execution. configurable: false so nothing\n // can strip this accessor back to a plain data property.\n Object.defineProperty(process, 'env', {\n configurable: false,\n enumerable: true,\n get: () => proxy,\n set: (newValue: NodeJS.ProcessEnv) => {\n // Self-assignment: something captured process.env (getting this same proxy back, e.g.\n // a test's own `const saved = process.env; ...; process.env = saved;` restore pattern)\n // and wrote it back. Restoring the pre-swap value from history — rather than a no-op —\n // makes this correct; adopting the proxy itself as the real env instead would make every\n // future unscoped read recurse back through this same trap forever.\n if (isEnvProxy(newValue)) {\n sharedState.restoreRealEnvFromHistory();\n return;\n }\n sharedState.setRealEnvIfOutsideScope(newValue);\n },\n });\n}\nensureEnvProxyInstalled();\n\n// /proc/thread-self resolves to /proc/self/task/<tid>, hence the optional /task/<tid> segment.\n// Matches any numeric pid, not just process.pid: a parent process (e.g. the shell that launched\n// the dev server) inherits the same secrets, and there's no legitimate reason a backend function\n// reads any process's environ file during a scoped execution.\nconst ENVIRON_PATH_RE = /^\\/proc\\/(self|thread-self|\\d+)(\\/task\\/\\d+)?\\/environ$/;\n\n// Structural check, not `instanceof Error`: Node's native fs errors can cross a realm boundary\n// (e.g. Jest's per-test-file VM sandboxing) where `instanceof Error` is false even though the\n// object is a genuine error with a real `.code`, which would otherwise silently misroute a normal\n// ENOENT into a fail-closed branch instead of its intended graceful fallback.\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return typeof error === 'object' && error !== null && 'code' in error;\n}\n\n// fs path arguments can legally be a string, a Buffer, or a file:// URL — checking only the string\n// case let a Buffer/URL argument to any of the guarded functions bypass the check entirely.\nfunction toPathString(rawPath: unknown): string | undefined {\n if (typeof rawPath === 'string') {\n return rawPath;\n }\n if (Buffer.isBuffer(rawPath)) {\n // Buffer.prototype.toString.call, not rawPath.toString(): a customer-controlled instance can\n // override its own toString to report a benign path while Node's native fs call still reads\n // the real, unmodified bytes.\n return Buffer.prototype.toString.call(rawPath);\n }\n if (rawPath instanceof URL) {\n return fileURLToPath(rawPath);\n }\n if (typeof rawPath === 'number' && process.platform === 'linux') {\n // fs.readFileSync/open and friends also accept an already-open fd in place of a path —\n // /proc/self/fd/<fd> is a Linux-only symlink to whatever that fd actually points at, letting\n // the realpath resolution below see through it the same way it does for a literal symlink\n // path. Only ENOENT falls back to \"not path-like\"; any other failure (EACCES, ELOOP, ...)\n // is re-thrown rather than treating an unverifiable fd as safe.\n try {\n return nativeReadlinkSync(`/proc/self/fd/${rawPath}`);\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n return undefined;\n }\n throw error;\n }\n }\n return undefined;\n}\n\nfunction isEnvironPath(rawPath: unknown): boolean {\n const pathString = toPathString(rawPath);\n if (pathString === undefined) {\n return false;\n }\n // Resolved via realpathSync first, not just normalized: fs.readFileSync and friends follow\n // symlinks transparently, so a symlink pointing at /proc/.../environ would otherwise bypass a\n // literal-string match. Falls back to normalize-only on ENOENT (a nonexistent path can't be\n // /proc/.../environ). Any other realpathSync failure is re-thrown rather than silently treated\n // as a safe path — the real fs call would hit the identical error anyway.\n let resolvedPath: string;\n try {\n resolvedPath = nativeRealpathSync(pathString);\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n resolvedPath = nodePath.posix.normalize(pathString);\n } else {\n throw error;\n }\n }\n return ENVIRON_PATH_RE.test(resolvedPath);\n}\n\nconst ENVIRON_READ_BLOCKED_MESSAGE =\n \"Reading /proc/.../environ is not allowed in backend functions — it exposes the dev server's real, unscoped environment. Use $.Source or a declared Custom Credential instead.\";\n\n// Per-continuation, like getCurrentEnv() above, so it can't fire for unrelated code running\n// concurrently on a different, unscoped continuation. A pure predicate (rather than throwing\n// itself) so it can also serve as makeGuardWrapper's shouldBlock. extractFdNumber unwraps an\n// already-open FileHandle to the same numeric fd toPathString() resolves via /proc/self/fd, so a\n// FileHandle opened against /proc/.../environ before the scope is caught the same way.\nfunction isBlockedEnvironPath(rawPath: unknown): boolean {\n // Short-circuits before touching rawPath at all when no scope is active — extractFdNumber reads\n // a real FileHandle's native .fd getter, which callers outside any scope must never trigger.\n if (!sharedState.isInsideScope()) {\n return false;\n }\n const fdNumber = extractFdNumber(rawPath);\n return isEnvironPath(fdNumber);\n}\n\nfunction throwIfBlockedEnvironPath(rawPath: unknown): void {\n if (isBlockedEnvironPath(rawPath)) {\n throw new Error(ENVIRON_READ_BLOCKED_MESSAGE);\n }\n}\n\n// A FileHandle exposes its underlying fd as a plain number via its own .fd property. Cross-checked\n// against the same native getter readNativeFd()'s other callers use below, since this naive `.fd`\n// read is otherwise exactly the shadow TOCTOU those callers are already hardened against.\nfunction extractFdNumber(fdValue: unknown): unknown {\n if (typeof fdValue === 'object' && fdValue !== null && 'fd' in fdValue) {\n return readNativeFd(sharedState.getCachedNativeFdGetter(), fdValue as { fd: number });\n }\n return fdValue;\n}\n\n// Reads each of `keys` from a getter-backed options object exactly once, then rebuilds a plain\n// object where a key absent from the caller's own options stays absent — see guardCpOptions's own\n// comment for why re-adding an absent key as explicit `undefined` breaks Node's own cp validation.\n// Shared by guardEnvironPathOrFdOption (a single always-present key) and guardCpOptions (two\n// independently-optional keys): presence-conditional restore is correct for both, since a\n// guaranteed-present key just never hits the \"absent\" branch.\nfunction snapshotOptionKeysOnce<K extends string>(\n options: Record<string, unknown>,\n keys: readonly K[],\n): Record<string, unknown> {\n // Copying every OTHER own-enumerable key first, via Object.keys rather than a `{ ...options }`\n // spread, is what keeps this to exactly one read per snapshotted key below — a spread of the\n // full options object would invoke every key's getter once on its own, then a second time when\n // that same key is explicitly snapshotted next.\n const keySet = new Set<string>(keys);\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(options)) {\n if (!keySet.has(key)) {\n result[key] = options[key];\n }\n }\n for (const key of keys) {\n if (key in options) {\n result[key] = options[key];\n }\n }\n return result;\n}\n\n// createReadStream/ReadStream's options.fd (a raw fd number, or a FileHandle whose own .fd is one)\n// makes Node read from that fd directly, ignoring the leading path argument — a plain\n// throwIfBlockedEnvironPath(rawPath) would never see the real target. Returns a safe options\n// object rather than the caller's own: options.fd could be an accessor whose getter returns a\n// harmless value to this check and a different, real target to Node's own later read.\nfunction guardEnvironPathOrFdOption(rawPath: unknown, options: unknown): unknown {\n throwIfBlockedEnvironPath(rawPath);\n // No scope active means nothing here can be an environ read worth blocking — returning options\n // untouched (rather than destructuring/rebuilding it below) preserves whatever createReadStream/\n // ReadStream call a caller outside any scope makes, including non-enumerable or inherited\n // options properties a plain spread would otherwise silently drop.\n if (!sharedState.isInsideScope()) {\n return options;\n }\n if (typeof options !== 'object' || options === null || !('fd' in options)) {\n return options;\n }\n const snapshot = snapshotOptionKeysOnce(options as Record<string, unknown>, ['fd'] as const);\n throwIfBlockedEnvironPath(extractFdNumber(snapshot.fd));\n return snapshot;\n}\n\n// Every guarded fs entry point below except createReadStream takes only a leading path argument —\n// wraps that shared shape once via the same makeGuardWrapper network-guard.ts uses, with\n// isBlockedEnvironPath as an argument-dependent shouldBlock. Only for genuinely synchronous APIs,\n// where a guard failure throwing synchronously matches their real Node contract.\nfunction wrapGuardedFsFn<T extends (...args: never[]) => unknown>(real: T): T {\n return makeGuardWrapper(\n () => real,\n (rawPath) => isBlockedEnvironPath(rawPath),\n ENVIRON_READ_BLOCKED_MESSAGE,\n 'throw',\n );\n}\n\n// fs.promises.* functions must reject rather than throw synchronously on a guard failure, matching\n// their real Promise-returning contract. `onResolved`, if given, runs on the real, unguarded result\n// once resolved — used only by fs.promises.open below to patch FileHandle.prototype.read from the\n// first real handle it returns (see ensureFileHandleReadGuarded).\nfunction wrapGuardedAsyncFsFn<T extends (...args: never[]) => Promise<unknown>>(\n real: T,\n onResolved?: (result: unknown) => void,\n): T {\n const guarded = makeGuardWrapper(\n () => real,\n (rawPath) => isBlockedEnvironPath(rawPath),\n ENVIRON_READ_BLOCKED_MESSAGE,\n 'reject',\n );\n if (!onResolved) {\n return guarded;\n }\n const wrapped = async function (this: unknown, ...args: Parameters<T>): Promise<unknown> {\n const result = await (guarded as unknown as (...a: unknown[]) => Promise<unknown>).apply(\n this,\n args,\n );\n onResolved(result);\n return result;\n } as T;\n return wrapped;\n}\n\n// fs.readFile/open/copyFile/cp report failure via an error-first callback, never a synchronous\n// throw — routing them through wrapGuardedFsFn's 'throw' mode would violate that contract for a\n// caller that (correctly, per their real signature) never wraps the call itself in a try/catch.\nfunction wrapGuardedCallbackFsFn<T extends (...args: never[]) => unknown>(real: T): T {\n return makeGuardCallbackWrapper(\n () => real,\n (rawPath) => isBlockedEnvironPath(rawPath),\n ENVIRON_READ_BLOCKED_MESSAGE,\n );\n}\n\n// createReadStream is the one guarded entry point whose second (options) argument can itself carry\n// the real read target via options.fd, bypassing whatever the leading path argument says — every\n// other function this file guards only ever reads from its own leading path argument.\nfunction wrapGuardedStreamFn<T extends (...args: never[]) => unknown>(real: T): T {\n const wrapped = (...args: Parameters<T>): ReturnType<T> => {\n const safeOptions = guardEnvironPathOrFdOption(args[0], args[1]);\n const safeArgs = [args[0], safeOptions] as Parameters<T>;\n return real(...safeArgs) as ReturnType<T>;\n };\n return wrapped as T;\n}\n\n// Shared by every FileHandle prototype method patched below — re-checks proto[methodName] fresh on\n// every fs.promises.open() call rather than trusting a one-time flag, for the same reason\n// FILE_HANDLE_READ_GUARD_MARKER exists.\nfunction originalIfUnguarded(\n proto: Record<PropertyKey, unknown>,\n methodName: string,\n): ((...args: never[]) => unknown) | undefined {\n const original = proto[methodName];\n if (typeof original !== 'function') {\n return undefined;\n }\n if ((original as unknown as Record<PropertyKey, unknown>)[FILE_HANDLE_READ_GUARD_MARKER]) {\n return undefined;\n }\n return original as (...args: never[]) => unknown;\n}\n\nfunction markGuarded(fn: (...args: never[]) => unknown): void {\n (fn as unknown as Record<PropertyKey, unknown>)[FILE_HANDLE_READ_GUARD_MARKER] = true;\n}\n\n// A customer-controlled own property can shadow the prototype's real `fd` getter in either\n// direction — reporting a harmless value to this check while `original.apply` below reads the\n// real, dangerous fd, or the reverse. An untampered handle never carries an own `fd` property, so\n// any divergence between the naive and native reads is itself proof of tampering.\nfunction readNativeFd(nativeFdGetter: (() => number) | undefined, handle: { fd: number }): number {\n if (!nativeFdGetter) {\n return handle.fd;\n }\n const trueFd = nativeFdGetter.call(handle);\n if (handle.fd !== trueFd) {\n throw new Error(ENVIRON_READ_BLOCKED_MESSAGE);\n }\n return trueFd;\n}\n\n// A stateful accessor `fd` property can still defeat readNativeFd's own divergence check: return\n// the validated, harmless fd on the one read the check makes, then a different, dangerous fd on\n// Node's own later read(s) of the same property — read()/readFile()/readv() all re-read `handle.fd`\n// more than once over a single call's lifetime. Pinning `fd` as a plain, static-value own property\n// for the call's full async duration, restored to its original shape afterward, forces every read\n// to resolve the one validated value instead of a getter's shifting answer.\nasync function withPinnedFd<T>(handle: object, fd: number, fn: () => Promise<T>): Promise<T> {\n const hasOwnFd = Object.prototype.hasOwnProperty.call(handle, 'fd');\n const priorDescriptor = hasOwnFd ? Object.getOwnPropertyDescriptor(handle, 'fd') : undefined;\n Object.defineProperty(handle, 'fd', { value: fd, configurable: true, enumerable: true });\n try {\n return await fn();\n } finally {\n if (priorDescriptor) {\n Object.defineProperty(handle, 'fd', priorDescriptor);\n } else {\n delete (handle as Record<string, unknown>).fd;\n }\n }\n}\n\n// read()/readFile()/readv() all report failure via their own returned Promise, never a\n// synchronous throw.\nfunction patchFileHandleAsyncMethod(\n proto: Record<PropertyKey, unknown>,\n methodName: string,\n nativeFdGetter: (() => number) | undefined,\n): void {\n const original = originalIfUnguarded(proto, methodName);\n if (!original) {\n return;\n }\n const guarded = function (this: { fd: number }, ...args: never[]): unknown {\n // Skips readNativeFd entirely outside any scope — it calls the native .fd getter, which\n // unscoped callers must never trigger (see isBlockedEnvironPath's own short-circuit).\n if (!sharedState.isInsideScope()) {\n return original.apply(this, args);\n }\n let fd: number;\n try {\n fd = readNativeFd(nativeFdGetter, this);\n } catch (error) {\n return Promise.reject(error);\n }\n if (isBlockedEnvironPath(fd)) {\n return Promise.reject(new Error(ENVIRON_READ_BLOCKED_MESSAGE));\n }\n return withPinnedFd(this, fd, async () => original.apply(this, args));\n };\n markGuarded(guarded);\n proto[methodName] = guarded;\n}\n\n// createReadStream()/readableWebStream()/readLines() all construct and return their stream/iterator\n// synchronously — the actual reads happen lazily as the caller consumes it, but a guard failure on\n// the fd itself is known up front, so this matches their real, synchronous-return contract instead\n// of rejecting a promise no caller of these methods is expecting.\nfunction patchFileHandleSyncMethod(\n proto: Record<PropertyKey, unknown>,\n methodName: string,\n nativeFdGetter: (() => number) | undefined,\n): void {\n const original = originalIfUnguarded(proto, methodName);\n if (!original) {\n return;\n }\n const guarded = function (this: { fd: number }, ...args: never[]): unknown {\n if (!sharedState.isInsideScope()) {\n return original.apply(this, args);\n }\n const fd = readNativeFd(nativeFdGetter, this);\n if (isBlockedEnvironPath(fd)) {\n throw new Error(ENVIRON_READ_BLOCKED_MESSAGE);\n }\n return original.apply(this, args);\n };\n markGuarded(guarded);\n proto[methodName] = guarded;\n}\n\n// FileHandle isn't part of Node's public API, so read/readFile/readv/createReadStream/\n// readableWebStream/readLines are patched lazily off the first real handle fs.promises.open()\n// returns — a handle obtained before that patch installs is unaffected, matching every other guard\n// here. These six are distinct prototype methods that don't delegate to each other, so each needs\n// its own patch; guarding .read() alone would leave the other five as unguarded, direct reads of\n// the real fd.\nfunction ensureFileHandleReadGuarded(handle: unknown): void {\n if (typeof handle !== 'object' || handle === null) {\n return;\n }\n const proto = Object.getPrototypeOf(handle) as Record<PropertyKey, unknown>;\n // Read once here, from the first real handle fs.promises.open() ever returns — before any\n // customer code has had a chance to install its own instance-level `fd` on some later handle.\n const nativeFdGetter = Object.getOwnPropertyDescriptor(proto, 'fd')?.get as\n | (() => number)\n | undefined;\n sharedState.setCachedNativeFdGetterOnce(nativeFdGetter);\n patchFileHandleAsyncMethod(proto, 'read', nativeFdGetter);\n patchFileHandleAsyncMethod(proto, 'readFile', nativeFdGetter);\n patchFileHandleAsyncMethod(proto, 'readv', nativeFdGetter);\n patchFileHandleSyncMethod(proto, 'createReadStream', nativeFdGetter);\n patchFileHandleSyncMethod(proto, 'readableWebStream', nativeFdGetter);\n // readLines() returns a readline Interface synchronously — the real reads happen lazily as the\n // caller iterates it, same reasoning as createReadStream()/readableWebStream() above.\n patchFileHandleSyncMethod(proto, 'readLines', nativeFdGetter);\n}\n\n// open/openSync/promises.open are separate entry points that map a path to a file descriptor\n// without going through readFile*, so they need the same guard.\nfs.readFileSync = wrapGuardedFsFn(fs.readFileSync);\nfs.readFile = wrapGuardedCallbackFsFn(fs.readFile);\nfs.promises.readFile = wrapGuardedAsyncFsFn(fs.promises.readFile);\nfs.createReadStream = wrapGuardedStreamFn(fs.createReadStream);\nfs.openSync = wrapGuardedFsFn(fs.openSync);\nfs.open = wrapGuardedCallbackFsFn(fs.open);\nfs.promises.open = wrapGuardedAsyncFsFn(fs.promises.open, ensureFileHandleReadGuarded);\n\n// openAsBlob is its own entry point, separate from open*/readFile* above, and absent on Node 18.\n// Feature-detected the same way packages/core/src/helpers/fs.ts's getFile() already checks for it\n// — an unconditional assignment here would replace that check's `undefined` with an always-defined\n// wrapper, silently forcing every Node 18 caller onto the unsupported branch.\nif (typeof fs.openAsBlob === 'function') {\n fs.openAsBlob = wrapGuardedAsyncFsFn(fs.openAsBlob);\n}\n\n// read/readSync/readv/readvSync take an already-open fd as their own leading argument — the same\n// shape isBlockedEnvironPath's toPathString() already resolves via /proc/self/fd for the numeric-fd\n// case above, just on entry points that were never wrapped at all.\nfs.read = wrapGuardedCallbackFsFn(fs.read);\nfs.readSync = wrapGuardedFsFn(fs.readSync);\nfs.readv = wrapGuardedCallbackFsFn(fs.readv);\nfs.readvSync = wrapGuardedFsFn(fs.readvSync);\n\n// copyFileSync/copyFile/promises.copyFile read the source file's bytes through a distinct native\n// binding that never calls through readFile*/open* above — an uncovered path that could otherwise\n// copy /proc/.../environ to an ordinary, unguarded file and read it back from there.\nfs.copyFileSync = wrapGuardedFsFn(fs.copyFileSync);\nfs.copyFile = wrapGuardedCallbackFsFn(fs.copyFile);\nfs.promises.copyFile = wrapGuardedAsyncFsFn(fs.promises.copyFile);\n\n// cp/cpSync/promises.cp additionally need to reject a recursive+dereference copy of ANY directory\n// (see guardCpOptions's own comment) — a check the plain isBlockedEnvironPath(src) check above\n// can't cover, since it only ever inspects the top-level source argument.\nconst CP_BLOCKED_MESSAGE =\n \"Copying /proc/.../environ, or recursively copying with dereference: true, is not allowed in backend functions — both can expose the dev server's real, unscoped environment. Use $.Source or a declared Custom Credential instead.\";\n\n// Snapshots options.recursive/dereference into plain data properties, read exactly once — the\n// generic makeGuardWrapper machinery forwards a caller's original options object unchanged, which\n// would let a getter-backed recursive/dereference report false here and true when Node's own\n// fs.cp* reads it again internally, letting a symlinked /proc/.../environ get dereferenced and\n// copied through undetected. Same TOCTOU reasoning as guardEnvironPathOrFdOption's options.fd\n// handling above; hand-rolled here since arg transformation isn't something makeGuardWrapper\n// supports.\nfunction guardCpOptions(options: unknown): unknown {\n if (!sharedState.isInsideScope()) {\n return options;\n }\n if (typeof options !== 'object' || options === null) {\n return options;\n }\n // Node's cp implementations distinguish an absent key (defaulted internally) from one\n // explicitly present with value `undefined` (rejected by its own validation), so\n // snapshotOptionKeysOnce restoring both keys unconditionally would turn a caller's\n // `{ recursive: true }` (no dereference key at all) into `{ recursive: true, dereference:\n // undefined }` and throw a validation error that never happens when the real options object is\n // forwarded as-is — this is why it only re-adds keys actually present on the caller's options.\n const safeOptions = snapshotOptionKeysOnce(\n options as Record<string, unknown>,\n ['recursive', 'dereference'] as const,\n );\n if (safeOptions.recursive === true && safeOptions.dereference === true) {\n throw new Error(CP_BLOCKED_MESSAGE);\n }\n return safeOptions;\n}\n\n// Captured into local consts before reassignment below — a lazy `() => fs.cpSync` getter would\n// re-read the property AFTER it's replaced with this very wrapper, recursing into itself forever.\nconst originalCpSync = fs.cpSync;\nconst originalCp = fs.cp;\nconst originalPromisesCp = fs.promises.cp;\n\n// cpSync is genuinely synchronous — a guard failure throwing matches its real contract. `this`\n// is forwarded via .apply, matching every other guarded fs entry point in this file — Node's own\n// implementations don't consult it, but nothing here should be the one silent exception.\nfs.cpSync = function (this: unknown, src: unknown, dest: unknown, options?: unknown) {\n throwIfBlockedEnvironPath(src);\n const safeOptions = guardCpOptions(options) as fs.CopySyncOptions;\n return originalCpSync.apply(this, [src as string | URL, dest as string | URL, safeOptions]);\n} as typeof fs.cpSync;\n\n// cp reports failure via an error-first callback, never a synchronous throw. Only the guard's own\n// decision logic runs inside the try/catch — the real call runs outside it, so a synchronous throw\n// from Node's own validation propagates normally instead of being swallowed by invokeCallbackArg\n// when a malformed call has no valid callback to report through.\nfs.cp = function (this: unknown, src: unknown, dest: unknown, ...rest: unknown[]) {\n let safeArgs: unknown[];\n try {\n throwIfBlockedEnvironPath(src);\n const hasOptions = rest.length > 1;\n const safeOptions = hasOptions ? guardCpOptions(rest[0]) : undefined;\n safeArgs = hasOptions ? [src, dest, safeOptions, ...rest.slice(1)] : [src, dest, ...rest];\n } catch (error) {\n invokeCallbackArg(\n [src, dest, ...rest],\n error instanceof Error ? error : new Error(String(error)),\n );\n return undefined;\n }\n return (originalCp as unknown as (...a: unknown[]) => unknown).apply(this, safeArgs);\n} as typeof fs.cp;\n\n// promises.cp rejects, matching its real Promise-returning contract.\nfs.promises.cp = async function (this: unknown, src: unknown, dest: unknown, options?: unknown) {\n throwIfBlockedEnvironPath(src);\n const safeOptions = guardCpOptions(options) as fs.CopyOptions;\n return originalPromisesCp.apply(this, [src as string | URL, dest as string | URL, safeOptions]);\n} as typeof fs.promises.cp;\n\n// createReadStream's own wrap above only covers that factory function — Node also exports the\n// ReadStream class it constructs internally, and `new fs.ReadStream(path)` never calls through\n// createReadStream at all. @types/node declares no explicit constructor for ReadStream (it inherits\n// Readable's), so a subclass can't be typed against its real (path, options) signature — a Proxy's\n// construct trap guards the same entry point without needing that signature at all. `new Proxy<T>`\n// is itself typed to return T given a T target, so no cast is needed on the assignment either.\nfs.ReadStream = new Proxy(fs.ReadStream, {\n construct(target, args, newTarget) {\n const safeOptions = guardEnvironPathOrFdOption(args[0], args[1]);\n return Reflect.construct(target, [args[0], safeOptions], newTarget);\n },\n});\n\n// @types/node doesn't declare fs.FileReadStream at all, even though Node itself still exports it.\n// `let`, not `const` — ReadStream itself is declared as a class (an assignable binding, matching\n// the reassignment already made above), and this needs to be assignable too.\ndeclare module 'fs' {\n // no-undef doesn't understand module-augmentation scoping (ReadStream is 'fs's own ambient\n // class, visible here without an import); import/no-mutable-exports doesn't apply either — this\n // `let` declares the shape of the 'fs' module's own property, not a real value this file exports.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-undef, import/no-mutable-exports\n export let FileReadStream: typeof ReadStream;\n}\n\n// fs.FileReadStream is a real, long-deprecated alias for fs.ReadStream — reassigning fs.ReadStream\n// only rebinds that one property; fs.FileReadStream is a separate slot that keeps pointing at the\n// original, unwrapped class, so `new fs.FileReadStream(path)` would construct through it with no\n// guard at all.\nfs.FileReadStream = fs.ReadStream;\n\n// @types/node doesn't declare excludeEnv yet. It's real, but only wired up to the native report\n// generator from Node v22.13.0 — CI pins Node 20.19.4, where setting it is a no-op. Kept anyway:\n// on versions that support it, it also redacts reports Node generates on its own via\n// --report-on-fatalerror/--report-on-signal, which the getReport()/writeReport() wraps below can't\n// reach since no JS call happens for those. Augmented globally so every consumer shares one\n// canonical type instead of independently-typed `as unknown as` casts.\ndeclare global {\n namespace NodeJS {\n interface ProcessReport {\n excludeEnv?: boolean;\n }\n }\n}\n\ntype ReportLike = Record<string, unknown> & { environmentVariables?: unknown };\n\n// process.report.getReport()'s declared return type is a bare `object`, carrying no shape\n// information — this predicate narrows it without an `as` cast.\nfunction hasEnvironmentVariables(report: object): report is ReportLike {\n return 'environmentVariables' in report;\n}\n\n// Preserves the original's exact (possibly-overloaded) type on the returned wrapper, the same\n// reasoning as wrapGuardedFsFn/wrapGuardedAsyncFsFn above, so getReport/writeReport below can\n// reassign with no cast — `implementation` receives the original as its first argument rather than\n// closing over it, since each wrap's own logic differs and can't share one generic body.\nfunction wrapReportFn<T extends (...args: never[]) => unknown>(\n original: T,\n implementation: (original: T, ...args: Parameters<T>) => ReturnType<T>,\n): T {\n const wrapped = (...args: Parameters<T>): ReturnType<T> => implementation(original, ...args);\n return wrapped as T;\n}\n\n// Strips environmentVariables at the JS level so a customer function's own getReport()/\n// writeReport() call is redacted on every supported Node version, not just where excludeEnv is\n// wired up. writeReport() lets Node handle filename generation/defaults as normal, then\n// post-processes the file it actually wrote rather than reimplementing its naming convention.\n// Gated on sharedState.isInsideScope(), not a global scope count — forceResetEnv() clears the\n// count for an abandoned execution whose fn() is still running, and keying redaction on that count\n// would let the zombie's own getReport()/writeReport() call see the real environment the moment the\n// count resets, even though its own continuation never actually closed.\nconst originalGetReport = process.report.getReport.bind(process.report);\nprocess.report.getReport = wrapReportFn(originalGetReport, (original, ...args) => {\n const report = original(...args);\n if (sharedState.isInsideScope() && hasEnvironmentVariables(report)) {\n delete report.environmentVariables;\n }\n return report;\n});\n\n// writeReport(fileName) can target a non-regular destination — a FIFO, socket, or character device\n// like /dev/stdout — and Node writes the real, unredacted report straight there before this wrap\n// can read it back and strip environmentVariables. Redacting after the fact can't undo bytes\n// already delivered to whatever's reading the other end, so refusing the call once the destination\n// is verified non-regular is the only option that can't leak.\nconst WRITE_REPORT_NON_REGULAR_SINK_MESSAGE =\n \"process.report.writeReport() to a non-regular destination (a pipe, socket, or similar) is not allowed in backend functions — Node would write its real, unscoped report there before this file's own redaction could ever run. Use $.Source or a declared Custom Credential instead.\";\n\n// A not-yet-existing path is fine — writeReport creates a fresh, ordinary regular file there —\n// so ENOENT is the one failure treated as \"not a non-regular sink,\" matching isEnvironPath's own\n// identical ENOENT fallback elsewhere in this file. fs.statSync follows symlinks on its own,\n// unlike lstatSync, so a symlink pointing at a FIFO is resolved to its real target automatically.\nfunction isVerifiedNonRegularDestination(filePath: string): boolean {\n try {\n return !fs.statSync(filePath).isFile();\n } catch (error) {\n if (isErrnoException(error) && error.code === 'ENOENT') {\n return false;\n }\n throw error;\n }\n}\n\nconst originalWriteReport = process.report.writeReport.bind(process.report);\nprocess.report.writeReport = wrapReportFn(originalWriteReport, (original, ...args) => {\n if (sharedState.isInsideScope()) {\n // writeReport(fileName?, err?) also accepts writeReport(err?) with no fileName at all —\n // only a string first argument is ever a caller-chosen destination, so this branch is\n // skipped (falling through to Node's own write below) when none was given.\n // Checked as the last statement before the real write, not earlier in this function: an\n // external process could swap a symlink at fileNameArg between this check and the write\n // below. This doesn't close that window entirely (the write is still a separate syscall\n // right after), but narrows it to two back-to-back synchronous calls with nothing between.\n const fileNameArg = args[0];\n if (typeof fileNameArg === 'string') {\n if (isVerifiedNonRegularDestination(fileNameArg)) {\n throw new Error(WRITE_REPORT_NON_REGULAR_SINK_MESSAGE);\n }\n // Builds the redacted report itself and writes it directly, rather than letting Node\n // persist the real report first and rewriting it after — that would leave unredacted\n // content on disk if anything between the two writes throws. Cast: TS collapses the\n // bound writeReport's overloads to `(err?: Error)`, so the real err arg needs restating.\n const errArg = (args as unknown as [string?, Error?])[1];\n const report = originalGetReport(errArg) as ReportLike;\n delete report.environmentVariables;\n fs.writeFileSync(fileNameArg, JSON.stringify(report, null, 2));\n return fileNameArg;\n }\n }\n const filename = original(...args);\n if (sharedState.isInsideScope()) {\n const rawReport = fs.readFileSync(filename, 'utf8');\n const report: ReportLike = JSON.parse(rawReport);\n delete report.environmentVariables;\n const serializedReport = JSON.stringify(report, null, 2);\n fs.writeFileSync(filename, serializedReport);\n }\n return filename;\n});\n\n// installGuardedProperty in network-guard.ts only patches the CJS-style default-export object;\n// Node keeps ESM named bindings (e.g. `import { readFileSync } from 'node:fs'`) as separate\n// references that stay bound to the original native functions otherwise.\nsyncBuiltinESMExports();\n\nexport interface EnvScopeHandle {\n // Discharges this specific call's own token, safe to call even while a different scope is\n // still active — unlike forceResetEnv(), it never touches a token it doesn't own.\n abandon(): void;\n}\n\n// Wraps only the customer function's own call in local-execution.ts's runScriptLocally, matching\n// runBlocked's scope exactly. `onScopeStarted`, if given, is invoked synchronously with a handle\n// scoped to *this* call, for a caller whose own timeout might fire while `fn` is still pending.\nexport async function runWithScopedEnv<T>(\n scopedEnv: Record<string, string>,\n fn: () => Promise<T>,\n onScopeStarted?: (handle: EnvScopeHandle) => void,\n): Promise<T> {\n ensureEnvProxyInstalled();\n const token = sharedState.armScope();\n onScopeStarted?.({ abandon: () => sharedState.disarmScope(token) });\n try {\n return await sharedState.runInScope(scopedEnv, fn);\n } finally {\n sharedState.disarmScope(token);\n }\n}\n\n// Test-only escape hatch for resetting shared module state between tests — unconditional, unlike\n// EnvScopeHandle.abandon(), since a test fully controls when scopes start and end. Production code\n// discharges a specific hung scope via that handle instead, since this would otherwise also disarm\n// a different, still-active execution's own scope.\nexport function forceResetEnv(): void {\n sharedState.forceResetAllScopes();\n}\n"],"names":["INJECTED_FILE","INJECTED_FILE_RX","RegExp","ALL_ENVS","SITES","DEFAULT_SITE","HOST_NAME","green","chalk","bold","yellow","OVERRIDE_VARIABLES","getDDEnvValue","key","process","env","getUsedKey","usedKeys","push","resolveSite","value","source","errors","parsed","lowerValue","toLowerCase","exactMatch","find","s","site","suffixMatches","filter","endsWith","length","reduce","longest","subdomain","slice","test","parseSite","validateOptions","options","metadata","version","validateMetadata","normalizedOptions","sourcemaps","Array","isArray","runtimeOptions","debugId","upload","some","option","rum","sourceCodeContext","enable","errorTracking","normalized","bailOnError","dryRun","maxConcurrency","normalizeSourcemapsOptions","envRaw","resolvedSite","auth","Error","join","Object","defineProperty","apiKey","enumerable","appKey","enableGit","logLevel","formatErrorEntry","e","entries","map","JSON","stringify","ERROR_CODES_NO_RETRY","doRequest","async","opts","url","method","getData","type","onResponse","signal","fetchImpl","fetch","retryOpts","retries","onRetry","maxTimeout","minTimeout","retry","bail","attempt","response","requestInit","duplex","requestHeaders","accessToken","Authorization","data","headers","body","error","ok","errorMessage","status","statusText","details","bodyText","parse","entry","parseErrorDetails","text","includes","result","json","getSendLog","message","context","payload","ddsource","packageName","service","team","bundler","name","cleanPluginName","replace","isInjectionFile","filename","serializeBuildReport","report","jsonReport","warnings","logs","timings","start","end","duration","writeDuration","inputs","outputs","newEntry","file","filepath","input","newInput","dependencies","dependents","dependency","dependent","output","newOutput","shouldGetGitInfo","gitEnabledFromSourcemaps","gitEnabledFromRoot","formatDuration","days","Math","floor","d","Date","hours","getUTCHours","minutes","getUTCMinutes","seconds","getUTCSeconds","milliseconds","getUTCMilliseconds","timeString","trim","truncateString","str","maxLength","placeholder","stringLength","max","leftStop","min","rightStop","filterSensitiveInfoFromRepositoryUrl","repositoryUrl","startsWith","URL","cleanPath","pathname","protocol","host","normalizeTagValue","prettyObject","obj","String","toString","formatValue","logPriority","debug","info","warn","none","cleanName","split","getLogFn","stores","cleanedName","forward","color","c","dim","logFn","console","log","red","cyan","prefix","content","pluginName","time","now","forwardLog","sendLog","plugin","subLogger","queue","getTimeLogger","store","label","level","toLog","tags","timer","spans","total","getUncompleteSpans","span","resume","startTime","pause","pauseTime","uncompleteSpans","param","endTime","acc","tag","tagsToAdd","tagOpts","uncompleteSpan","getLoggerFactory","getLogger","subName","logger","HOOKS_TO_TRACE","wrapHook","hookName","hook","wrapWithTiming","fn","args","apply","this","Promise","finally","handler","wrapGetPlugins","getPlugins","arg","initTimer","wrappedPlugins","wrappedPlugin","wrapPlugin","pluginNames","warnedKeys","Set","resolveEnable","configKey","pluginConfig","has","add","CONFIG_KEY","PLUGIN_NAME","ARCHIVE_FILENAME","BACKEND_FILE_RE","LOCAL_EXECUTION_LOAD_SUFFIX","BACKEND_FILE_WITH_QUERY_RE","BACKEND_CODE_EXTENSIONS","resolveLongPolling","longPolling","maxRetries","timeoutMs","Number","isInteger","isFinite","jitter","exponentialBackoff","rm","dir","fsp","force","recursive","mkdir","outputFileSync","path","dirname","fs","mkdirSync","writeFileSync","encoding","readFile","existsSync","code","getFile","openAsBlob","blob","contentType","File","stream","Readable","toWeb","createReadStream","Response","checkFile","filePath","validity","empty","exists","size","stat","InjectPosition","networkGuardModule","getNetworkGuard","resolve","then","networkGuard","catch","err","AUTH_GUIDANCE","MissingAuthenticationError","constructor","super","statusCode","ensureProgram","node","isProgramNode","hasNodeType","isStringLiteral","isTypeOnly","importKind","exportKind","isVariableDeclaratorNode","staticStringValue","expressions","quasis","isNoSubstitutionTemplateLiteral","cooked","extractExportedFunctions","ast","program","declarations","Map","id","set","kind","init","spec","specifiers","local","buildDeclarationMap","backendExports","declaration","namesFromDeclaration","localName","exported","validateSpecifierBinding","enumerateBackendExports","backendExport","NON_CALLABLE_INIT_TYPES","isNonCallableInit","decl","flatMap","get","walkAst","state","visitors","visit","currentNode","_","getSpecializedVisitor","keys","visitChildren","item","isAstNode","analyzeModuleScope","child","nodeWithRange","range","scopeManager","eslintScope","analyze","ecmaVersion","ignoreEval","sourceType","referencesByIdentifier","scope","scopes","reference","references","identifier","moduleScope","getModuleScope","resolveIdentifier","scopeAnalysis","resolved","isImportVariable","variable","defs","definition","getModuleVariable","globalScope","findActionCatalogCallSites","callState","unsupportedAliases","collectUnsupportedActionCatalogAliases","callSites","CallExpression","callee","resolvesTo","unsupportedActionCatalogCall","actionFunctions","optional","isNamespaceMember","hasUnsupportedMemberAccess","classifyActionCatalogCall","VariableDeclarator","aliasVariable","getDeclaredVariables","actionNamespaces","aliasNames","properties","property","computed","collectPatternIdentifiers","getActionCatalogAliasVariables","AssignmentExpression","left","right","getResolvedVariables","aliasIdentifiers","getAssignedActionCatalogAliasVariables","root","getMemberExpressionRoot","object","variables","resolvesToModuleVariable","identifiers","names","wantedNames","pattern","argument","elements","element","unsupported","ACTION_CATALOG_PACKAGE","resolveStaticDefinitionForIdentifier","modules","moduleId","record","unsupportedMissingModuleRecordForVariable","isDefinitionIdentifier","unsupportedUnresolvedIdentifier","resolveVariable","visitedExports","resolveExport","exportName","hops","reason","requestKind","unsupportedMissingModuleRecordForExport","unsupportedDefaultExport","visitKey","unsupportedCycle","explicitExport","exportsByName","binding","exportReason","unsupportedExport","importedName","resolvedId","sourceModuleId","sourceExportName","resolveExplicitExport","candidate","starExport","starExports","isSameLocalDefinition","unsupportedAmbiguousStarExport","unsupportedMissingExport","resolveStarExport","delete","importBinding","importsByVariable","unsupportedDefaultImport","variableName","unsupportedNamespaceImport","resolveImportBinding","topLevelBindingsByVariable","declarationKind","unsupportedMutableBinding","bindingReason","unsupportedBinding","unsupportedMissingStaticBinding","resolveExpression","rawExpression","expression","unwrapStaticExpression","valueType","unsupportedNonStringLiteral","resolveLiteral","unsupportedDynamicTemplateLiteral","quasi","raw","resolveTemplateLiteral","unsupportedStaticDefinition","unsupportedUninitializedConst","seenVariables","resolveIdentifierValue","resolvedExpression","resolveObjectMemberExpression","resolveMemberExpressionValue","expressionType","unsupportedExpression","unsupportedOptionalMemberExpression","unsupportedComputedMemberExpression","propertyType","unsupportedNonStaticMemberProperty","objectExpression","resolveObjectExpressionValue","propertyName","match","unsupportedObjectSpread","unsupportedComputedObjectProperty","getStaticPropertyKey","unsupportedDuplicateObjectProperty","unsupportedAccessorObjectProperty","hasExpressionValue","unsupportedObjectPropertyValue","unsupportedMissingObjectProperty","resolveObjectPropertyExpression","unsupportedNonObjectMemberValue","memberExpression","mutatedImportedObjectVariables","unsupportedImportedObjectMutation","collectMutatedImportedObjectVariables","mutatedVariables","values","markMutatedImportedPattern","UpdateExpression","UnaryExpression","operator","ForInStatement","markMutatedImportedForIterationTarget","ForOfStatement","markMutatedImportedIdentifier","resolveImportedObjectAlias","initializer","getVariableInitializer","getImportedObjectAliasRoot","current","isTypeScriptExpressionWrapper","PACKAGE_MANAGER_DIRS","createParsedModuleRecord","buildRoot","staticDependencies","shouldTraverseCollectedModule","staticModuleDependencies","staticDependencyIds","staticModuleSources","getStaticModuleSources","index","collectStaticModuleDependencies","unsupportedDependencies","collectUnsupportedModuleDependencies","collectImportBindings","collectExportBindings","collectStarExports","collectTopLevelBindings","getResolvedSource","specifier","getModuleExportName","imported","collectNamespaceExportBinding","collectNamedExportBindings","declarator","collectDeclarationExportBindings","exportedName","getExportAllExportedName","bindings","collectTopLevelNodeBindings","markAssignedPattern","markForIterationTarget","markReassignedTopLevelBindings","collectVariableDeclarationBindings","markAssignedVariable","ImportExpression","getLiteralSpecifier","getImportExpressionSpecifier","shouldFailDynamicImport","isImportCallExpression","arguments","getImportCallSpecifier","isLocalSpecifier","isLocalRequireCall","getRequireSpecifier","extension","relativePath","relative","isAbsolute","sep","segment","fallback","unsupportedModuleGraphDependency","extractConnectionIdsFromModuleGraph","entryId","connectionIds","pending","visited","shift","dependencyId","walkModuleGraph","imports","functions","namespaces","collectActionCatalogImports","analyzeActionCatalogScopes","callSite","connectionId","extractConnectionIdFromActionCall","sort","firstArg","connectionIdProperty","isConnectionIdKey","findConnectionIdProperty","resolveStaticStringValue","getStaticStringUnsupportedReason","RESTRICTED_MODULES","builtinModules","hasRuntimeSpecifier","rejectIfRestrictedSource","isRestrictedSource","isAmbientGlobalReceiverName","forOfAmbientAliases","resolvesToAmbientGlobal","staticMemberName","parent","reachesSelfReference","staticPropertyName","unwrapDefaultValue","resolveStaticPropertyName","direct","BULK_COPY_CALLS","forEachAmbientGlobalAccess","handlers","onNamedAccess","checkDestructuredPattern","onBulkCopy","nestedPattern","checkDestructure","MemberExpression","AssignmentPattern","bindingPattern","bindingIdentifierVariable","findDeclaredVariable","ObjectExpression","objectName","matchBulkCopyCall","RESTRICTED_GLOBALS","rejectRestrictedGlobals","precomputedScopeAnalysis","throwRestrictedGlobalError","from","DIVERGENT_GLOBALS","warnedGlobalsByFile","runBackendStaticChecks","rejectNodeBuiltinImports","warned","clear","warnOnce","warnDivergentGlobal","warnAboutDivergentGlobals","encodeQueryName","ref","posixPath","createHash","update","digest","generateProxyModule","exports","lines","queryName","isPackageExportInstalled","packageExport","fromDir","require","paths","isActionCatalogInstalled","isDatadogAppsBackendInstalled","generateVirtualEntryContent","functionName","entryPath","projectRoot","hasDatadogAppsBackendRuntime","VIRTUAL_MODULE_ID_RE","normalizeViteModuleId","isViteVirtualModuleId","createBackendConnectionIdCollector","moduleGraphCollector","records","moduleParsed","moduleInfo","importedIdResolutions","importedIds","getStaticDependencyIds","getModuleRecords","createBackendModuleGraphCollector","getAllowedConnectionIds","createBackendStaticChecksPlugin","existingRecord","createVirtualPlugin","virtualEntries","enforce","resolveId","moduleSideEffects","load","getBaseBackendBuildConfig","plugins","configFile","envFile","envPrefix","build","minify","target","ssr","rollupOptions","format","inlineDynamicImports","preserveEntrySignatures","treeshake","onwarn","warning","defaultHandler","extensions","noExternal","collectAssets","patterns","cwd","matches","all","glob","absolute","nodir","flat","relativePaths","commonPrefix","segments","i","every","p","findCommonPrefix","strippedPath","absolutePath","CUSTOM_CREDENTIALS_LOCAL_FILENAME","resolveCustomCredentials","isErrnoException","create","isCustomCredentialsAsset","credentialsIdentity","basename","stats","dev","ino","writeManifestFile","backendFunctions","manifestDir","mkdtemp","os","tmpdir","manifestPath","writeFile","func","allowedConnectionIds","backend","buildManifest","manifestAsset","cleanup","buildAppPackage","backendOutputs","outDir","defaultArchivePath","packageDirectory","archivePath","relativeOutdir","assets","include","cleanupManifest","generatedPaths","backendPaths","candidateAssets","asset","resolveCredentialsIdentity","nonCredentialsAssets","isCredentialsAsset","packageAssets","bundleName","manifest","archive","zip","JSZip","binary","compression","compressionOptions","reject","createWriteStream","generateNodeStream","streamFiles","on","pipe","createArchive","loaderForModuleId","stripLocalExecutionMarker","normalizeDevServerModuleId","createEpochGuard","currentGeneration","activeGeneration","myGeneration","isCurrent","concludeIfCurrent","hasActiveScope","forceInvalidate","getMaxRetryDelayMs","lazyImportOnce","loader","modulePromise","getEnvGuard","backendGlobalsContext","AsyncLocalStorage","hadPreexistingDollar","Reflect","globalThis","customerModuleLoadContext","localExecutionResolutionContext","globalDollarOutsideExecution","ensureDollarAccessorInstalled","getOwnPropertyDescriptor","dollarGetter","configurable","dollarSetter","box","getStore","loadBox","assigned","executionDispatchContext","isIndexableRecord","assertRuntimeUser","orgId","email","DEFAULT_LONG_POLLING_CONFIG","deriveActionTimeouts","worstCaseMs","config","totalMs","getTotalRetryDelayBudgetMs","actionCallTimeoutMs","totalExecutionTimeoutMs","loadCustomerModuleEntry","loadModule","entrySpecifier","onScopeStarted","buildScopedEnv","runWithScopedEnv","customCredentials","scopedEnv","run","validateActionCall","call","actionDescription","assertConnectionIdAllowed","invokeAction","executeAction","actionId","serializedInputs","subject","roundTripped","assertJsonRoundTrippable","serializeActionInputs","runAllowed","queueTail","abandonedExecutionError","refusedAction","executionEpoch","makeActionsProxy","pathParts","Proxy","_target","prop","nestedPathParts","concat","_thisArg","actionPath","withTimeout","promise","setTimeout","clearTimeout","registerOnceIfInstalled","isInstalled","registrations","registerOnce","existing","registration","actionCatalogRegistrations","WeakMap","registerActionCatalogOnce","loadPromise","setExecuteActionImplementation","request","dispatch","isAbandoned","backendRuntimeRegistrations","registerBackendRuntimeOnce","jsFunctionWithActionsModule","runtimeModule","buildRuntimeFromJsFunctionWithActions","setBackend","runtimeByDispatch","runtime","$","bind","UnsupportedJsonValueError","serialized","isRootCall","childValue","wasRootCall","getOwnPropertySymbols","executeColdActionLocally","getRuntimeContext","displayName","enqueue","runtimeContext","Source","initiator","runAsUser","assertValidRuntimeContext","connectionIdsPromise","primingEnvScope","primingPromise","handle","primedEntry","abandon","rejectTimeout","absoluteTimeoutTimer","blockedScope","envScope","pendingActionCalls","abandonExecutionAndRejectWith","concludeExecution","abandonIfCurrent","scheduleTimeout","rearmAbsoluteTimeout","guardedExecuteAction","fqn","actionCallPromise","backendFunctionArgs","Actions","rejectIfAbandoned","networkGuardPromise","envGuardPromise","customCredentialsPromise","runBlocked","actionCatalogRegistration","registerActionCatalogIfInstalled","backendRuntimeRegistration","registerBackendRuntimeIfInstalled","assertJsonSerializable","timeout","_resolve","runPromise","raceSettled","race","runScriptLocally","delay","ms","removeEventListener","onAbort","addEventListener","once","aborted","isAbortError","getRetryDelay","backoffDelay","random","formatRef","bundleBackendFunction","viteBuild","virtualId","virtualContent","generateDevVirtualEntryContent","connectionIdCollector","staticChecksPlugin","baseConfig","write","enrichedFunc","submitQuery","querySpec","doAuthenticatedRequest","endpoint","attributes","query","randomUUID","onlyTriggerManually","template_params","initialResult","receiptId","retryDelay","round","attemptTimeoutSignal","AbortSignal","requestSignal","any","detail","title","attrs","done","pollQueryExecution","sendError","res","setHeader","success","sendSuccess","guardAuthenticated","handleHttpError","HttpError","parseAndLookupFunction","req","functionsByName","chunk","parseRequestBody","validateAndBundle","bundle","handleExecuteAction","makeExecuteActionRemotely","controller","AbortController","timeoutError","deadline","abort","script","makeGetRuntimeContextRemotely","handleExecuteActionViaCloud","scriptBody","executeScriptViaDatadog","createDevServerMiddleware","getBackendFunctions","mode","isDevVerifyMode","initialFunctions","f","next","handleDebugBundle","authedRequest","routeToCloudHandler","APPS_RUNTIME_PATH","__dirname","VITE_DEFAULT_SERVER_FS_DENY","getVitePlugin","inject","position","MIDDLE","setBackendFunctions","functionsByEntryPath","createBackendFunctionRegistry","devServerActive","server","deny","order","importer","resolveOptions","sourceWithoutPostfix","subgraphImporters","skipSelf","external","suffixedId","transform","exclude","transformOptions","queryIndex","indexOf","normalizedId","exportNames","proxyCode","refPath","proxyExports","buildProxyModule","closeBundle","backendOutDir","allowedConnectionIdsByEntryPath","emptyOutDir","entryFileNames","isEntry","fileName","cleanupError","buildBackendFunctions","configureServer","trustedFetch","getAuthenticatedRequest","ssrLoadModule","middleware","moduleGraph","bareEntryId","entryUrl","transformRequest","entryNode","getModuleById","stripped","parseAst","importerFile","moduleSource","pluginContainer","dependencyNode","importedModules","collectModuleGraphFromServer","middlewares","use","validatedOptions","resolvedOptions","vite","decomposePath","absoluteOutDir","sourcemapFilePath","extname","minifiedFilePath","minifiedUrl","normalizedPrefix","normalizedRelativePath","href","joinUrlOrPath","DEBUG_ID_RX","extractDebugId","fd","open","buffer","Buffer","alloc","overlap","bytesRead","read","searchableContent","fileContent","exec","close","readDebugId","SLASH_RX","SLASH_TRIM_RX","prefixRepeat","prefixParts","normalizedPath","partialPrefix","getPayload","sourcemap","git","resultMinFile","resultSourcemap","repeatedPrefix","getSourcemapValidity","debug_id","minified_url","files","trackedFilesMatcher","matchSourcemap","hash","repository_url","remote","getStatusCodeTag","getErrorTypeTag","statusCodeTag","incrementUploadMetric","uploadMetrics","metricKey","getMetricKey","currentMetric","metrics","recordSourcemapUploadRetry","baseTags","recordSourcemapUploadFailure","addSourcemapUploadMetrics","sendMetrics","timestamp","metric","points","getSourcemapUploadMetrics","addMetric","defaultHeaders","getForm","form","Request","pipeThrough","CompressionStream","fromEntries","createRequestData","FormData","Blob","append","payloads","queueTimer","PQueue","default","concurrency","intakeUrl","bundlerName","createSourcemapUploadMetrics","configurationString","summary","addPromises","warningMessage","onIdle","uploadSourcemaps","sourcemapsTime","minifiedPathPrefix","getSourcemapsFiles","sendTime","git_repository_url","git_commit_sha","plugin_version","project_path","releaseVersion","payloadsTimer","payloadsQueue","sourcemapsWithDebugIds","addAll","debugIdCount","errorMsg","skippedSourcemaps","sourcemapsToUpload","uploadTimer","uploadErrors","uploadWarnings","fileMetadata","errorToPrint","cause","stack","sendSourcemaps","validateSourcemapsOptions","toReturn","sourcemapsCfg","validateMinifiedPathPrefix","timeOptions","sourcemapsResults","sendSourcemapUploadMetrics","gitInfo","buildReport","sourcemapsHandling","sourcemapsHandled","handleSourcemaps","artifactsReady","totalTime","handleOrQueueSourcemaps","artifactsPending","sourcemapsPromise","repoData","asyncTrueEnd","DEFAULT_FILE_EXTENSIONS","BACKSLASH_PATTERN","WINDOWS_ABSOLUTE_PATH_PATTERN","ID_SUFFIX_PATTERN","normalizePath","createPatternMatcher","lastIndex","absoluteGlob","resolveGlob","matchesGlob","picomatch","dot","createFileFilter","matchesPatterns","includeMatchers","excludeMatchers","createPatternFilter","matchesFileExtension","fileExtensions","normalizedExtensions","normalizedFilePath","createFileExtensionFilter","escapeRegExp","runtimeStubs","buildMetadataGlobal","getRuntimeBootstrap","resolveCjsDefaultExport","generateFunctionId","functionPath","anonymousSiblingIndex","typesModule","getFunctionName","locationSuffix","line","loc","column","getFunctionLocation","isIdentifier","isObjectMethod","isClassMethod","isClassPrivateMethod","getPropertyLikeName","isVariableDeclarator","isAssignmentExpression","isMemberExpression","isOptionalMemberExpression","getMemberObjectName","getMemberPropertyName","getAssignmentTargetName","isObjectProperty","isClassProperty","isClassPrivateProperty","isThisExpression","parentObjectName","isComputed","isPrivateName","isNumericLiteral","isBigIntLiteral","hasSkipComment","skipComment","leadingComments","comment","getLocalVariableDeclarations","functionNode","isBlockStatement","paramNames","params","getPatternIdentifiers","paramSet","stmt","isVariableDeclaration","declarationEnd","temporalDeadZones","cappedVariables","localNames","localNameSet","temporalDeadZonesByName","functionBody","collectTemporalDeadZonesFromStatement","getNestedTemporalDeadZonesByName","isFunctionDeclaration","isClassDeclaration","collectTemporalDeadZonesFromBlock","isIfStatement","consequent","alternate","isForStatement","isForInStatement","isForOfStatement","isWhileStatement","isDoWhileStatement","isSwitchStatement","caseClause","cases","addTemporalDeadZonesFromStatements","collectTemporalDeadZonesFromSwitch","isTryStatement","block","finalizer","isLabeledStatement","isWithStatement","statements","scopeStart","addVariableDeclarationTemporalDeadZones","addTemporalDeadZone","existingZones","isRestElement","isAssignmentPattern","isObjectPattern","isArrayPattern","isTSParameterProperty","parameter","REQUIRED_PEER_DEPS","traverse","babelTypes","MagicString","hasLoadedTransformRuntime","requireOptionalPeerDep","loadKnownPeerDep","dep","isMissingPeerDepError","missingDep","rewrapMissingPeerDepError","HAS_FUNCTION_SYNTAX","getParserPlugins","decorators","transformCode","honorSkipComments","functionTypes","namedOnly","failedCount","instrumentedCount","skippedByCommentCount","skippedUnsupportedCount","totalFunctions","containsUnsupportedImports","skippedFileCount","sourceFilename","targets","constructorBodyStartsByNode","constructorsUsingThisAlias","superCallsByConstructorNode","anonymousCountByParent","probeVarCounter","Function","derivedConstructor","isDerivedClassMethod","getDerivedConstructor","statement","collectSuperCallTargetsFromNode","getSuperCallTargets","generator","canInstrumentFunction","isStatement","isExportDeclaration","parentPath","shouldSkipFunction","isArrowFunctionExpression","getFunctionKind","parentNode","functionId","idx","probeVarName","entryVars","getParameterNames","localVars","isExpressionBody","hasSequenceExpressionBody","isSequenceExpression","constructorPath","isFunction","getDerivedConstructorForLexicalThis","useThisAlias","returns","needsTrailingReturn","alwaysReturns","directivesEnd","collectReturnStatements","directives","bodyStart","bodyEnd","functionEnd","aliasesExpressionBodySuperCall","isSuperCallExpression","bodyParenStart","extra","parenStart","probeIdx","superCallRangesHandledByExpressionBodies","ranges","getRangeKey","getSuperCallRangesHandledByExpressionBodies","constructorThisAliasTargets","constructorNode","superCalls","superCall","getConstructorThisAliasTargets","injectInstrumentation","injectConstructorThisAlias","generateMap","hires","rvVarName","receiverArg","entryVarsList","hasParams","entryArgs","argsArg","probeDecl","character","entryCall","catchBlock","openingParens","collectArrowWrapperParens","getLeadingArrowBodyParens","closingParens","getTrailingArrowBodyParens","parenCount","openingParen","closingParen","Boolean","expressionSuffix","suffix","getReturnCaptureArgs","bodyPrefix","appendRight","preamble","ret","returnCaptureArgs","argStart","argEnd","assignmentPrefix","hasSequenceExpressionArgument","assignmentSuffix","appendLeft","anchor","trailingReturnCaptureArgs","postamble","collectSuperCallTargetsFromUnknown","isNode","isCallExpression","isSuper","classPath","classNode","isClassExpression","superClass","exitPosition","localsArg","availableLocals","isInTemporalDeadZone","getLocalCaptureArg","paren","parens","char","isReturnStatement","last","VALID_FUNCTION_KINDS","VALID_DECORATOR_SYNTAXES","INVALID_FILE_EXTENSION_PATTERN","metadataVersion","configuredFileExtensions","lowercaseExtensions","normalizeFileExtensions","DD_LD_LIMIT","Infinity","getLiveDebuggerPlugin","pluginOptions","shouldInstrumentFile","fileExtensionPattern","escapedExtensions","createFileExtensionPattern","nativeInclude","transformedFileCount","totalFilesWithFunctions","inputMap","ctx","native","getNativeBuildContext","inputSourceMap","getInputSourceMap","composedMap","instrumentMap","remapping","_file","depth","composeWithInputMap","buildEnd","BEFORE","injectIntoAllChunks","defaultFilters","thresholds","count","accumulator","currentPoint","getTimestamp","getDefaultTags","configuredTags","defaultTags","getMetric","getMetricsToSend","filters","metricsToSend","processedMetrics","toSend","m","formatCwd","getDisplayName","pop","formatModuleName","getModuleName","module","compilation","userRequest","issuer","getIssuer","_identifier","getModulePath","formatLoaderName","getValueContext","numColor","nameColor","sortDesc","attr","a","b","aVal","bVal","getTimingValues","times","durationsToPrint","top","increment","outputTexts","globalContext","valuesToPrint","loaders","tapables","dependentsToPrint","dependenciesToPrint","sizesToPrint","aggregatedSizesToPrint","serializedReport","fileDependencies","fileDependents","dependenciesSet","dependentsSet","existingDependencies","existingDependents","inputDependencies","inputDependents","aggregatedSize","dependenciesArray","prettyBytes","getModulesValues","nbModules","nbAssets","nbWarnings","nbErrors","nbEntries","getGeneralValues","outputString","group","maxTitleWidth","val","maxNameWidth","v","maxValueWidth","totalWidth","titlePad","repeat","valuePad","renderValues","METRICS_API_PATH","metricIterations","metricsNames","nameA","nameB","localeCompare","series","FN_TO_WRAP","loadersMap","pluginsMap","modulesMap","getNewBuildObject","newBuildObject","assign","cb","pluginTiming","events","isLoader","initialFunction","modulePath","moduleTiming","performance","statsObject","loaderTiming","getEsbuildPlugin","setup","initialOptions","metafile","timeWrap","initialPlugins","oldSetup","esbuild","wrapPlugins","onEnd","timeResult","asyncHook","Loaders","started","finished","startModule","moduleName","l","getLoaderNames","doneModule","event","getResults","eventName","Tapables","monitoredTaps","hooks","ignoredHooks","saveResult","timing","tapableName","tapable","hookArray","previous","getPromiseTapPatch","checkNewHooks","returnValue","getAsyncTapPatch","originalCB","getDefaultTapPatch","getTapPatch","newTap","originalTap","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","initializeMetricsCollector","enableDefaultPrefix","enableTracing","legacyPlugin","webpack","rspack","timeBuild","needLegacyPlugin","timingsReport","sendCollectedMetrics","timeMetrics","getMetricsToSendFromCollectedMetrics","timeSend","computeMetrics","timeUniversal","universalMetrics","entriesPerInput","assetsPerInput","entriesPerAsset","cleanAssetName","entryName","assetName","getUniversalMetrics","timePlugin","pluginMetrics","pluginDuration","pluginCount","hookDuration","getPluginMetrics","timeLoader","loaderMetrics","getLoaderMetrics","allMetrics","timeReport","universalPlugin","buildStart","flush","sanitizeOutputPath","validateFilesOptions","defaultValue","getXpackPlugin","statsTimer","statsJson","toJson","children","chunks","chunkGroupAuxiliary","chunkGroupChildren","chunkGroups","chunkRelations","entrypoints","ids","nestedModules","relatedAssets","reasons","chunkModules","getRollupPlugin","writeBundle","fileValue","timeWrite","pathOption","outputPath","getFilePath","dataToWrite","writable","readable","JsonStreamStringify","prom","outputJson","queuedWrite","timeSerialization","getStats","rollup","getOutputs","VARIANT_CHARS","getSourceCodeContextSnippet","contextOptions","withVersion","variantIndex","charCodeAt","withVariant","stringToUUID","sourceOrHash","ddDebugId","getPrivacyPlugin","helperCodeExpression","privacy","addToDictionaryHelper","inlineSourceMap","embedCodeInSourceMap","buildTransformOptions","dictionaryEntryCount","fileCount","nativeBuildContext","framework","instrument","privacyDictionarySize","getContent","sdk","getInjectionValue","sdkOpts","clientToken","appResponse","applicationId","client_token","validateSDKOptions","sdkWithDefault","allowUntrustedEvents","compressIntakeRequests","defaultPrivacyLevel","enablePrivacyForActionName","sessionReplaySampleRate","sessionSampleRate","silentMultipleInit","startSessionReplayRecordingManually","storeContextsAcrossPages","telemetrySampleRate","traceSampleRate","trackingConsent","trackLongTasks","trackResources","trackUserInteractions","trackViewsManually","validatePrivacyOptions","privacyWithDefault","addToDictionaryFunctionName","validateSourceCodeContextOptions","cfg","sdkResults","privacyResults","sourceCodeContextResults","privacyPlugin","getAnalyticsPlugins","buildStartFn","getAsyncQueuePlugins","wrappedPromise","getEsbuildEntries","entryPoints","entryPaths","resolutionErrors","fullPath","in","proms","getAllEntryFiles","sync","resolveDir","original","resolutionError","getAbsolutePath","getNearestCommonDirectory","dirs","splitPaths","minLength","parts","commonParts","component","EXTENSION_RX","QUERY_RX","getType","BUNDLER_SPECIFICS","cleanReport","cleanedReport","reportFilepath","cleanedPath","filepath1","filepath2","filepath2Split","commonPath","part","removeCommonPrefix","reIndexMeta","entryNames","resolvedEntries","timeBuildReport","onStart","timeEntries","timeCollect","tempEntryFiles","tempSourcemaps","reportInputsIndexed","reportOutputsIndexed","timeIndex","metaInputsIndexed","metaOutputsIndexed","getRealPathFromInjectionProxy","entryPoint","metaInput","actualImport","imp","timeInputs","bytes","timeOutputs","inputFiles","inputName","inputFound","inputFile","timeSourcemaps","foundOutput","meta","FILE_EXCEPTIONS_RX","isFileSupported","getAllImports","allImports","metaFile","isRelative","absoluteImportPath","entryFile","entryInputs","entryOutputs","outputFile","timeDeps","absoluteDependencyPath","dependencyFile","timeModuleParsing","timeInputsOutputs","timeCompleteDeps","importsReport","onLog","logItem","renderError","cleanId","newDependencies","dynamicallyImportedIds","newDependents","dynamicImporters","importers","tempOutputsImports","cleanedDependency","cleanedDependent","byteLength","modulepath","moduleSize","originalLength","statSync","renderedLength","moduleFile","importName","cleanedImport","importFile","outputReport","importReport","foundInput","getAllOutputs","allOutputs","dynamicImports","modulesPerFile","moduleIndex","tempDeps","isModuleSupported","moduleIdentifier","cleanExternalName","indexModule","mod","moduleToIndex","blocks","externalType","createIndexedModule","keysToIndex","indexes","keysOfModuleToIndexOn","indexValue","valueToIndex","getKeysToIndex","previousModule","getAllDependencies","getModuleFromDep","cleanRequest","isExternal","finishModules","finishedModules","timeGraph","moduleDeps","depIdentifier","depDeps","timeAssign","depsReport","depInput","getAssets","getChunkFiles","auxiliaryFiles","timeChunks","chunkGraph","getChunkModules","m2","fileModules","outputFound","getAllChunksFromGroup","chunkGroup","allChunks","childGroup","childrenIterable","childChunks","entrypoint","entryFiles","entryFilename","getChunkEntryModulesIterable","getBuildReportPlugins","getAbsoluteOutDir","getOutDirsFromOutputs","outputOptions","o","xpackPlugin","rawConfig","vitePlugin","configResolved","outDirs","getBundlerReportPlugins","absWorkingDir","outdir","outfile","inDirs","normalizedInput","getIndirsFromInputs","computedCwd","renderStart","getCustomHooksPlugins","executeHooks","hookArgs","timeHook","hookFn","TrackedFilesMatcher","trackedFiles","trackedFilenames","getFilename","list","displaySource","src","srcmapPath","onSourcesNotFound","buff","readFileSync","srcmapObj","sources","filtered","matchSources","filenameAlreadyMatched","rawTrackedFilesList","rawList","forEach","lastIndexOf","substring","gitRemote","remotes","getRemotes","defaultRemote","getDefaultRemoteName","refs","getConfig","gitHash","revparse","gitTrackedFiles","gitBranch","branch","gitMessage","show","gitAuthorAndCommitter","getGitPlugins","gitRepositoryUrl","timeGit","processGit","gitDir","baseDir","maxConcurrentProcesses","simpleGit","newSimpleGit","repositoryData","remoteOverride","authorAndCommitter","authorName","authorEmail","authorDate","committerName","committerEmail","committerDate","commit","author","date","committer","getRepositoryData","currentDir","closest","getClosest","DISTANT_FILE_RX","SUPPORTED_EXTENSIONS","hasBeforeAfterInjection","contentsToInject","AFTER","hasChunkInjection","getContentToInject","contentToInject","resolveWithFallback","timeoutId","processDistantFile","processLocalFile","itemId","prepareInjections","toInject","dynamicPerChunk","isPerChunk","userFn","staticInject","resolvedStaticInject","normalize","isNodeSystemError","ext","warnUnsupportedFile","promises","onResolve","onLoad","tmpDir","realpathSync","absoluteFilePath","injectionRx","initialInject","namespace","contents","markArtifactsReady","base","mapPath","banner","footer","cleaned","sourcefile","TO_INJECT_ID","TO_INJECT_SUFFIX","renderChunk","prepend","resolution","getModuleInfo","hasDefaultExport","cache","ConcatSource","shutdown","rmSync","setupInjections","beforeRun","watchRun","stage","Compilation","PROCESS_ASSETS_STAGE_ADDITIONS","processAssets","canBeInitial","chunkSource","contentHash","javascript","updateAsset","old","cached","initialEntry","injectedEntry","import","objectInjection","entryKey","entryValue","unshift","originEntry","ddHelper","injectEntry","getInjectionPlugins","injections","transformIndexHtml","injectTo","markArtifactsPending","getTrueEndPlugins","asyncHookFn","flushHookFn","syncHookFn","bothHookFns","rollupPlugin","onDispose","CONFIG_KEY$2","metrics.CONFIG_KEY","metrics.helpers","datadogWebpackPlugin","createUnplugin","unpluginMetaContext","pluginStart","esbuildHostName","passedEnv","BUILD_PLUGINS_ENV","bundlerVersion","rspackVersion","VERSION","resolveArtifacts","rejectArtifacts","getContext","timeInit","pluginsToAdd","customPlugins","userFacingPlugins","apps.CONFIG_KEY","apps.getPlugins","errorTracking.CONFIG_KEY","errorTracking.getPlugins","liveDebugger.CONFIG_KEY","liveDebugger.getPlugins","metrics.getPlugins","output.CONFIG_KEY","output.getPlugins","rum.CONFIG_KEY","rum.getPlugins","overridenValues","k","usedKey","notifyOnEnvOverrides","duplicates","n","blockOnDuplicateNames","factory.buildPluginFactory","pkg","factory.helpers","makeGuardWrapper","getReal","shouldBlock","blockedMessage","onBlocked","blocked","invokeCallbackArg","maybeCallback","nextTick","getOrCreateShared","hostModule","factory","symbol","Symbol","for","registry","prototype","hasOwnProperty","NETWORK_BLOCKED_MESSAGE","SUBPROCESS_BLOCKED_MESSAGE","getSharedContext","net","isActive","blockedContext","allowedContext","isCurrentlyBlocked","ALREADY_GUARDED","RUNNING_UNDER_JEST","JEST_WORKER_ID","shouldAllowConfigurableUnderJest","Socket","installGuardedProperty","makeGuard","existingGetter","real","realAtGuardCreation","buildGuard","capturedReal","guard","currentGuard","getter","extraArgs","emitAsyncErrorIfListened","listenerCount","emit","trustedStdout","stdout","trustedStderr","stderr","guardSocketOp","blockedReturn","socket","destroy","signalBlockedSocketOp","guardBindMethod","guardCallbackMethod","EventEmitter","guardNetworkPromiseMethod","guardConstructibleGlobal","construct","newTarget","RealCtor","guardWebSocket","guardEventSource","guardWorker","guardSubprocess","createBlockedChildProcessStub","stub","pid","exitCode","signalCode","killed","connected","channel","stdin","Writable","_chunk","_encoding","callback","kill","unref","disconnect","send","sendArgs","sendErr","guardSpawnFactory","guardExecWithPromisifyCustom","wrapper","guardExecFactory","promisify","custom","errorWithOutput","dgram","Server","DNS_RESOLVE_METHODS","dns","Resolver","child_process","ChildProcess","worker_threads","syncBuiltinESMExports","blockEpoch","nativeRealpathSync","nativeReadlinkSync","readlinkSync","SAFE_ENV_KEYS","sharedState","scopedEnvContext","nativeGetStore","realEnv","realEnvHistory","activeScopeTokens","savedExcludeEnv","cachedNativeFdGetter","nativeFdGetterCaptured","nativeExcludeEnvDescriptor","getExcludeEnv","applyExcludeEnvValue","excludeEnvValue","excludeEnv","newValue","restoreExcludeEnvIfLastScope","currentValue","getCurrentEnv","isInsideScope","setRealEnvIfOutsideScope","restoreRealEnvFromHistory","runInScope","armScope","token","disarmScope","forceResetAllScopes","getCachedNativeFdGetter","setCachedNativeFdGetterOnce","ENV_PROXY_MARKER","FILE_HANDLE_READ_GUARD_MARKER","isEnvProxy","forwardToCurrentEnv","reflectFn","INERT_PROXY_TARGET","ensureEnvProxyInstalled","proxy","receiver","deleteProperty","ownKeys","descriptor","setPrototypeOf","getPrototypeOf","preventExtensions","ENVIRON_PATH_RE","isEnvironPath","rawPath","pathString","isBuffer","fileURLToPath","platform","toPathString","resolvedPath","nodePath","posix","ENVIRON_READ_BLOCKED_MESSAGE","isBlockedEnvironPath","extractFdNumber","throwIfBlockedEnvironPath","fdValue","readNativeFd","snapshotOptionKeysOnce","keySet","guardEnvironPathOrFdOption","snapshot","wrapGuardedFsFn","wrapGuardedAsyncFsFn","onResolved","guarded","wrapGuardedCallbackFsFn","originalIfUnguarded","proto","methodName","markGuarded","nativeFdGetter","trueFd","patchFileHandleAsyncMethod","priorDescriptor","withPinnedFd","patchFileHandleSyncMethod","safeOptions","safeArgs","openSync","readSync","readv","readvSync","copyFileSync","copyFile","guardCpOptions","dereference","originalCpSync","cpSync","originalCp","cp","originalPromisesCp","wrapReportFn","implementation","dest","rest","hasOptions","ReadStream","FileReadStream","originalGetReport","getReport","hasEnvironmentVariables","environmentVariables","originalWriteReport","writeReport","fileNameArg","isFile","isVerifiedNonRegularDestination","errArg","rawReport","scoped","merged","canonicalKey"],"mappings":"soCAIO,MAAMA,EAAgB,wBAChBC,EAAmB,IAAIC,OAAOF,GAE9BG,EAAW,CAAC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