{"version":3,"file":"utils.js","sources":["../../../src/vite/utils.ts"],"sourcesContent":["import type { Nuxt } from '@nuxt/schema';\nimport { consoleSandbox } from '@sentry/core';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { SentryNuxtModuleOptions } from '../common/types';\nimport { resolvePath } from '@nuxt/kit';\n\n/**\n * Gets the major version of the installed nitro package.\n * Returns 2 as the default if nitro is not found or the version cannot be determined.\n */\nexport async function getNitroMajorVersion(): Promise {\n try {\n const { getPackageInfo } = await import('local-pkg');\n const info = await getPackageInfo('nitro');\n if (info?.version) {\n const major = parseInt(info.version.split('.')[0] ?? '2', 10);\n return isNaN(major) ? 2 : major;\n }\n } catch {\n // If local-pkg is unavailable or nitro is not found, default to v2\n }\n return 2;\n}\n\n/**\n * Find the default SDK init file for the given type (client or server).\n * The sentry.server.config file is prioritized over the instrument.server file.\n */\nexport async function findDefaultSdkInitFile(\n type: 'server' | 'client',\n nuxt?: Nuxt,\n options?: SentryNuxtModuleOptions,\n): Promise {\n const possibleFileExtensions = ['ts', 'js', 'mjs', 'cjs', 'mts', 'cts'];\n const relativePaths: string[] = [];\n\n if (type === 'server') {\n for (const ext of possibleFileExtensions) {\n relativePaths.push(`sentry.${type}.config.${ext}`);\n relativePaths.push(path.join('public', `instrument.${type}.${ext}`));\n }\n } else {\n for (const ext of possibleFileExtensions) {\n relativePaths.push(`sentry.${type}.config.${ext}`);\n }\n }\n\n // Get layers from highest priority to lowest\n const layers = [...(nuxt?.options._layers ?? [])].reverse();\n\n for (const layer of layers) {\n for (const relativePath of relativePaths) {\n const fullPath = path.resolve(layer.cwd, relativePath);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n }\n\n // As a fallback, also check CWD (left for pure compatibility)\n const rootDir = options?.configDir ? await resolvePath(options.configDir, { type: 'dir' }) : process.cwd();\n for (const relativePath of relativePaths) {\n const fullPath = path.resolve(rootDir, relativePath);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts the filename from a node command with a path.\n */\nexport function getFilenameFromNodeStartCommand(nodeCommand: string): string | null {\n const regex = /[^/\\\\]+\\.[^/\\\\]+$/;\n const match = nodeCommand.match(regex);\n return match ? match[0] : null;\n}\n\nexport const SENTRY_WRAPPED_ENTRY = '?sentry-query-wrapped-entry';\nexport const SENTRY_WRAPPED_FUNCTIONS = '?sentry-query-wrapped-functions=';\nexport const SENTRY_REEXPORTED_FUNCTIONS = '?sentry-query-reexported-functions=';\nexport const QUERY_END_INDICATOR = 'SENTRY-QUERY-END';\n\n/**\n * Strips the Sentry query part from a path.\n * Example: example/path?sentry-query-wrapped-entry?sentry-query-functions-reexport=foo,SENTRY-QUERY-END -> /example/path\n *\n * Only exported for testing.\n */\nexport function removeSentryQueryFromPath(url: string): string {\n // oxlint-disable-next-line sdk/no-regexp-constructor\n const regex = new RegExp(`\\\\${SENTRY_WRAPPED_ENTRY}.*?\\\\${QUERY_END_INDICATOR}`);\n return url.replace(regex, '');\n}\n\n/**\n * Extracts and sanitizes function re-export and function wrap query parameters from a query string.\n * If it is a default export, it is not considered for re-exporting.\n *\n * Only exported for testing.\n */\nexport function extractFunctionReexportQueryParameters(query: string): { wrap: string[]; reexport: string[] } {\n // Regex matches the comma-separated params between the functions query\n // oxlint-disable-next-line sdk/no-regexp-constructor\n const wrapRegex = new RegExp(\n `\\\\${SENTRY_WRAPPED_FUNCTIONS}(.*?)(\\\\${QUERY_END_INDICATOR}|\\\\${SENTRY_REEXPORTED_FUNCTIONS})`,\n );\n // oxlint-disable-next-line sdk/no-regexp-constructor\n const reexportRegex = new RegExp(`\\\\${SENTRY_REEXPORTED_FUNCTIONS}(.*?)(\\\\${QUERY_END_INDICATOR})`);\n\n const wrapMatch = query.match(wrapRegex);\n const reexportMatch = query.match(reexportRegex);\n\n const wrap =\n wrapMatch?.[1]\n ?.split(',')\n .filter(param => param !== '')\n // Sanitize, as code could be injected with another rollup plugin\n .map((str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')) || [];\n\n const reexport =\n reexportMatch?.[1]\n ?.split(',')\n .filter(param => param !== '' && param !== 'default')\n // Sanitize, as code could be injected with another rollup plugin\n .map((str: string) => str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')) || [];\n\n return { wrap, reexport };\n}\n\n/**\n * Constructs a comma-separated string with all functions that need to be re-exported later from the server entry.\n * It uses Rollup's `exportedBindings` to determine the functions to re-export. Functions which should be wrapped\n * (e.g. serverless handlers) are wrapped by Sentry.\n */\nexport function constructWrappedFunctionExportQuery(\n exportedBindings: Record | null,\n entrypointWrappedFunctions: string[],\n debug?: boolean,\n): string {\n const functionsToExport: { wrap: string[]; reexport: string[] } = {\n wrap: [],\n reexport: [],\n };\n\n // `exportedBindings` can look like this: `{ '.': [ 'handler' ] }` or `{ '.': [], './firebase-gen-1.mjs': [ 'server' ] }`\n // The key `.` refers to exports within the current file, while other keys show from where exports were imported first.\n Object.values(exportedBindings || {}).forEach(functions =>\n functions.forEach(fn => {\n if (entrypointWrappedFunctions.includes(fn)) {\n functionsToExport.wrap.push(fn);\n } else {\n functionsToExport.reexport.push(fn);\n }\n }),\n );\n\n if (debug && functionsToExport.wrap.length === 0) {\n consoleSandbox(() =>\n // eslint-disable-next-line no-console\n console.warn(\n \"[Sentry] No functions found to wrap. In case the server needs to export async functions other than `handler` or `server`, consider adding the name(s) to Sentry's build options `sentry.experimental_entrypointWrappedFunctions` in `nuxt.config.ts`.\",\n ),\n );\n }\n\n const wrapQuery = functionsToExport.wrap.length\n ? `${SENTRY_WRAPPED_FUNCTIONS}${functionsToExport.wrap.join(',')}`\n : '';\n const reexportQuery = functionsToExport.reexport.length\n ? `${SENTRY_REEXPORTED_FUNCTIONS}${functionsToExport.reexport.join(',')}`\n : '';\n\n return [wrapQuery, reexportQuery].join('');\n}\n\n/**\n * Constructs a code snippet with function reexports (can be used in Rollup plugins as a return value for `load()`)\n */\nexport function constructFunctionReExport(pathWithQuery: string, entryId: string): string {\n const { wrap: wrapFunctions, reexport: reexportFunctions } = extractFunctionReexportQueryParameters(pathWithQuery);\n\n return wrapFunctions\n .reduce(\n (functionsCode, currFunctionName) =>\n functionsCode.concat(\n `async function ${currFunctionName}_sentryWrapped(...args) {\\n` +\n ` const res = await import(${JSON.stringify(entryId)});\\n` +\n ` return res.${currFunctionName}.call(this, ...args);\\n` +\n '}\\n' +\n `export { ${currFunctionName}_sentryWrapped as ${currFunctionName} };\\n`,\n ),\n '',\n )\n .concat(\n reexportFunctions.reduce(\n (functionsCode, currFunctionName) =>\n functionsCode.concat(`export { ${currFunctionName} } from ${JSON.stringify(entryId)};`),\n '',\n ),\n );\n}\n\n/**\n * Sets up alias to work around OpenTelemetry's incomplete ESM imports.\n * https://github.com/getsentry/sentry-javascript/issues/15204\n *\n * OpenTelemetry's @opentelemetry/resources package has incomplete imports missing\n * the .js file extensions (like execAsync for machine-id detection). This causes module resolution\n * errors in certain Nuxt configurations, particularly when local Nuxt modules in Nuxt 4 are present.\n *\n * @see https://nuxt.com/docs/guide/concepts/esm#aliasing-libraries\n */\nexport function addOTelCommonJSImportAlias(nuxt: Nuxt, isNitroV3 = false): void {\n if (!nuxt.options.dev || isNitroV3) {\n return;\n }\n\n if (!nuxt.options.alias) {\n nuxt.options.alias = {};\n }\n\n if (!nuxt.options.alias['@opentelemetry/resources']) {\n nuxt.options.alias['@opentelemetry/resources'] = '@opentelemetry/resources/build/src/index.js';\n }\n}\n"],"names":[],"mappings":";;;;;AAWA,eAAsB,oBAAA,GAAwC;AAC5D,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,cAAA,EAAe,GAAI,MAAM,OAAO,WAAW,CAAA;AACnD,IAAA,MAAM,IAAA,GAAO,MAAM,cAAA,CAAe,OAAO,CAAA;AACzC,IAAA,IAAI,MAAM,OAAA,EAAS;AACjB,MAAA,MAAM,KAAA,GAAQ,QAAA,CAAS,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,C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