@sentry/bundler-plugins 11.0.0-rc.1 → 11.0.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.
Files changed (33) hide show
  1. package/build/cjs/core/get-code-injection-position.js +87 -0
  2. package/build/cjs/core/get-code-injection-position.js.map +1 -0
  3. package/build/cjs/core/index.js +2 -5
  4. package/build/cjs/core/index.js.map +1 -1
  5. package/build/cjs/core/version.js +1 -1
  6. package/build/cjs/core/version.js.map +1 -1
  7. package/build/cjs/esbuild/index.js.map +1 -1
  8. package/build/cjs/rollup/index.js +5 -6
  9. package/build/cjs/rollup/index.js.map +1 -1
  10. package/build/cjs/webpack/index.js +53 -25
  11. package/build/cjs/webpack/index.js.map +1 -1
  12. package/build/esm/core/get-code-injection-position.js +85 -0
  13. package/build/esm/core/get-code-injection-position.js.map +1 -0
  14. package/build/esm/core/index.js +2 -5
  15. package/build/esm/core/index.js.map +1 -1
  16. package/build/esm/core/version.js +1 -1
  17. package/build/esm/core/version.js.map +1 -1
  18. package/build/esm/esbuild/index.js.map +1 -1
  19. package/build/esm/package.json +1 -1
  20. package/build/esm/rollup/index.js +6 -7
  21. package/build/esm/rollup/index.js.map +1 -1
  22. package/build/esm/webpack/index.js +53 -25
  23. package/build/esm/webpack/index.js.map +1 -1
  24. package/build/types/core/get-code-injection-position.d.ts +2 -0
  25. package/build/types/core/get-code-injection-position.d.ts.map +1 -0
  26. package/build/types/core/index.d.ts +1 -1
  27. package/build/types/core/index.d.ts.map +1 -1
  28. package/build/types/core/version.d.ts +1 -1
  29. package/build/types/core/version.d.ts.map +1 -1
  30. package/build/types/esbuild/index.d.ts.map +1 -1
  31. package/build/types/rollup/index.d.ts.map +1 -1
  32. package/build/types/webpack/index.d.ts.map +1 -1
  33. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/webpack/index.ts"],"sourcesContent":["import type { Options } from '../core/index';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n stringToUUID,\n createComponentNameAnnotateHooks,\n CodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n isJsFile,\n stampDebugId,\n} from '../core/index';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\nconst _req = createRequire(import.meta.url);\n\n// Resolve the loader path via the package's own exports.\n// This module may end up in a shared chunk (_chunks/) whose import.meta.url\n// does not point to the webpack/ directory where the transform file lives, so\n// a path-relative lookup would fail. Using require.resolve on the package export\n// always finds the correct installed file regardless of chunk placement.\nlet COMPONENT_ANNOTATION_LOADER: string;\ntry {\n COMPONENT_ANNOTATION_LOADER = _req.resolve('@sentry/bundler-plugins/webpack-loader');\n} catch {\n // Fallback for non-packaged environments (e.g., monorepo source runs without dist)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Rollup transpiles import.meta for us for CJS\n const dirname = path.dirname(fileURLToPath(import.meta.url));\n // The Rollup build emits `.js` for both CJS and ESM, so the extension is the same in both.\n COMPONENT_ANNOTATION_LOADER = path.resolve(dirname, 'component-annotation-transform.js');\n}\n\ninterface BannerPluginCallbackArg {\n chunk?: {\n hash?: string;\n contentHash?: {\n javascript?: string;\n };\n };\n}\n\ntype PluginClass = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype WebpackSource = {\n source: () => string | Buffer;\n};\n\ntype WebpackRawSource = {\n new (source: string): WebpackSource;\n};\n\ntype WebpackAsset = {\n name: string;\n source: WebpackSource;\n info: {\n related?: {\n sourceMap?: string | string[];\n };\n };\n};\n\ntype WebpackCompiler = {\n options: {\n plugins?: unknown[];\n mode?: string;\n module?: {\n rules?: unknown[];\n };\n };\n hooks: {\n thisCompilation: {\n tap: (name: string, callback: (compilation: WebpackCompilation) => void) => void;\n };\n afterEmit: {\n tapAsync: (name: string, callback: (compilation: WebpackCompilation, cb: () => void) => void) => void;\n };\n done: {\n tap: (name: string, callback: () => void) => void;\n };\n };\n webpack?: {\n BannerPlugin?: PluginClass;\n DefinePlugin?: PluginClass;\n Compilation?: {\n PROCESS_ASSETS_STAGE_DEV_TOOLING?: number;\n };\n sources?: {\n RawSource?: WebpackRawSource;\n };\n };\n};\n\ntype WebpackCompilation = {\n outputOptions: {\n path?: string;\n };\n assets: Record<string, unknown>;\n getAssets: () => WebpackAsset[];\n getAsset: (name: string) => WebpackAsset | undefined;\n updateAsset: (name: string, source: WebpackSource) => void;\n hooks: {\n processAssets: {\n tap: (options: { name: string; stage: number }, callback: () => void) => void;\n };\n };\n};\n\ntype WebpackModule = {\n version?: string;\n default?: { version?: string };\n};\n\n// Only used for telemetry; `webpack` is an optional peer dependency and may be absent (e.g. rspack).\nfunction getWebpackMajorVersion(): string | undefined {\n try {\n const webpack = _req('webpack') as WebpackModule;\n const version = webpack.version ?? webpack.default?.version;\n return version?.split('.')[0];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Stamps each JS asset's debug ID into the asset itself and its source map asset.\n *\n * Runs after source maps have been generated, so the JS asset no longer needs to carry\n * source map information and can be replaced with a plain `RawSource`.\n */\nfunction addDebugIdsToAssets(compilation: WebpackCompilation, RawSource: WebpackRawSource): void {\n for (const asset of compilation.getAssets()) {\n if (!isJsFile(asset.name)) {\n continue;\n }\n\n const bundleSource = asset.source.source().toString();\n const relatedSourceMap = asset.info.related?.sourceMap;\n const sourceMapName = typeof relatedSourceMap === 'string' ? relatedSourceMap : `${asset.name}.map`;\n const sourceMapAsset = compilation.getAsset(sourceMapName);\n\n const stamped = stampDebugId(bundleSource, sourceMapAsset?.source.source().toString());\n if (!stamped) {\n continue;\n }\n\n compilation.updateAsset(asset.name, new RawSource(stamped.bundleSource));\n if (stamped.sourceMapSource !== undefined) {\n compilation.updateAsset(sourceMapName, new RawSource(stamped.sourceMapSource));\n }\n }\n}\n\nfunction createSentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? '[sentry-webpack-plugin]',\n buildTool: 'webpack',\n buildToolMajorVersion: getWebpackMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n apply() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n return {\n apply(compiler: WebpackCompiler) {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n const { BannerPlugin, DefinePlugin } = compiler.webpack ?? {};\n\n // Add BannerPlugin for code injection (release, metadata, debug IDs)\n if (!staticInjectionCode.isEmpty() || sourcemapsEnabled) {\n if (!BannerPlugin) {\n logger.warn(\n 'BannerPlugin is not available. Skipping code injection. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(\n new BannerPlugin({\n raw: true,\n include: /\\.(js|ts|jsx|tsx|mjs|cjs)(\\?[^?]*)?(#[^#]*)?$/,\n banner: (arg?: BannerPluginCallbackArg) => {\n const codeToInject = staticInjectionCode.clone();\n if (sourcemapsEnabled) {\n const hash = arg?.chunk?.contentHash?.javascript ?? arg?.chunk?.hash;\n const debugId = hash ? stringToUUID(hash) : randomUUID();\n codeToInject.append(getDebugIdSnippet(debugId));\n }\n return codeToInject.code();\n },\n }),\n );\n }\n }\n\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is skipped\n // with `disable-upload`, so the emitted artifacts get stamped in the asset pipeline instead.\n if (sourcemapsEnabled && options.sourcemaps?.disable === 'disable-upload') {\n const RawSource = compiler.webpack?.sources?.RawSource;\n // Right after source map generation (and thus after minification, which would strip the comment),\n // so later stages (real content hashing, subresource integrity) see the final assets.\n const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING ?? 500) + 1;\n\n if (!RawSource) {\n logger.warn(\n 'Webpack sources are not available. Skipping debug ID injection into emitted source maps. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => {\n compilation.hooks.processAssets.tap({ name: 'sentry-webpack-plugin', stage }, () => {\n addDebugIdsToAssets(compilation, RawSource);\n });\n });\n }\n }\n\n // Add DefinePlugin for bundle size optimizations\n if (transformReplace && DefinePlugin) {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(new DefinePlugin(replacementValues));\n }\n\n // Add component name annotation transform\n if (transformAnnotations?.transform) {\n compiler.options.module = compiler.options.module || {};\n compiler.options.module.rules = compiler.options.module.rules || [];\n compiler.options.module.rules.unshift({\n test: /\\.[jt]sx$/,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [\n {\n loader: COMPONENT_ANNOTATION_LOADER,\n options: {\n transform: transformAnnotations.transform,\n },\n },\n ],\n });\n }\n\n compiler.hooks.afterEmit.tapAsync(\n 'sentry-webpack-plugin',\n (compilation: WebpackCompilation, callback: (err?: Error) => void) => {\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n const run = async (): Promise<void> => {\n try {\n await sentryBuildPluginManager.createRelease();\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const outputPath = compilation.outputOptions.path ?? path.resolve();\n const buildArtifacts = Object.keys(compilation.assets).map(asset => path.join(outputPath, asset));\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n };\n\n run().then(\n () => callback(),\n (err: Error) => callback(err),\n );\n },\n );\n\n if (userOptions._experiments?.forceExitOnBuildCompletion && compiler.options.mode === 'production') {\n compiler.hooks.done.tap('sentry-webpack-plugin', () => {\n setTimeout(() => {\n logger.debug('Exiting process after debug file upload');\n process.exit(0);\n });\n });\n }\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const sentryWebpackPlugin: (options?: SentryWebpackPluginOptions) => any = createSentryWebpackPlugin;\n\nexport type SentryWebpackPluginOptions = Options & {\n _experiments?: Options['_experiments'] & {\n /**\n * If enabled, the webpack plugin will exit the build process after the build completes.\n * Use this with caution, as it will terminate the process.\n *\n * More information: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/345\n *\n * @default false\n */\n forceExitOnBuildCompletion?: boolean;\n };\n};\n"],"names":["createRequire","path","fileURLToPath","isJsFile","stampDebugId","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","stringToUUID","randomUUID","getDebugIdSnippet","createDebugIdUploadFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAM,IAAA,GAAOA,yBAA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,YAA2B;AACrC,YAAA,IAAI;AACF,cAAA,MAAM,yBAAyB,aAAA,EAAc;AAC7C,cAAA,IAAI,iBAAA,IAAqB,OAAA,CAAQ,UAAA,EAAY,OAAA,KAAY,gBAAA,EAAkB;AACzE,gBAAA,MAAM,UAAA,GAAa,WAAA,CAAY,aAAA,CAAc,IAAA,IAAQZ,gBAAK,OAAA,EAAQ;AAClE,gBAAA,MAAM,cAAA,GAAiB,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAM,CAAA,CAAE,GAAA,CAAI,CAAA,KAAA,KAASA,eAAA,CAAK,IAAA,CAAK,UAAA,EAAY,KAAK,CAAC,CAAA;AAChG,gBAAA,MAAM,OAAO,cAAc,CAAA;AAAA,cAC7B;AAAA,YACF,CAAA,SAAE;AACA,cAAA,oCAAA,EAAqC;AACrC,cAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,YACjD;AAAA,UACF,CAAA;AAEA,UAAA,GAAA,EAAI,CAAE,IAAA;AAAA,YACJ,MAAM,QAAA,EAAS;AAAA,YACf,CAAC,GAAA,KAAe,QAAA,CAAS,GAAG;AAAA,WAC9B;AAAA,QACF;AAAA,OACF;AAEA,MAAA,IAAI,YAAY,YAAA,EAAc,0BAAA,IAA8B,QAAA,CAAS,OAAA,CAAQ,SAAS,YAAA,EAAc;AAClG,QAAA,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,uBAAA,EAAyB,MAAM;AACrD,UAAA,UAAA,CAAW,MAAM;AACf,YAAA,MAAA,CAAO,MAAM,yCAAyC,CAAA;AACtD,YAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,UAChB,CAAC,CAAA;AAAA,QACH,CAAC,CAAA;AAAA,MACH;AAAA,IACF;AAAA,GACF;AACF;AAGO,MAAM,mBAAA,GAAqE;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/webpack/index.ts"],"sourcesContent":["/* oxlint-disable max-lines */\n\nimport type { Options } from '../core/index';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n stringToUUID,\n createComponentNameAnnotateHooks,\n CodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n getCodeInjectionPosition,\n isJsFile,\n stampDebugId,\n} from '../core/index';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\nconst _req = createRequire(import.meta.url);\n\n// Resolve the loader path via the package's own exports.\n// This module may end up in a shared chunk (_chunks/) whose import.meta.url\n// does not point to the webpack/ directory where the transform file lives, so\n// a path-relative lookup would fail. Using require.resolve on the package export\n// always finds the correct installed file regardless of chunk placement.\nlet COMPONENT_ANNOTATION_LOADER: string;\ntry {\n COMPONENT_ANNOTATION_LOADER = _req.resolve('@sentry/bundler-plugins/webpack-loader');\n} catch {\n // Fallback for non-packaged environments (e.g., monorepo source runs without dist)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Rollup transpiles import.meta for us for CJS\n const dirname = path.dirname(fileURLToPath(import.meta.url));\n // The Rollup build emits `.js` for both CJS and ESM, so the extension is the same in both.\n COMPONENT_ANNOTATION_LOADER = path.resolve(dirname, 'component-annotation-transform.js');\n}\n\ntype PluginClass = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (options: any): unknown;\n};\n\ntype WebpackSource = {\n source: () => string | Buffer;\n};\n\ntype WebpackRawSource = {\n new (source: string): WebpackSource;\n};\n\ntype WebpackReplaceSource = WebpackSource & {\n insert: (position: number, value: string) => void;\n};\n\nconst WEBPACK_JAVASCRIPT_ASSET_REGEX = /\\.(?:js|ts|jsx|tsx|mjs|cjs|mts|cts)(?:\\?[^?]*)?(?:#[^#]*)?$/;\n\ntype WebpackAsset = {\n name: string;\n source: WebpackSource;\n info: {\n related?: {\n sourceMap?: string | string[];\n };\n };\n};\n\ntype WebpackCompiler = {\n options: {\n plugins?: unknown[];\n mode?: string;\n module?: {\n rules?: unknown[];\n };\n };\n hooks: {\n compilation: {\n tap: (name: string, callback: (compilation: WebpackCompilation) => void) => void;\n };\n thisCompilation: {\n tap: (name: string, callback: (compilation: WebpackCompilation) => void) => void;\n };\n afterEmit: {\n tapAsync: (name: string, callback: (compilation: WebpackCompilation, cb: () => void) => void) => void;\n };\n done: {\n tap: (name: string, callback: () => void) => void;\n };\n };\n webpack?: {\n DefinePlugin?: PluginClass;\n Compilation?: {\n PROCESS_ASSETS_STAGE_ADDITIONS?: number;\n PROCESS_ASSETS_STAGE_DEV_TOOLING?: number;\n };\n sources?: {\n RawSource?: WebpackRawSource;\n ReplaceSource?: new (source: WebpackSource) => WebpackReplaceSource;\n };\n };\n};\n\ntype WebpackCompilation = {\n chunks: Iterable<{\n files: Iterable<string>;\n hash?: string;\n contentHash?: { javascript?: string };\n }>;\n outputOptions: {\n path?: string;\n };\n assets: Record<string, unknown>;\n getAssets: () => WebpackAsset[];\n getAsset: (name: string) => WebpackAsset | undefined;\n updateAsset: (name: string, source: WebpackSource) => void;\n hooks: {\n processAssets: {\n tap: (\n options: { name: string; stage: number },\n callback: (assets: Record<string, WebpackSource>) => void,\n ) => void;\n };\n };\n};\n\ntype WebpackModule = {\n version?: string;\n default?: { version?: string };\n};\n\n// Only used for telemetry; `webpack` is an optional peer dependency and may be absent (e.g. rspack).\nfunction getWebpackMajorVersion(): string | undefined {\n try {\n const webpack = _req('webpack') as WebpackModule;\n const version = webpack.version ?? webpack.default?.version;\n return version?.split('.')[0];\n } catch {\n return undefined;\n }\n}\n\n/**\n * Stamps each JS asset's debug ID into the asset itself and its source map asset.\n *\n * Runs after source maps have been generated, so the JS asset no longer needs to carry\n * source map information and can be replaced with a plain `RawSource`.\n */\nfunction addDebugIdsToAssets(compilation: WebpackCompilation, RawSource: WebpackRawSource): void {\n for (const asset of compilation.getAssets()) {\n if (!isJsFile(asset.name)) {\n continue;\n }\n\n const bundleSource = asset.source.source().toString();\n const relatedSourceMap = asset.info.related?.sourceMap;\n const sourceMapName = typeof relatedSourceMap === 'string' ? relatedSourceMap : `${asset.name}.map`;\n const sourceMapAsset = compilation.getAsset(sourceMapName);\n\n const stamped = stampDebugId(bundleSource, sourceMapAsset?.source.source().toString());\n if (!stamped) {\n continue;\n }\n\n compilation.updateAsset(asset.name, new RawSource(stamped.bundleSource));\n if (stamped.sourceMapSource !== undefined) {\n compilation.updateAsset(sourceMapName, new RawSource(stamped.sourceMapSource));\n }\n }\n}\n\nfunction createSentryWebpackPlugin(userOptions: SentryWebpackPluginOptions = {}) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? '[sentry-webpack-plugin]',\n buildTool: 'webpack',\n buildToolMajorVersion: getWebpackMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n apply() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n function addCodeInjection(compiler: WebpackCompiler): void {\n if (staticInjectionCode.isEmpty() && !sourcemapsEnabled) {\n return;\n }\n\n const ReplaceSource = compiler.webpack?.sources?.ReplaceSource;\n const processAssetsStage = compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_ADDITIONS;\n\n if (!ReplaceSource || processAssetsStage === undefined) {\n logger.warn(\n 'Webpack sources are not available. Skipping code injection. This usually means webpack is not properly configured.',\n );\n return;\n }\n\n compiler.hooks.compilation.tap('sentry-webpack-plugin-injection', compilation => {\n compilation.hooks.processAssets.tap(\n {\n name: 'sentry-webpack-plugin-injection',\n stage: processAssetsStage,\n },\n assets => {\n const injectedAssets = new Set<string>();\n\n for (const chunk of compilation.chunks) {\n for (const assetName of chunk.files) {\n if (injectedAssets.has(assetName) || !WEBPACK_JAVASCRIPT_ASSET_REGEX.test(assetName)) {\n continue;\n }\n\n const source = assets[assetName];\n if (!source) {\n continue;\n }\n injectedAssets.add(assetName);\n\n const sourceContents = source.source();\n const code = typeof sourceContents === 'string' ? sourceContents : Buffer.from(sourceContents).toString();\n const codeToInject = staticInjectionCode.clone();\n if (sourcemapsEnabled) {\n const hash = chunk.contentHash?.javascript ?? chunk.hash;\n codeToInject.append(getDebugIdSnippet(hash ? stringToUUID(hash) : randomUUID()));\n }\n\n const injectionPosition = getCodeInjectionPosition(code);\n const injection = injectionPosition === code.length ? `\\n${codeToInject.code()}` : codeToInject.code();\n const updatedSource = new ReplaceSource(source);\n updatedSource.insert(injectionPosition, injection);\n compilation.updateAsset(assetName, updatedSource);\n }\n }\n },\n );\n });\n }\n\n return {\n apply(compiler: WebpackCompiler) {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n const { DefinePlugin } = compiler.webpack ?? {};\n\n // BannerPlugin prepends executable code before directive prologues.\n addCodeInjection(compiler);\n\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is skipped\n // with `disable-upload`, so the emitted artifacts get stamped in the asset pipeline instead.\n if (sourcemapsEnabled && options.sourcemaps?.disable === 'disable-upload') {\n const RawSource = compiler.webpack?.sources?.RawSource;\n // Right after source map generation (and thus after minification, which would strip the comment),\n // so later stages (real content hashing, subresource integrity) see the final assets.\n const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING ?? 500) + 1;\n\n if (!RawSource) {\n logger.warn(\n 'Webpack sources are not available. Skipping debug ID injection into emitted source maps. This usually means webpack is not properly configured.',\n );\n } else {\n compiler.hooks.thisCompilation.tap('sentry-webpack-plugin', compilation => {\n compilation.hooks.processAssets.tap({ name: 'sentry-webpack-plugin', stage }, () => {\n addDebugIdsToAssets(compilation, RawSource);\n });\n });\n }\n }\n\n // Add DefinePlugin for bundle size optimizations\n if (transformReplace && DefinePlugin) {\n compiler.options.plugins = compiler.options.plugins || [];\n compiler.options.plugins.push(new DefinePlugin(replacementValues));\n }\n\n // Add component name annotation transform\n if (transformAnnotations?.transform) {\n compiler.options.module = compiler.options.module || {};\n compiler.options.module.rules = compiler.options.module.rules || [];\n compiler.options.module.rules.unshift({\n test: /\\.[jt]sx$/,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [\n {\n loader: COMPONENT_ANNOTATION_LOADER,\n options: {\n transform: transformAnnotations.transform,\n },\n },\n ],\n });\n }\n\n compiler.hooks.afterEmit.tapAsync(\n 'sentry-webpack-plugin',\n (compilation: WebpackCompilation, callback: (err?: Error) => void) => {\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n const run = async (): Promise<void> => {\n try {\n await sentryBuildPluginManager.createRelease();\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const outputPath = compilation.outputOptions.path ?? path.resolve();\n const buildArtifacts = Object.keys(compilation.assets).map(asset => path.join(outputPath, asset));\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n };\n\n run().then(\n () => callback(),\n (err: Error) => callback(err),\n );\n },\n );\n\n if (userOptions._experiments?.forceExitOnBuildCompletion && compiler.options.mode === 'production') {\n compiler.hooks.done.tap('sentry-webpack-plugin', () => {\n setTimeout(() => {\n logger.debug('Exiting process after debug file upload');\n process.exit(0);\n });\n });\n }\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const sentryWebpackPlugin: (options?: SentryWebpackPluginOptions) => any = createSentryWebpackPlugin;\n\nexport type SentryWebpackPluginOptions = Options & {\n _experiments?: Options['_experiments'] & {\n /**\n * If enabled, the webpack plugin will exit the build process after the build completes.\n * Use this with caution, as it will terminate the process.\n *\n * More information: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/345\n *\n * @default false\n */\n forceExitOnBuildCompletion?: boolean;\n };\n};\n"],"names":["createRequire","path","fileURLToPath","isJsFile","stampDebugId","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","getDebugIdSnippet","stringToUUID","randomUUID","getCodeInjectionPosition","createDebugIdUploadFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,IAAA,GAAOA,yBAAA,CAAc,kQAAe,CAAA;AAO1C,IAAI,2BAAA;AACJ,IAAI;AACF,EAAA,2BAAA,GAA8B,IAAA,CAAK,QAAQ,wCAAwC,CAAA;AACrF,CAAA,CAAA,MAAQ;AAIN,EAAA,MAAM,UAAUC,eAAA,CAAK,OAAA,CAAQC,sBAAA,CAAc,kQAAe,CAAC,CAAA;AAE3D,EAAA,2BAAA,GAA8BD,eAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,mCAAmC,CAAA;AACzF;AAmBA,MAAM,8BAAA,GAAiC,6DAAA;AA4EvC,SAAS,sBAAA,GAA6C;AACpD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BAAA,MAAM,OAAO,cAAc,CAAA;AAAA,cAC7B;AAAA,YACF,CAAA,SAAE;AACA,cAAA,oCAAA,EAAqC;AACrC,cAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,YACjD;AAAA,UACF,CAAA;AAEA,UAAA,GAAA,EAAI,CAAE,IAAA;AAAA,YACJ,MAAM,QAAA,EAAS;AAAA,YACf,CAAC,GAAA,KAAe,QAAA,CAAS,GAAG;AAAA,WAC9B;AAAA,QACF;AAAA,OACF;AAEA,MAAA,IAAI,YAAY,YAAA,EAAc,0BAAA,IAA8B,QAAA,CAAS,OAAA,CAAQ,SAAS,YAAA,EAAc;AAClG,QAAA,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,GAAA,CAAI,uBAAA,EAAyB,MAAM;AACrD,UAAA,UAAA,CAAW,MAAM;AACf,YAAA,MAAA,CAAO,MAAM,yCAAyC,CAAA;AACtD,YAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,UAChB,CAAC,CAAA;AAAA,QACH,CAAC,CAAA;AAAA,MACH;AAAA,IACF;AAAA,GACF;AACF;AAGO,MAAM,mBAAA,GAAqE;;;;"}
@@ -0,0 +1,85 @@
1
+ function isLineTerminator(character) {
2
+ return character === "\n" || character === "\r" || character === "\u2028" || character === "\u2029";
3
+ }
4
+ function skipTrivia(code, start) {
5
+ let position = start;
6
+ let hasLineBreak = false;
7
+ while (position < code.length) {
8
+ const character = code[position];
9
+ if (/\s/.test(character || "")) {
10
+ hasLineBreak || (hasLineBreak = isLineTerminator(character));
11
+ position++;
12
+ } else if (code.startsWith("//", position) || position === 0 && code.startsWith("#!", position)) {
13
+ let lineEnd = position + 2;
14
+ while (lineEnd < code.length && !isLineTerminator(code[lineEnd])) {
15
+ lineEnd++;
16
+ }
17
+ if (lineEnd === code.length) {
18
+ return { end: code.length, hasLineBreak };
19
+ }
20
+ position = lineEnd + 1;
21
+ hasLineBreak = true;
22
+ } else if (code.startsWith("/*", position)) {
23
+ const commentEnd = code.indexOf("*/", position + 2);
24
+ if (commentEnd === -1) {
25
+ return { end: code.length, hasLineBreak };
26
+ }
27
+ const comment = code.slice(position, commentEnd + 2);
28
+ hasLineBreak || (hasLineBreak = /[\n\r\u2028\u2029]/.test(comment));
29
+ position = commentEnd + 2;
30
+ } else {
31
+ break;
32
+ }
33
+ }
34
+ return { end: position, hasLineBreak };
35
+ }
36
+ function findStringLiteralEnd(code, start) {
37
+ const quote = code[start];
38
+ if (quote !== '"' && quote !== "'") {
39
+ return void 0;
40
+ }
41
+ for (let position = start + 1; position < code.length; position++) {
42
+ const character = code[position];
43
+ if (character === "\\") {
44
+ position += code[position + 1] === "\r" && code[position + 2] === "\n" ? 2 : 1;
45
+ } else if (character === quote) {
46
+ return position + 1;
47
+ } else if (isLineTerminator(character)) {
48
+ return void 0;
49
+ }
50
+ }
51
+ return void 0;
52
+ }
53
+ function startsWithBinaryOperatorKeyword(remainder, keyword) {
54
+ return remainder.startsWith(keyword) && !/^[$_\\\u200C\u200D\p{ID_Continue}]/u.test(remainder.slice(keyword.length));
55
+ }
56
+ function canContinueStringExpression(code, position) {
57
+ const remainder = code.slice(position, position + "instanceof".length + 1);
58
+ if (/^(?:\+\+|--|!(?!=))/.test(remainder)) {
59
+ return false;
60
+ }
61
+ return /^!={1,2}/.test(remainder) || /^[([.`+\-*/%<>=&|^?,:]/.test(remainder) || ["in", "instanceof"].some((keyword) => startsWithBinaryOperatorKeyword(remainder, keyword));
62
+ }
63
+ function getCodeInjectionPosition(code) {
64
+ let position = skipTrivia(code, 0).end;
65
+ let prologueEnd = position;
66
+ while (position < code.length) {
67
+ const stringEnd = findStringLiteralEnd(code, position);
68
+ if (stringEnd === void 0) {
69
+ break;
70
+ }
71
+ const trailingTrivia = skipTrivia(code, stringEnd);
72
+ if (code[trailingTrivia.end] === ";") {
73
+ position = skipTrivia(code, trailingTrivia.end + 1).end;
74
+ } else if (trailingTrivia.end === code.length || trailingTrivia.hasLineBreak && !canContinueStringExpression(code, trailingTrivia.end)) {
75
+ position = trailingTrivia.end;
76
+ } else {
77
+ break;
78
+ }
79
+ prologueEnd = position;
80
+ }
81
+ return prologueEnd;
82
+ }
83
+
84
+ export { getCodeInjectionPosition };
85
+ //# sourceMappingURL=get-code-injection-position.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-code-injection-position.js","sources":["../../../src/core/get-code-injection-position.ts"],"sourcesContent":["function isLineTerminator(character: string | undefined): boolean {\n return character === '\\n' || character === '\\r' || character === '\\u2028' || character === '\\u2029';\n}\n\nfunction skipTrivia(code: string, start: number): { end: number; hasLineBreak: boolean } {\n let position = start;\n let hasLineBreak = false;\n\n while (position < code.length) {\n const character = code[position];\n\n if (/\\s/.test(character || '')) {\n hasLineBreak ||= isLineTerminator(character);\n position++;\n } else if (code.startsWith('//', position) || (position === 0 && code.startsWith('#!', position))) {\n let lineEnd = position + 2;\n while (lineEnd < code.length && !isLineTerminator(code[lineEnd])) {\n lineEnd++;\n }\n if (lineEnd === code.length) {\n return { end: code.length, hasLineBreak };\n }\n position = lineEnd + 1;\n hasLineBreak = true;\n } else if (code.startsWith('/*', position)) {\n const commentEnd = code.indexOf('*/', position + 2);\n if (commentEnd === -1) {\n return { end: code.length, hasLineBreak };\n }\n const comment = code.slice(position, commentEnd + 2);\n hasLineBreak ||= /[\\n\\r\\u2028\\u2029]/.test(comment);\n position = commentEnd + 2;\n } else {\n break;\n }\n }\n\n return { end: position, hasLineBreak };\n}\n\nfunction findStringLiteralEnd(code: string, start: number): number | undefined {\n const quote = code[start];\n if (quote !== '\"' && quote !== \"'\") {\n return undefined;\n }\n\n for (let position = start + 1; position < code.length; position++) {\n const character = code[position];\n if (character === '\\\\') {\n position += code[position + 1] === '\\r' && code[position + 2] === '\\n' ? 2 : 1;\n } else if (character === quote) {\n return position + 1;\n } else if (isLineTerminator(character)) {\n return undefined;\n }\n }\n\n return undefined;\n}\n\nfunction startsWithBinaryOperatorKeyword(remainder: string, keyword: string): boolean {\n return remainder.startsWith(keyword) && !/^[$_\\\\\\u200C\\u200D\\p{ID_Continue}]/u.test(remainder.slice(keyword.length));\n}\n\nfunction canContinueStringExpression(code: string, position: number): boolean {\n const remainder = code.slice(position, position + 'instanceof'.length + 1);\n if (/^(?:\\+\\+|--|!(?!=))/.test(remainder)) {\n return false;\n }\n\n return (\n /^!={1,2}/.test(remainder) ||\n /^[([.`+\\-*/%<>=&|^?,:]/.test(remainder) ||\n ['in', 'instanceof'].some(keyword => startsWithBinaryOperatorKeyword(remainder, keyword))\n );\n}\n\nexport function getCodeInjectionPosition(code: string): number {\n let position = skipTrivia(code, 0).end;\n let prologueEnd = position;\n\n while (position < code.length) {\n const stringEnd = findStringLiteralEnd(code, position);\n if (stringEnd === undefined) {\n break;\n }\n\n const trailingTrivia = skipTrivia(code, stringEnd);\n if (code[trailingTrivia.end] === ';') {\n position = skipTrivia(code, trailingTrivia.end + 1).end;\n } else if (\n trailingTrivia.end === code.length ||\n (trailingTrivia.hasLineBreak && !canContinueStringExpression(code, trailingTrivia.end))\n ) {\n position = trailingTrivia.end;\n } else {\n break;\n }\n\n prologueEnd = position;\n }\n\n return prologueEnd;\n}\n"],"names":[],"mappings":"AAAA,SAAS,iBAAiB,SAAA,EAAwC;AAChE,EAAA,OAAO,cAAc,IAAA,IAAQ,SAAA,KAAc,IAAA,IAAQ,SAAA,KAAc,YAAY,SAAA,KAAc,QAAA;AAC7F;AAEA,SAAS,UAAA,CAAW,MAAc,KAAA,EAAuD;AACvF,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,IAAI,YAAA,GAAe,KAAA;AAEnB,EAAA,OAAO,QAAA,GAAW,KAAK,MAAA,EAAQ;AAC7B,IAAA,MAAM,SAAA,GAAY,KAAK,QAAQ,CAAA;AAE/B,IAAA,IAAI,IAAA,CAAK,IAAA,CAAK,SAAA,IAAa,EAAE,CAAA,EAAG;AAC9B,MAAA,YAAA,KAAA,YAAA,GAAiB,iBAAiB,SAAS,CAAA,CAAA;AAC3C,MAAA,Q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vC,CAAC,IAAA,EAAM,YAAY,CAAA,CAAE,IAAA,CAAK,aAAW,+BAAA,CAAgC,SAAA,EAAW,OAAO,CAAC,CAAA;AAE5F;AAEO,SAAS,yBAAyB,IAAA,EAAsB;AAC7D,EAAA,IAAI,QAAA,GAAW,UAAA,CAAW,IAAA,EAAM,CAAC,CAAA,CAAE,GAAA;AACnC,EAAA,IAAI,WAAA,GAAc,QAAA;AAElB,EAAA,OAAO,QAAA,GAAW,KAAK,MAAA,EAAQ;AAC7B,IAAA,MAAM,SAAA,GAAY,oBAAA,CAAqB,IAAA,EAAM,QAAQ,CAAA;AACrD,IAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,cAAA,GAAiB,UAAA,CAAW,IAAA,EAAM,SAAS,CAAA;AACjD,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,GAAG,CAAA,KAAM,GAAA,EAAK;AACpC,MAAA,QAAA,GAAW,UAAA,CAAW,IAAA,EAAM,cAAA,CAAe,GAAA,GAAM,CAAC,CAAA,CAAE,GAAA;AAAA,IACtD,CAAA,MAAA,IACE,cAAA,CAAe,GAAA,KAAQ,IAAA,CAAK,MAAA,IAC3B,cAAA,CAAe,YAAA,IAAgB,CAAC,2BAAA,CAA4B,IAAA,EAAM,cAAA,CAAe,GAAG,CAAA,EACrF;AACA,MAAA,QAAA,GAAW,cAAA,CAAe,GAAA;AAAA,IAC5B,CAAA,MAAO;AACL,MAAA;AAAA,IACF;AAEA,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB;AAEA,EAAA,OAAO,WAAA;AACT;;;;"}
@@ -2,6 +2,7 @@ import { debug } from '@sentry/core';
2
2
  import { stripQueryAndHashFromPath, CodeInjection, containsOnlyImports } from './utils.js';
3
3
  export { generateModuleMetadataInjectorCode, generateReleaseInjectorCode, replaceBooleanFlagsInCode, stringToUUID } from './utils.js';
4
4
  export { globFiles } from './glob.js';
5
+ export { getCodeInjectionPosition } from './get-code-injection-position.js';
5
6
  export { createSentryBuildPluginManager } from './build-plugin-manager.js';
6
7
  export { addDebugIdToEmittedArtifacts, createDebugIdUploadFunction, stampDebugId } from './debug-id-upload.js';
7
8
 
@@ -20,10 +21,6 @@ function loadBabelAnnotationRuntime() {
20
21
  }
21
22
  return babelAnnotationRuntimePromise;
22
23
  }
23
- const COMMENT_USE_STRICT_REGEX = (
24
- // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.
25
- /^(?:\s*|\/\*(?:.|\r|\n)*?\*\/|\/\/.*[\n\r])*(?:"[^"]*";|'[^']*';)?/
26
- );
27
24
  function isJsFile(fileName) {
28
25
  const cleanFileName = stripQueryAndHashFromPath(fileName);
29
26
  return [".js", ".mjs", ".cjs"].some((ext) => cleanFileName.endsWith(ext));
@@ -87,5 +84,5 @@ function getDebugIdSnippet(debugId) {
87
84
  );
88
85
  }
89
86
 
90
- export { COMMENT_USE_STRICT_REGEX, CodeInjection, createComponentNameAnnotateHooks, getDebugIdSnippet, isJsFile, shouldSkipCodeInjection };
87
+ export { CodeInjection, createComponentNameAnnotateHooks, getDebugIdSnippet, isJsFile, shouldSkipCodeInjection };
91
88
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n// We need to be careful not to inject the snippet before any `\"use strict\";`s.\n// As an additional complication `\"use strict\";`s may come after any number of comments.\nexport const COMMENT_USE_STRICT_REGEX =\n // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.\n /^(?:\\s*|\\/\\*(?:.|\\r|\\n)*?\\*\\/|\\/\\/.*[\\n\\r])*(?:\"[^\"]*\";|'[^']*';)?/;\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\n"],"names":[],"mappings":";;;;;;;AAcA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GAAA,CAAI,CAAC,OAAO,aAAa,GAAG,OAAO,0BAAiB,CAAC,CAAC,CAAA,CAAE,IAAA;AAAA,MAC9F,CAAC,CAAC,KAAA,EAAO,WAAW,CAAA,KAAM;AACxB,QAAA,OAAO;AAAA,UACL,gBAAgB,KAAA,CAAM,cAAA;AAAA,UACtB,6BAA6B,WAAA,CAAY,OAAA;AAAA,UACzC,yCAAyC,WAAA,CAAY;AAAA,SACvD;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,6BAAA;AACT;AAIO,MAAM,wBAAA;AAAA;AAAA,EAEX;AAAA;AAMK,SAAS,SAAS,QAAA,EAA2B;AAClD,EAAA,MAAM,aAAA,GAAgB,0BAA0B,QAAQ,CAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA,CAAE,KAAK,CAAA,GAAA,KAAO,aAAA,CAAc,QAAA,CAAS,GAAG,CAAC,CAAA;AACxE;AAgBO,SAAS,uBAAA,CAAwB,MAAc,cAAA,EAAoD;AAExG,EAAA,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA,EAAG;AAC5B,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,kBAAkB,yBAAA,CAA0B,cAAc,CAAA,CAAE,QAAA,CAAS,OAAO,CAAA,EAAG;AACjF,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ACZ,yBAAA,EAA2B,IAAA;AAAA,YAC3B,OAAA,EAAS;AAAA,WACX;AAAA,UACA,aAAA,EAAe;AAAA,YACb,sBAAA,EAAwB;AAAA,WAC1B;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,QAAQ,IAAA,IAAQ,IAAA;AAAA,UACtB,KAAK,MAAA,EAAQ;AAAA,SACf;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAA,KAAA,CAAM,KAAA,CAAM,yCAAyC,CAAC,CAAA;AAAA,MACxD;AAEA,MAAA,OAAO,EAAE,IAAA,EAAK;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAI,aAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\nexport { getCodeInjectionPosition } from './get-code-injection-position';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\n"],"names":[],"mappings":";;;;;;;;AAcA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GA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F;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAI,aAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;"}
@@ -1,4 +1,4 @@
1
- const LIB_VERSION = "11.0.0-rc.1";
1
+ const LIB_VERSION = "11.0.0";
2
2
 
3
3
  export { LIB_VERSION };
4
4
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.0.0-rc.1\";\n"],"names":[],"mappings":"AAAO,MAAM,WAAA,GAAc;;;;"}
1
+ {"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.0.0\";\n"],"names":[],"mappings":"AAAO,MAAM,WAAA,GAAc;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n addDebugIdToEmittedArtifacts,\n isJsFile,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n write?: boolean;\n absWorkingDir?: string;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled) {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n\n if (options.sourcemaps?.disable !== 'disable-upload') {\n await upload(buildArtifacts);\n } else if (initialOptions.write === false) {\n logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.');\n } else {\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is\n // skipped with `disable-upload`. esbuild has no hook to modify outputs before they are\n // written, so the emitted artifacts get stamped on disk instead.\n const outputDir = initialOptions.absWorkingDir ?? process.cwd();\n await Promise.all(\n buildArtifacts\n .filter(isJsFile)\n .map(bundle =>\n addDebugIdToEmittedArtifacts(\n path.resolve(outputDir, bundle),\n logger,\n options.sourcemaps?.resolveSourceMap,\n ),\n ),\n );\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\n"],"names":[],"mappings":";;;;;;;;AAwEA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAE7B,IAAA,OAAO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,cAAA,CACG,MAAA,CAAO,QAAQ,CAAA,CACf,GAAA;AAAA,kBAAI,CAAA,MAAA,KACH,4BAAA;AAAA,oBACE,IAAA,CAAK,OAAA,CAAQ,SAAA,EAAW,MAAM,CAAA;AAAA,oBAC9B,MAAA;AAAA,oBACA,QAAQ,UAAA,EAAY;AAAA;AACtB;AACF,eACJ;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAA,SAAE;AACA,UAAA,oCAAA,EAAqC;AACrC,UAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n addDebugIdToEmittedArtifacts,\n isJsFile,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n write?: boolean;\n absWorkingDir?: string;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n // esbuild emits injected files after an entry's directive prologue. A banner would precede\n // \"use strict\" and turn it into an ordinary string expression.\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled) {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n\n if (options.sourcemaps?.disable !== 'disable-upload') {\n await upload(buildArtifacts);\n } else if (initialOptions.write === false) {\n logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.');\n } else {\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is\n // skipped with `disable-upload`. esbuild has no hook to modify outputs before they are\n // written, so the emitted artifacts get stamped on disk instead.\n const outputDir = initialOptions.absWorkingDir ?? process.cwd();\n await Promise.all(\n buildArtifacts\n .filter(isJsFile)\n .map(bundle =>\n addDebugIdToEmittedArtifacts(\n path.resolve(outputDir, bundle),\n logger,\n options.sourcemaps?.resolveSourceMap,\n ),\n ),\n );\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\n"],"names":[],"mappings":";;;;;;;;AAwEA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAE7B,IAAA,OAAO,OAAA,CAAQ,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAAA,EACtC,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,M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,SAAA,EAAW,MAAM,CAAA;AAAA,oBAC9B,MAAA;AAAA,oBACA,QAAQ,UAAA,EAAY;AAAA;AACtB;AACF,eACJ;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAA,SAAE;AACA,UAAA,oCAAA,EAAqC;AACrC,UAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.0.0-rc.1","sideEffects":["./sentry-release-injection-file.js","./sentry-esbuild-debugid-injection-file.js"]}
1
+ {"type":"module","version":"11.0.0","sideEffects":["./sentry-release-injection-file.js","./sentry-esbuild-debugid-injection-file.js"]}
@@ -1,4 +1,4 @@
1
- import { createComponentNameAnnotateHooks, isJsFile, shouldSkipCodeInjection, getDebugIdSnippet, COMMENT_USE_STRICT_REGEX } from '../core/index.js';
1
+ import { createComponentNameAnnotateHooks, isJsFile, shouldSkipCodeInjection, getDebugIdSnippet } from '../core/index.js';
2
2
  import MagicString from 'magic-string';
3
3
  import * as path from 'node:path';
4
4
  import { createRequire } from 'node:module';
@@ -6,6 +6,7 @@ import { createSentryBuildPluginManager } from '../core/build-plugin-manager.js'
6
6
  import { CodeInjection, generateReleaseInjectorCode, generateModuleMetadataInjectorCode, stringToUUID, replaceBooleanFlagsInCode } from '../core/utils.js';
7
7
  import { globFiles } from '../core/glob.js';
8
8
  import { stampDebugId, createDebugIdUploadFunction } from '../core/debug-id-upload.js';
9
+ import { getCodeInjectionPosition } from '../core/get-code-injection-position.js';
9
10
 
10
11
  let viteParseAstAsyncPromise;
11
12
  const JS_MODULE_ID_FILTER = /\.[cm]?[jt]sx?(?:[?#].*)?$/;
@@ -150,12 +151,10 @@ function _rollupPluginInternal(userOptions = {}, buildTool, buildToolMajorVersio
150
151
  return null;
151
152
  }
152
153
  const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });
153
- const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];
154
- if (match) {
155
- ms.appendLeft(match.length, injectCode.code());
156
- } else {
157
- ms.prepend(injectCode.code());
158
- }
154
+ const injectionPosition = getCodeInjectionPosition(code);
155
+ const codeToInject = injectionPosition === code.length ? `
156
+ ${injectCode.code()}` : injectCode.code();
157
+ ms.appendLeft(injectionPosition, codeToInject);
159
158
  if (ms?.constructor?.name === "BindingMagicString") {
160
159
  return { code: ms };
161
160
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/rollup/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n stringToUUID,\n COMMENT_USE_STRICT_REGEX,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n stampDebugId,\n} from '../core';\nimport type {\n ComponentAnnotationTransformMeta,\n ComponentAnnotationTransformResult,\n} from '../core/component-annotation-oxc';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\n\n// The subset of Rollup's `TransformResult` that this plugin's `transform`\n// hook actually returns. Defined locally instead of imported from `rollup`\n// because `rollup` is an optional dependency.\ntype TransformResult = { code: string; map?: SourceMap | string | { mappings: string } | null } | null | undefined;\n\n// The subset of Rollup's `OutputBundle` the stamping hook reads.\ntype OutputBundle = Record<\n string,\n | { type: 'chunk'; fileName: string; code: string; sourcemapFileName?: string | null }\n | { type: 'asset'; fileName: string; source: string | Uint8Array }\n>;\n\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\ntype FastAnnotationHooks = {\n transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<ComponentAnnotationTransformResult>;\n};\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\n\nfunction hasExistingDebugID(code: string): boolean {\n // Check if a debug ID has already been injected to avoid duplicate injection (e.g. by another plugin or Sentry CLI)\n const chunkStartSnippet = code.slice(0, 6000);\n const chunkEndSnippet = code.slice(-500);\n\n if (chunkStartSnippet.includes('_sentryDebugIdIdentifier') || chunkEndSnippet.includes('//# debugId=')) {\n return true; // Debug ID already present, skip injection\n }\n\n return false;\n}\n\nfunction getRollupMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const rollup = req('rollup') as { VERSION?: string };\n return rollup.VERSION?.split('.')[0];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nfunction getViteParseAstAsync(): Promise<ViteParseAstAsync | null> {\n if (!viteParseAstAsyncPromise) {\n viteParseAstAsyncPromise = Promise.resolve()\n .then(async () => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Vite is an optional runtime peer for this package\n const viteModule = createRequire(import.meta.url)('vite') as ViteModule;\n\n if (typeof viteModule.parseAstAsync !== 'function') {\n return null;\n }\n\n try {\n await viteModule.parseAstAsync('const x = <div />;', { lang: 'tsx' });\n } catch {\n return null;\n }\n\n return viteModule.parseAstAsync;\n })\n .catch(() => null);\n }\n\n return viteParseAstAsyncPromise;\n}\n\n/**\n * @ignore - this is the internal plugin factory function only used for the Vite plugin!\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _rollupPluginInternal(\n userOptions: Options = {},\n buildTool: 'rollup' | 'vite',\n buildToolMajorVersion?: string,\n) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[sentry-${buildTool}-plugin]`,\n buildTool,\n buildToolMajorVersion: buildToolMajorVersion || getRollupMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-noop-plugin',\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n const transformFastAnnotations =\n options.reactComponentAnnotation?.enabled && !options.reactComponentAnnotation?._experimentalInjectIntoHtml\n ? (() => {\n let fastAnnotationHooksPromise: Promise<FastAnnotationHooks> | undefined;\n\n return {\n transform(code: string, id: string, meta?: ComponentAnnotationTransformMeta) {\n if (!fastAnnotationHooksPromise) {\n fastAnnotationHooksPromise = import('../core/component-annotation-oxc').then(\n ({ createOxcComponentNameAnnotateHooks, getOxcParseAstAsync }) =>\n createOxcComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n // Vite 8 already loads an oxc-based parser, so reuse it.\n buildTool === 'vite' && buildToolMajorVersion === '8'\n ? getViteParseAstAsync\n : getOxcParseAstAsync,\n ),\n );\n }\n\n return fastAnnotationHooksPromise.then(hooks => hooks.transform(code, id, meta));\n },\n };\n })()\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n const shouldTransform = transformAnnotations || transformReplace;\n\n function buildStart(): void {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n }\n\n async function transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<TransformResult> {\n // Component annotations are only in user code and boolean flag replacements are\n // only in Sentry code. If we successfully add annotations, we can return early.\n let shouldRunBabelAnnotations = true;\n\n if (transformFastAnnotations?.transform) {\n const result = await transformFastAnnotations.transform(code, id, meta);\n if (result) {\n return result;\n }\n\n if (result === null) {\n shouldRunBabelAnnotations = false;\n }\n }\n\n if (shouldRunBabelAnnotations && transformAnnotations?.transform) {\n const result = await transformAnnotations.transform(code, id);\n if (result) {\n return result;\n }\n }\n\n if (transformReplace) {\n return replaceBooleanFlagsInCode(code, replacementValues);\n }\n\n return null;\n }\n\n function renderChunk(\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null },\n _?: unknown,\n meta?: { magicString?: MagicString },\n ): {\n code: string;\n map?: SourceMap;\n } | null {\n if (!isJsFile(chunk.fileName)) {\n return null; // returning null means not modifying the chunk at all\n }\n\n // Skip empty chunks and HTML facade chunks (Vite MPA)\n if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) {\n return null;\n }\n\n const injectCode = staticInjectionCode.clone();\n\n if (sourcemapsEnabled && !hasExistingDebugID(code)) {\n const debugId = stringToUUID(code); // generate a deterministic debug ID\n injectCode.append(getDebugIdSnippet(debugId));\n }\n\n if (injectCode.isEmpty()) {\n return null;\n }\n\n const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });\n const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];\n\n if (match) {\n // Add injected code after any comments or \"use strict\" at the beginning of the bundle.\n ms.appendLeft(match.length, injectCode.code());\n } else {\n // ms.replace() doesn't work when there is an empty string match (which happens if\n // there is neither, a comment, nor a \"use strict\" at the top of the chunk) so we\n // need this special case here.\n ms.prepend(injectCode.code());\n }\n\n // Rolldown can pass a native MagicString instance in meta.magicString\n // https://rolldown.rs/in-depth/native-magic-string#usage-examples\n if (ms?.constructor?.name === 'BindingMagicString') {\n // Rolldown docs say to return the magic string instance directly in this case\n return { code: ms as unknown as string };\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ file: chunk.fileName, hires: 'boundary' as unknown as undefined }),\n };\n }\n\n /**\n * Stamps debug IDs into the emitted chunks and source maps.\n *\n * `disable-upload` skips the upload routine (which stamps debug IDs into temp copies), so the emitted\n * artifacts get stamped here instead. Not in `renderChunk`: minifiers running after it would strip the\n * comment. Rollup computes `[hash]` file names before this hook, so only plugins that hash the final\n * assets afterwards (e.g. subresource integrity) see the stamped content.\n */\n function generateBundle(_outputOptions: unknown, bundle: OutputBundle): void {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !isJsFile(output.fileName)) {\n continue;\n }\n\n const sourceMapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];\n const sourceMapSource =\n sourceMapAsset?.type === 'asset' && typeof sourceMapAsset.source === 'string'\n ? sourceMapAsset.source\n : undefined;\n\n const stamped = stampDebugId(output.code, sourceMapSource);\n if (!stamped) {\n continue;\n }\n\n output.code = stamped.bundleSource;\n if (stamped.sourceMapSource !== undefined && sourceMapAsset?.type === 'asset') {\n sourceMapAsset.source = stamped.sourceMapSource;\n }\n }\n }\n\n async function writeBundle(\n outputOptions: { dir?: string; file?: string },\n bundle: { [fileName: string]: unknown },\n ): Promise<void> {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n if (outputOptions.dir) {\n const outputDir = outputOptions.dir;\n const JS_AND_MAP_PATTERNS = [\n '/**/*.js',\n '/**/*.mjs',\n '/**/*.cjs',\n '/**/*.js.map',\n '/**/*.mjs.map',\n '/**/*.cjs.map',\n ].map(q => `${q}?(\\\\?*)?(#*)`); // We want to allow query and hash strings at the end of files\n const buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n await upload(buildArtifacts);\n } else if (outputOptions.file) {\n await upload([outputOptions.file]);\n } else {\n const buildArtifacts = Object.keys(bundle).map(asset => path.join(path.resolve(), asset));\n await upload(buildArtifacts);\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n }\n\n const name = `sentry-${buildTool}-plugin`;\n const transformHook =\n buildTool === 'vite'\n ? {\n filter: { id: JS_MODULE_ID_FILTER },\n handler: transform,\n }\n : transform;\n\n return {\n name,\n buildStart,\n ...(shouldTransform ? { transform: transformHook } : {}),\n renderChunk,\n ...(options.sourcemaps?.disable === 'disable-upload'\n ? { generateBundle: { order: 'pre' as const, handler: generateBundle } }\n : {}),\n writeBundle,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any\nexport function sentryRollupPlugin(userOptions: Options = {}): any {\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return [_rollupPluginInternal(userOptions, 'rollup')];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"names":[],"mappings":";;;;;;;;;AAmDA,IAAI,wBAAA;AAEJ,MAAM,mBAAA,GAAsB,4BAAA;AAE5B,SAAS,mBAAmB,IAAA,EAAuB;AAEjD,EAAA,MAAM,iBAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAI,CAAA;AAC5C,EAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAEvC,EAAA,IAAI,kBAAkB,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'../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n stringToUUID,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n stampDebugId,\n getCodeInjectionPosition,\n} from '../core';\nimport type {\n ComponentAnnotationTransformMeta,\n ComponentAnnotationTransformResult,\n} from '../core/component-annotation-oxc';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\n\n// The subset of Rollup's `TransformResult` that this plugin's `transform`\n// hook actually returns. Defined locally instead of imported from `rollup`\n// because `rollup` is an optional dependency.\ntype TransformResult = { code: string; map?: SourceMap | string | { mappings: string } | null } | null | undefined;\n\n// The subset of Rollup's `OutputBundle` the stamping hook reads.\ntype OutputBundle = Record<\n string,\n | { type: 'chunk'; fileName: string; code: string; sourcemapFileName?: string | null }\n | { type: 'asset'; fileName: string; source: string | Uint8Array }\n>;\n\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\ntype FastAnnotationHooks = {\n transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<ComponentAnnotationTransformResult>;\n};\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\n\nfunction hasExistingDebugID(code: string): boolean {\n // Check if a debug ID has already been injected to avoid duplicate injection (e.g. by another plugin or Sentry CLI)\n const chunkStartSnippet = code.slice(0, 6000);\n const chunkEndSnippet = code.slice(-500);\n\n if (chunkStartSnippet.includes('_sentryDebugIdIdentifier') || chunkEndSnippet.includes('//# debugId=')) {\n return true; // Debug ID already present, skip injection\n }\n\n return false;\n}\n\nfunction getRollupMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const rollup = req('rollup') as { VERSION?: string };\n return rollup.VERSION?.split('.')[0];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nfunction getViteParseAstAsync(): Promise<ViteParseAstAsync | null> {\n if (!viteParseAstAsyncPromise) {\n viteParseAstAsyncPromise = Promise.resolve()\n .then(async () => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Vite is an optional runtime peer for this package\n const viteModule = createRequire(import.meta.url)('vite') as ViteModule;\n\n if (typeof viteModule.parseAstAsync !== 'function') {\n return null;\n }\n\n try {\n await viteModule.parseAstAsync('const x = <div />;', { lang: 'tsx' });\n } catch {\n return null;\n }\n\n return viteModule.parseAstAsync;\n })\n .catch(() => null);\n }\n\n return viteParseAstAsyncPromise;\n}\n\n/**\n * @ignore - this is the internal plugin factory function only used for the Vite plugin!\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _rollupPluginInternal(\n userOptions: Options = {},\n buildTool: 'rollup' | 'vite',\n buildToolMajorVersion?: string,\n) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[sentry-${buildTool}-plugin]`,\n buildTool,\n buildToolMajorVersion: buildToolMajorVersion || getRollupMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-noop-plugin',\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n const transformFastAnnotations =\n options.reactComponentAnnotation?.enabled && !options.reactComponentAnnotation?._experimentalInjectIntoHtml\n ? (() => {\n let fastAnnotationHooksPromise: Promise<FastAnnotationHooks> | undefined;\n\n return {\n transform(code: string, id: string, meta?: ComponentAnnotationTransformMeta) {\n if (!fastAnnotationHooksPromise) {\n fastAnnotationHooksPromise = import('../core/component-annotation-oxc').then(\n ({ createOxcComponentNameAnnotateHooks, getOxcParseAstAsync }) =>\n createOxcComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n // Vite 8 already loads an oxc-based parser, so reuse it.\n buildTool === 'vite' && buildToolMajorVersion === '8'\n ? getViteParseAstAsync\n : getOxcParseAstAsync,\n ),\n );\n }\n\n return fastAnnotationHooksPromise.then(hooks => hooks.transform(code, id, meta));\n },\n };\n })()\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n const shouldTransform = transformAnnotations || transformReplace;\n\n function buildStart(): void {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n }\n\n async function transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<TransformResult> {\n // Component annotations are only in user code and boolean flag replacements are\n // only in Sentry code. If we successfully add annotations, we can return early.\n let shouldRunBabelAnnotations = true;\n\n if (transformFastAnnotations?.transform) {\n const result = await transformFastAnnotations.transform(code, id, meta);\n if (result) {\n return result;\n }\n\n if (result === null) {\n shouldRunBabelAnnotations = false;\n }\n }\n\n if (shouldRunBabelAnnotations && transformAnnotations?.transform) {\n const result = await transformAnnotations.transform(code, id);\n if (result) {\n return result;\n }\n }\n\n if (transformReplace) {\n return replaceBooleanFlagsInCode(code, replacementValues);\n }\n\n return null;\n }\n\n function renderChunk(\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null },\n _?: unknown,\n meta?: { magicString?: MagicString },\n ): {\n code: string;\n map?: SourceMap;\n } | null {\n if (!isJsFile(chunk.fileName)) {\n return null; // returning null means not modifying the chunk at all\n }\n\n // Skip empty chunks and HTML facade chunks (Vite MPA)\n if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) {\n return null;\n }\n\n const injectCode = staticInjectionCode.clone();\n\n if (sourcemapsEnabled && !hasExistingDebugID(code)) {\n const debugId = stringToUUID(code); // generate a deterministic debug ID\n injectCode.append(getDebugIdSnippet(debugId));\n }\n\n if (injectCode.isEmpty()) {\n return null;\n }\n\n const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });\n const injectionPosition = getCodeInjectionPosition(code);\n const codeToInject = injectionPosition === code.length ? `\\n${injectCode.code()}` : injectCode.code();\n ms.appendLeft(injectionPosition, codeToInject);\n\n // Rolldown can pass a native MagicString instance in meta.magicString\n // https://rolldown.rs/in-depth/native-magic-string#usage-examples\n if (ms?.constructor?.name === 'BindingMagicString') {\n // Rolldown docs say to return the magic string instance directly in this case\n return { code: ms as unknown as string };\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ file: chunk.fileName, hires: 'boundary' }),\n };\n }\n\n /**\n * Stamps debug IDs into the emitted chunks and source maps.\n *\n * `disable-upload` skips the upload routine (which stamps debug IDs into temp copies), so the emitted\n * artifacts get stamped here instead. Not in `renderChunk`: minifiers running after it would strip the\n * comment. Rollup computes `[hash]` file names before this hook, so only plugins that hash the final\n * assets afterwards (e.g. subresource integrity) see the stamped content.\n */\n function generateBundle(_outputOptions: unknown, bundle: OutputBundle): void {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !isJsFile(output.fileName)) {\n continue;\n }\n\n const sourceMapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];\n const sourceMapSource =\n sourceMapAsset?.type === 'asset' && typeof sourceMapAsset.source === 'string'\n ? sourceMapAsset.source\n : undefined;\n\n const stamped = stampDebugId(output.code, sourceMapSource);\n if (!stamped) {\n continue;\n }\n\n output.code = stamped.bundleSource;\n if (stamped.sourceMapSource !== undefined && sourceMapAsset?.type === 'asset') {\n sourceMapAsset.source = stamped.sourceMapSource;\n }\n }\n }\n\n async function writeBundle(\n outputOptions: { dir?: string; file?: string },\n bundle: { [fileName: string]: unknown },\n ): Promise<void> {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n if (outputOptions.dir) {\n const outputDir = outputOptions.dir;\n const JS_AND_MAP_PATTERNS = [\n '/**/*.js',\n '/**/*.mjs',\n '/**/*.cjs',\n '/**/*.js.map',\n '/**/*.mjs.map',\n '/**/*.cjs.map',\n ].map(q => `${q}?(\\\\?*)?(#*)`); // We want to allow query and hash strings at the end of files\n const buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n await upload(buildArtifacts);\n } else if (outputOptions.file) {\n await upload([outputOptions.file]);\n } else {\n const buildArtifacts = Object.keys(bundle).map(asset => path.join(path.resolve(), asset));\n await upload(buildArtifacts);\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n }\n\n const name = `sentry-${buildTool}-plugin`;\n const transformHook =\n buildTool === 'vite'\n ? {\n filter: { id: JS_MODULE_ID_FILTER },\n handler: transform,\n }\n : transform;\n\n return {\n name,\n buildStart,\n ...(shouldTransform ? { transform: transformHook } : {}),\n renderChunk,\n ...(options.sourcemaps?.disable === 'disable-upload'\n ? { generateBundle: { order: 'pre' as const, handler: generateBundle } }\n : {}),\n writeBundle,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any\nexport function sentryRollupPlugin(userOptions: Options = {}): any {\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return [_rollupPluginInternal(userOptions, 'rollup')];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"names":[],"mappings":";;;;;;;;;;AAmDA,IAAI,wBAAA;AAEJ,MAAM,mBAAA,GAAsB,4BAAA;AAE5B,SAAS,mBAAmB,IAAA,EAAuB;AAEjD,EAAA,MAAM,iBAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAI,CAAA;AAC5C,EAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAEvC,EAAA,IAAI,kBAAkB,QAAA,CAAS,0BAA0B,KAAK,eAAA,CAAgB,QAAA,CAAS,cAAc,CAAA,EAAG;AACtG,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,qBAAA,GAA4C;AACnD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAM,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACzC,IAAA,MAAM,MAAA,GAAS,IAAI,QAAQ,CAAA;AAC3B,IAAA,OAAO,MAAA,CAAO,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,oBAAA,GAA0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