@sentry/bundler-plugins 11.13.0 → 11.15.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 (89) hide show
  1. package/build/cjs/bun/index.js +6 -2
  2. package/build/cjs/bun/index.js.map +1 -1
  3. package/build/cjs/core/build-plugin-manager.js +6 -2
  4. package/build/cjs/core/build-plugin-manager.js.map +1 -1
  5. package/build/cjs/core/debug-id-upload.js +1 -1
  6. package/build/cjs/core/debug-id-upload.js.map +1 -1
  7. package/build/cjs/core/index.js +3 -0
  8. package/build/cjs/core/index.js.map +1 -1
  9. package/build/cjs/core/options-mapping.js +6 -1
  10. package/build/cjs/core/options-mapping.js.map +1 -1
  11. package/build/cjs/core/sentry/telemetry.js +3 -0
  12. package/build/cjs/core/sentry/telemetry.js.map +1 -1
  13. package/build/cjs/core/sentry/transports.js +1 -1
  14. package/build/cjs/core/sourcemap-settings.js +85 -5
  15. package/build/cjs/core/sourcemap-settings.js.map +1 -1
  16. package/build/cjs/core/utils.js +14 -6
  17. package/build/cjs/core/utils.js.map +1 -1
  18. package/build/cjs/core/version.js +1 -1
  19. package/build/cjs/core/version.js.map +1 -1
  20. package/build/cjs/esbuild/index.js +17 -11
  21. package/build/cjs/esbuild/index.js.map +1 -1
  22. package/build/cjs/rollup/index.js +20 -12
  23. package/build/cjs/rollup/index.js.map +1 -1
  24. package/build/cjs/rollup/source-map-handling.js +19 -1
  25. package/build/cjs/rollup/source-map-handling.js.map +1 -1
  26. package/build/cjs/vite/release-html-injection.js +33 -0
  27. package/build/cjs/vite/release-html-injection.js.map +1 -0
  28. package/build/cjs/vite/source-map-hooks.js +8 -6
  29. package/build/cjs/vite/source-map-hooks.js.map +1 -1
  30. package/build/cjs/webpack/index.js +40 -8
  31. package/build/cjs/webpack/index.js.map +1 -1
  32. package/build/esm/bun/index.js +6 -2
  33. package/build/esm/bun/index.js.map +1 -1
  34. package/build/esm/core/build-plugin-manager.js +7 -3
  35. package/build/esm/core/build-plugin-manager.js.map +1 -1
  36. package/build/esm/core/debug-id-upload.js +1 -1
  37. package/build/esm/core/debug-id-upload.js.map +1 -1
  38. package/build/esm/core/index.js +3 -3
  39. package/build/esm/core/index.js.map +1 -1
  40. package/build/esm/core/options-mapping.js +7 -2
  41. package/build/esm/core/options-mapping.js.map +1 -1
  42. package/build/esm/core/sentry/telemetry.js +3 -0
  43. package/build/esm/core/sentry/telemetry.js.map +1 -1
  44. package/build/esm/core/sentry/transports.js +1 -1
  45. package/build/esm/core/sourcemap-settings.js +84 -6
  46. package/build/esm/core/sourcemap-settings.js.map +1 -1
  47. package/build/esm/core/utils.js +11 -4
  48. package/build/esm/core/utils.js.map +1 -1
  49. package/build/esm/core/version.js +1 -1
  50. package/build/esm/core/version.js.map +1 -1
  51. package/build/esm/esbuild/index.js +17 -11
  52. package/build/esm/esbuild/index.js.map +1 -1
  53. package/build/esm/package.json +1 -1
  54. package/build/esm/rollup/index.js +20 -12
  55. package/build/esm/rollup/index.js.map +1 -1
  56. package/build/esm/rollup/source-map-handling.js +19 -1
  57. package/build/esm/rollup/source-map-handling.js.map +1 -1
  58. package/build/esm/vite/release-html-injection.js +33 -0
  59. package/build/esm/vite/release-html-injection.js.map +1 -0
  60. package/build/esm/vite/source-map-hooks.js +9 -7
  61. package/build/esm/vite/source-map-hooks.js.map +1 -1
  62. package/build/esm/webpack/index.js +40 -8
  63. package/build/esm/webpack/index.js.map +1 -1
  64. package/build/types/bun/index.d.ts.map +1 -1
  65. package/build/types/core/build-plugin-manager.d.ts.map +1 -1
  66. package/build/types/core/debug-id-upload.d.ts +1 -1
  67. package/build/types/core/index.d.ts +2 -2
  68. package/build/types/core/index.d.ts.map +1 -1
  69. package/build/types/core/options-mapping.d.ts +4 -1
  70. package/build/types/core/options-mapping.d.ts.map +1 -1
  71. package/build/types/core/sentry/telemetry.d.ts.map +1 -1
  72. package/build/types/core/sourcemap-settings.d.ts +19 -0
  73. package/build/types/core/sourcemap-settings.d.ts.map +1 -1
  74. package/build/types/core/types.d.ts +54 -1
  75. package/build/types/core/types.d.ts.map +1 -1
  76. package/build/types/core/utils.d.ts +7 -0
  77. package/build/types/core/utils.d.ts.map +1 -1
  78. package/build/types/core/version.d.ts +1 -1
  79. package/build/types/esbuild/index.d.ts.map +1 -1
  80. package/build/types/rollup/index.d.ts +36 -5
  81. package/build/types/rollup/index.d.ts.map +1 -1
  82. package/build/types/rollup/source-map-handling.d.ts +5 -0
  83. package/build/types/rollup/source-map-handling.d.ts.map +1 -1
  84. package/build/types/vite/release-html-injection.d.ts +31 -0
  85. package/build/types/vite/release-html-injection.d.ts.map +1 -0
  86. package/build/types/vite/source-map-hooks.d.ts +1 -0
  87. package/build/types/vite/source-map-hooks.d.ts.map +1 -1
  88. package/build/types/webpack/index.d.ts.map +1 -1
  89. package/package.json +4 -4
@@ -4,12 +4,14 @@ import { globFiles } from "../core/glob.js";
4
4
  import { getCodeInjectionPosition } from "../core/get-code-injection-position.js";
5
5
  import { createComponentNameAnnotateHooks } from "../core/component-annotate-hooks.js";
6
6
  import { createDebugIdUploadFunction } from "../core/debug-id-upload.js";
7
+ import { getSourceMapFeatures } from "../core/sourcemap-settings.js";
7
8
  import { createSentryBuildPluginManager } from "../core/build-plugin-manager.js";
8
9
  import { getDebugIdSnippet, isInitialChunk, isJsFile, shouldSkipCodeInjection } from "../core/index.js";
9
10
  import { finalizeRolldownDebugIds, getDebugIdForChunk, hasExistingDebugID } from "./debug-id-injection.js";
10
11
  import { stampDebugIds } from "./debug-id-stamping.js";
11
12
  import { createSourceMapHandling } from "./source-map-handling.js";
12
13
  import { createViteSourceMapHooks } from "../vite/source-map-hooks.js";
14
+ import { createViteReleaseHtmlInjection } from "../vite/release-html-injection.js";
13
15
  import { createRequire } from "node:module";
14
16
  import MagicString from "magic-string";
15
17
  import * as path from "node:path";
@@ -55,7 +57,7 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
55
57
  if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
56
58
  const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();
57
59
  const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });
58
- const sourcemapsEnabled = options.sourcemaps?.disable !== true;
60
+ const { injectDebugIds, upload: uploadEnabled, stampEmittedFiles } = getSourceMapFeatures(options);
59
61
  const sourceMapHandling = createSourceMapHandling(sentryBuildPluginManager);
60
62
  const releaseInjectionCode = new CodeInjection();
61
63
  const chunkInjectionCode = new CodeInjection();
@@ -66,13 +68,16 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
66
68
  injectBuildInformation: options._experiments.injectBuildInformation || false
67
69
  }));
68
70
  if (Object.keys(bundleMetadata).length > 0) chunkInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));
71
+ const releaseHtmlInjection = options.release.inject === "html" && buildTool === "vite" && !releaseInjectionCode.isEmpty() ? createViteReleaseHtmlInjection(releaseInjectionCode, logger) : void 0;
72
+ if (options.release.inject === "html" && buildTool === "rollup") logger.warn("`release.inject: 'html'` is not supported by the Rollup plugin, because Rollup does not emit HTML. Injecting the release into the startup chunks instead.");
69
73
  const transformAnnotations = options.reactComponentAnnotation?.enabled ? createComponentNameAnnotateHooks(options.reactComponentAnnotation?.ignoredComponents || [], !!options.reactComponentAnnotation?._experimentalInjectIntoHtml, {
70
74
  getParseAstAsync: buildTool === "vite" && buildToolMajorVersion === "8" ? getViteParseAstAsync : void 0,
71
75
  logger
72
76
  }) : void 0;
73
77
  const transformReplace = Object.keys(replacementValues).length > 0;
74
78
  const shouldTransform = transformAnnotations || transformReplace;
75
- function buildStart() {
79
+ function buildStart(inputOptions) {
80
+ releaseHtmlInjection?.buildStart(this, inputOptions);
76
81
  sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {});
77
82
  }
78
83
  async function transform(code, id, meta) {
@@ -87,9 +92,9 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
87
92
  if (!isJsFile(chunk.fileName)) return null;
88
93
  if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) return null;
89
94
  const injectCode = new CodeInjection();
90
- if (isInitialChunk(chunk, meta?.chunks)) injectCode.append(releaseInjectionCode);
95
+ if (!releaseHtmlInjection?.inHtml(this) && isInitialChunk(chunk, meta?.chunks)) injectCode.append(releaseInjectionCode);
91
96
  injectCode.append(chunkInjectionCode);
92
- if (sourcemapsEnabled && !hasExistingDebugID(code)) {
97
+ if (injectDebugIds && !hasExistingDebugID(code)) {
93
98
  const debugId = getDebugIdForChunk(code, !!this?.meta?.rolldownVersion);
94
99
  injectCode.append(getDebugIdSnippet(debugId));
95
100
  }
@@ -111,14 +116,13 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
111
116
  * Resolves Rolldown's placeholder debug IDs, then stamps debug IDs into the emitted chunks and
112
117
  * source maps.
113
118
  *
114
- * `disable-upload` skips the upload routine (which stamps debug IDs into temp copies), so the emitted
115
- * artifacts get stamped here instead. Not in `renderChunk`: minifiers running after it would strip the
116
- * comment. Rollup computes `[hash]` file names before this hook, so only plugins that hash the final
117
- * assets afterwards (e.g. subresource integrity) see the stamped content.
119
+ * Without an upload the emitted artifacts get stamped here. Not in `renderChunk`: minifiers running
120
+ * after it would strip the comment. Rollup computes `[hash]` file names before this hook, so only
121
+ * plugins that hash the final assets afterwards (e.g. subresource integrity) see the stamped content.
118
122
  */
119
123
  function generateBundle(_outputOptions, bundle) {
120
124
  if (this?.meta?.rolldownVersion) finalizeRolldownDebugIds(bundle);
121
- if (options.sourcemaps?.disable !== "disable-upload") return;
125
+ if (!stampEmittedFiles) return;
122
126
  stampDebugIds(bundle, true);
123
127
  }
124
128
  async function writeBundle(outputOptions, bundle) {
@@ -126,7 +130,7 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
126
130
  let stagingHandedOver = false;
127
131
  try {
128
132
  await sentryBuildPluginManager.createRelease();
129
- if (sourcemapsEnabled && options.sourcemaps?.disable !== "disable-upload") {
133
+ if (uploadEnabled) {
130
134
  let buildArtifacts;
131
135
  if (outputOptions.dir) {
132
136
  const outputDir = outputOptions.dir;
@@ -166,7 +170,11 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
166
170
  name,
167
171
  buildStart,
168
172
  ...shouldTransform ? { transform: transformHook } : {},
169
- ...viteSourceMapHooks ? { configResolved: viteSourceMapHooks.configResolved } : { outputOptions: sourceMapHandling.outputOptions },
173
+ ...viteSourceMapHooks ? {
174
+ configResolved: viteSourceMapHooks.configResolved,
175
+ outputOptions: viteSourceMapHooks.outputOptions
176
+ } : { outputOptions: sourceMapHandling.outputOptions },
177
+ ...releaseHtmlInjection ? { transformIndexHtml: releaseHtmlInjection.transformIndexHtml } : {},
170
178
  renderChunk,
171
179
  generateBundle: {
172
180
  order: "pre",
@@ -180,7 +188,7 @@ function _createRollupPluginInternals(userOptions = {}, buildTool, buildToolMajo
180
188
  generateBundle: {
181
189
  order: "post",
182
190
  async handler(outputOptions, bundle, isWrite) {
183
- if (buildTool === "vite" && options.sourcemaps?.disable === "disable-upload") stampDebugIds(bundle, false);
191
+ if (buildTool === "vite" && stampEmittedFiles) stampDebugIds(bundle, false);
184
192
  await sourceMapHandling.stageSourceMaps(outputOptions, bundle, isWrite);
185
193
  }
186
194
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/rollup/index.ts"],"sourcesContent":["import type { ChunkGraphNode, InternalOptions, Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n isInitialChunk,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n getCodeInjectionPosition,\n} from '../core';\nimport type { ComponentAnnotationTransformMeta } 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';\nimport { finalizeRolldownDebugIds, getDebugIdForChunk, hasExistingDebugID } from './debug-id-injection';\nimport { stampDebugIds, type OutputBundle } from './debug-id-stamping';\nimport { createSourceMapHandling, type OutputDestinationOptions } from './source-map-handling';\nimport { createViteSourceMapHooks } from '../vite/source-map-hooks';\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\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\n// Rolldown sets `meta.rolldownVersion` on the plugin context.\ntype PluginContext = { meta?: { rolldownVersion?: string } };\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\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 - internal plugin factory shared by the Rollup and Vite plugins.\n *\n * `main` carries injection, release creation and the upload. `post` runs last in `generateBundle`,\n * copies chunks and their source maps into the upload staging folder and drops the map assets\n * from the bundle, so the bundler never writes them.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _createRollupPluginInternals(\n userOptions: InternalOptions = {},\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 main: {\n name: 'sentry-noop-plugin',\n },\n post: undefined,\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 sourceMapHandling = createSourceMapHandling(sentryBuildPluginManager);\n const releaseInjectionCode = new CodeInjection();\n const chunkInjectionCode = 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 releaseInjectionCode.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 chunkInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n {\n // Vite 8 already loads an oxc-based parser, so reuse it.\n getParseAstAsync: buildTool === 'vite' && buildToolMajorVersion === '8' ? getViteParseAstAsync : undefined,\n logger,\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 if (transformAnnotations) {\n const result = await transformAnnotations.transform(code, id, meta);\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 this: PluginContext | undefined,\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null; isEntry?: boolean },\n _?: unknown,\n meta?: { magicString?: MagicString; chunks?: Record<string, ChunkGraphNode> },\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 = new CodeInjection();\n\n if (isInitialChunk(chunk, meta?.chunks)) {\n injectCode.append(releaseInjectionCode);\n }\n\n injectCode.append(chunkInjectionCode);\n\n if (sourcemapsEnabled && !hasExistingDebugID(code)) {\n const debugId = getDebugIdForChunk(code, !!this?.meta?.rolldownVersion);\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 * Resolves Rolldown's placeholder debug IDs, then stamps debug IDs into the emitted chunks and\n * 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(this: PluginContext | undefined, _outputOptions: unknown, bundle: OutputBundle): void {\n if (this?.meta?.rolldownVersion) {\n finalizeRolldownDebugIds(bundle);\n }\n\n if (options.sourcemaps?.disable !== 'disable-upload') {\n return;\n }\n\n stampDebugIds(bundle, true);\n }\n\n async function writeBundle(outputOptions: OutputDestinationOptions, bundle: OutputBundle | undefined): Promise<void> {\n const staging = await sourceMapHandling.takeStaging(outputOptions, bundle);\n let stagingHandedOver = false;\n\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n let buildArtifacts: string[];\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 buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n } else if (outputOptions.file) {\n buildArtifacts = [outputOptions.file];\n } else {\n buildArtifacts = Object.keys(bundle ?? {}).map(asset => path.join(path.resolve(), asset));\n }\n stagingHandedOver = true;\n await upload(buildArtifacts, { staging });\n } else {\n stagingHandedOver = true;\n await staging?.discard();\n }\n } catch (e) {\n if (!stagingHandedOver) {\n await staging?.keep('The source map upload did not run.');\n }\n throw e;\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 // Vite warns about `rollupOptions.output.sourcemap`, so the Vite plugin\n // decides in a `config` hook instead.\n const viteSourceMapHooks =\n buildTool === 'vite' ? createViteSourceMapHooks(sentryBuildPluginManager, sourceMapHandling) : undefined;\n\n const main = {\n name,\n buildStart,\n ...(shouldTransform ? { transform: transformHook } : {}),\n ...(viteSourceMapHooks\n ? { configResolved: viteSourceMapHooks.configResolved }\n : { outputOptions: sourceMapHandling.outputOptions }),\n renderChunk,\n generateBundle: { order: 'pre' as const, handler: generateBundle },\n writeBundle,\n };\n\n const post = {\n name: buildTool === 'vite' ? 'sentry-vite-upload-staging' : 'sentry-rollup-upload-staging',\n // On the post plugin, so framework plugins that set `build.sourcemap`\n // themselves run first and the decision sees the merged setting.\n ...(viteSourceMapHooks ? { config: viteSourceMapHooks.config } : {}),\n generateBundle: {\n order: 'post' as const,\n async handler(outputOptions: OutputDestinationOptions, bundle: OutputBundle, isWrite?: boolean): Promise<void> {\n if (buildTool === 'vite' && options.sourcemaps?.disable === 'disable-upload') {\n // Vite's module preload rewrite in `generateBundle` regenerates the source map of every\n // chunk with a dynamic import, which drops the debug ID the main plugin stamped in its\n // `pre` hook. Restore it without touching the chunk code, so file hashes stay valid.\n stampDebugIds(bundle, false);\n }\n\n await sourceMapHandling.stageSourceMaps(outputOptions, bundle, isWrite);\n },\n },\n };\n\n return { main, post };\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 return _createRollupPluginInternals(userOptions, buildTool, buildToolMajorVersion).main;\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 const { main, post } = _createRollupPluginInternals(userOptions, 'rollup');\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return post ? [main, post] : [main];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,IAAI;AAKJ,MAAM,sBAAsB;AAE5B,SAAS,wBAA4C;CACnD,IAAI;EAKF,OAFY,cAAc,YAAY,GACrB,CAAC,CAAC,QACP,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC;CACpC,QAAQ,CAER;AAGF;AAEA,SAAS,uBAA0D;CACjE,IAAI,CAAC,0BACH,2BAA2B,QAAQ,QAAQ,CAAC,CACzC,KAAK,YAAY;EAGhB,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC,CAAC,MAAM;EAExD,IAAI,OAAO,WAAW,kBAAkB,YACtC,OAAO;EAGT,IAAI;GACF,MAAM,WAAW,cAAc,sBAAsB,EAAE,MAAM,MAAM,CAAC;EACtE,QAAQ;GACN,OAAO;EACT;EAEA,OAAO,WAAW;CACpB,CAAC,CAAC,CACD,YAAY,IAAI;CAGrB,OAAO;AACT;;;;;;;;AAUA,SAAgB,6BACd,cAA+B,CAAC,GAChC,WACA,uBACA;CACA,MAAM,2BAA2B,+BAA+B,aAAa;EAC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ACjE;EAuBU;EAAG,MAAA;GAnBb,MAAM,cAAc,SAAS,+BAA+B;GAG5D,GAAI,qBAAqB,EAAE,QAAQ,mBAAmB,OAAO,IAAI,CAAC;GAClE,gBAAgB;IACd,OAAO;IACP,MAAM,QAAQ,eAAyC,QAAsB,SAAkC;KAC7G,IAAI,cAAc,UAAU,QAAQ,YAAY,YAAY,kBAI1D,cAAc,QAAQ,KAAK;KAG7B,MAAM,kBAAkB,gBAAgB,eAAe,QAAQ,OAAO;IACxE;GACF;EAGgB;CAAE;AACtB;;;;AAMA,SAAgB,sBACd,cAAuB,CAAC,GACxB,WACA,uBACA;CACA,OAAO,6BAA6B,aAAa,WAAW,qBAAqB,CAAC,CAAC;AACrF;AAGA,SAAgB,mBAAmB,cAAuB,CAAC,GAAQ;CACjE,MAAM,EAAE,MAAM,SAAS,6BAA6B,aAAa,QAAQ;CAGzE,OAAO,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI;AACpC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/rollup/index.ts"],"sourcesContent":["import type { ChunkGraphNode, InternalOptions, Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n isInitialChunk,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n getCodeInjectionPosition,\n getSourceMapFeatures,\n} from '../core';\nimport type { ComponentAnnotationTransformMeta } 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';\nimport { finalizeRolldownDebugIds, getDebugIdForChunk, hasExistingDebugID } from './debug-id-injection';\nimport { stampDebugIds, type OutputBundle } from './debug-id-stamping';\nimport { createSourceMapHandling, type OutputDestinationOptions } from './source-map-handling';\nimport { createViteSourceMapHooks } from '../vite/source-map-hooks';\nimport {\n createViteReleaseHtmlInjection,\n type BuildInputOptions,\n type ViteHookContext,\n} from '../vite/release-html-injection';\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\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\n// Rolldown sets `meta.rolldownVersion` on the plugin context.\ntype PluginContext = ViteHookContext & { meta?: { rolldownVersion?: string } };\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\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 - internal plugin factory shared by the Rollup and Vite plugins.\n *\n * `main` carries injection, release creation and the upload. `post` runs last in `generateBundle`,\n * copies chunks and their source maps into the upload staging folder and drops the map assets\n * from the bundle, so the bundler never writes them.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _createRollupPluginInternals(\n userOptions: InternalOptions = {},\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 main: {\n name: 'sentry-noop-plugin',\n },\n post: undefined,\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 { injectDebugIds, upload: uploadEnabled, stampEmittedFiles } = getSourceMapFeatures(options);\n const sourceMapHandling = createSourceMapHandling(sentryBuildPluginManager);\n const releaseInjectionCode = new CodeInjection();\n const chunkInjectionCode = 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 releaseInjectionCode.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 chunkInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const releaseHtmlInjection =\n options.release.inject === 'html' && buildTool === 'vite' && !releaseInjectionCode.isEmpty()\n ? createViteReleaseHtmlInjection(releaseInjectionCode, logger)\n : undefined;\n\n if (options.release.inject === 'html' && buildTool === 'rollup') {\n logger.warn(\n \"`release.inject: 'html'` is not supported by the Rollup plugin, because Rollup does not emit HTML. Injecting the release into the startup chunks instead.\",\n );\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n {\n // Vite 8 already loads an oxc-based parser, so reuse it.\n getParseAstAsync: buildTool === 'vite' && buildToolMajorVersion === '8' ? getViteParseAstAsync : undefined,\n logger,\n },\n )\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n const shouldTransform = transformAnnotations || transformReplace;\n\n function buildStart(this: ViteHookContext | undefined, inputOptions?: BuildInputOptions): void {\n releaseHtmlInjection?.buildStart(this, inputOptions);\n\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 if (transformAnnotations) {\n const result = await transformAnnotations.transform(code, id, meta);\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 this: PluginContext | undefined,\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null; isEntry?: boolean },\n _?: unknown,\n meta?: { magicString?: MagicString; chunks?: Record<string, ChunkGraphNode> },\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 = new CodeInjection();\n\n if (!releaseHtmlInjection?.inHtml(this) && isInitialChunk(chunk, meta?.chunks)) {\n injectCode.append(releaseInjectionCode);\n }\n\n injectCode.append(chunkInjectionCode);\n\n if (injectDebugIds && !hasExistingDebugID(code)) {\n const debugId = getDebugIdForChunk(code, !!this?.meta?.rolldownVersion);\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 * Resolves Rolldown's placeholder debug IDs, then stamps debug IDs into the emitted chunks and\n * source maps.\n *\n * Without an upload the emitted artifacts get stamped here. Not in `renderChunk`: minifiers running\n * after it would strip the comment. Rollup computes `[hash]` file names before this hook, so only\n * plugins that hash the final assets afterwards (e.g. subresource integrity) see the stamped content.\n */\n function generateBundle(this: PluginContext | undefined, _outputOptions: unknown, bundle: OutputBundle): void {\n if (this?.meta?.rolldownVersion) {\n finalizeRolldownDebugIds(bundle);\n }\n\n if (!stampEmittedFiles) {\n return;\n }\n\n stampDebugIds(bundle, true);\n }\n\n async function writeBundle(outputOptions: OutputDestinationOptions, bundle: OutputBundle | undefined): Promise<void> {\n const staging = await sourceMapHandling.takeStaging(outputOptions, bundle);\n let stagingHandedOver = false;\n\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (uploadEnabled) {\n let buildArtifacts: string[];\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 buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n } else if (outputOptions.file) {\n buildArtifacts = [outputOptions.file];\n } else {\n buildArtifacts = Object.keys(bundle ?? {}).map(asset => path.join(path.resolve(), asset));\n }\n stagingHandedOver = true;\n await upload(buildArtifacts, { staging });\n } else {\n stagingHandedOver = true;\n await staging?.discard();\n }\n } catch (e) {\n if (!stagingHandedOver) {\n await staging?.keep('The source map upload did not run.');\n }\n throw e;\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 // Vite warns about `rollupOptions.output.sourcemap`, so the Vite plugin\n // decides in a `config` hook instead.\n const viteSourceMapHooks =\n buildTool === 'vite' ? createViteSourceMapHooks(sentryBuildPluginManager, sourceMapHandling) : undefined;\n\n const main = {\n name,\n buildStart,\n ...(shouldTransform ? { transform: transformHook } : {}),\n ...(viteSourceMapHooks\n ? { configResolved: viteSourceMapHooks.configResolved, outputOptions: viteSourceMapHooks.outputOptions }\n : { outputOptions: sourceMapHandling.outputOptions }),\n ...(releaseHtmlInjection ? { transformIndexHtml: releaseHtmlInjection.transformIndexHtml } : {}),\n renderChunk,\n generateBundle: { order: 'pre' as const, handler: generateBundle },\n writeBundle,\n };\n\n const post = {\n name: buildTool === 'vite' ? 'sentry-vite-upload-staging' : 'sentry-rollup-upload-staging',\n // On the post plugin, so framework plugins that set `build.sourcemap`\n // themselves run first and the decision sees the merged setting.\n ...(viteSourceMapHooks ? { config: viteSourceMapHooks.config } : {}),\n generateBundle: {\n order: 'post' as const,\n async handler(outputOptions: OutputDestinationOptions, bundle: OutputBundle, isWrite?: boolean): Promise<void> {\n if (buildTool === 'vite' && stampEmittedFiles) {\n // Vite's module preload rewrite in `generateBundle` regenerates the source map of every\n // chunk with a dynamic import, which drops the debug ID the main plugin stamped in its\n // `pre` hook. Restore it without touching the chunk code, so file hashes stay valid.\n stampDebugIds(bundle, false);\n }\n\n await sourceMapHandling.stageSourceMaps(outputOptions, bundle, isWrite);\n },\n },\n };\n\n return { main, post };\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 return _createRollupPluginInternals(userOptions, buildTool, buildToolMajorVersion).main;\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 const { main, post } = _createRollupPluginInternals(userOptions, 'rollup');\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return post ? [main, post] : [main];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,IAAI;AAKJ,MAAM,sBAAsB;AAE5B,SAAS,wBAA4C;CACnD,IAAI;EAKF,OAFY,cAAc,YAAY,GACrB,CAAC,CAAC,QACP,CAAC,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC;CACpC,QAAQ,CAER;AAGF;AAEA,SAAS,uBAA0D;CACjE,IAAI,CAAC,0BACH,2BAA2B,QAAQ,QAAQ,CAAC,CACzC,KAAK,YAAY;EAGhB,MAAM,aAAa,cAAc,YAAY,GAAG,CAAC,CAAC,MAAM;EAExD,IAAI,OAAO,WAAW,kBAAkB,YACtC,OAAO;EAGT,IAAI;GACF,MAAM,WAAW,cAAc,sBAAsB,EAAE,MAAM,MAAM,CAAC;EACtE,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,yBAAyB,gBAAgB;EACjD;CACF;CAEA,MAAM,OAAO,UAAU,UAAU;CACjC,MAAM,gBACJ,cAAc,SACV;EACE,QAAQ,EAAE,IAAI,oBAAoB;EAClC,SAAS;CACX,IACA;CAIN,MAAM,qBACJ,cAAc,SAAS,yBAAyB,0BAA0B,iBAAiB,IAAI,KAAA;CAmCjG,OAAO;EAAE,MAAA;GAhCP;GACA;GACA,GAAI,kBAAkB,EAAE,WAAW,cAAc,IAAI,CAAC;GACtD,GAAI,qBACA;IAAE,gBAAgB,mBAAmB;IAAgB,eAAe,mBAAmB;GAAc,IACrG,EAAE,eAAe,kBAAkB,cAAc;GACrD,GAAI,uBAAuB,EAAE,oBAAoB,qBAAqB,mBAAmB,IAAI,CAAC;GAC9F;GACA,gBAAgB;IAAE,OAAO;IAAgB,SAAS;GAAe;GACjE;EAuBU;EAAG,MAAA;GAnBb,MAAM,cAAc,SAAS,+BAA+B;GAG5D,GAAI,qBAAqB,EAAE,QAAQ,mBAAmB,OAAO,IAAI,CAAC;GAClE,gBAAgB;IACd,OAAO;IACP,MAAM,QAAQ,eAAyC,QAAsB,SAAkC;KAC7G,IAAI,cAAc,UAAU,mBAI1B,cAAc,QAAQ,KAAK;KAG7B,MAAM,kBAAkB,gBAAgB,eAAe,QAAQ,OAAO;IACxE;GACF;EAGgB;CAAE;AACtB;;;;AAMA,SAAgB,sBACd,cAAuB,CAAC,GACxB,WACA,uBACA;CACA,OAAO,6BAA6B,aAAa,WAAW,qBAAqB,CAAC,CAAC;AACrF;AAGA,SAAgB,mBAAmB,cAAuB,CAAC,GAAQ;CACjE,MAAM,EAAE,MAAM,SAAS,6BAA6B,aAAa,QAAQ;CAGzE,OAAO,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI;AACpC"}
@@ -108,6 +108,23 @@ function createSourceMapHandling(sentryBuildPluginManager) {
108
108
  return decision.enableHidden ? outputOptions : null;
109
109
  },
110
110
  setDecision,
111
+ applyHiddenDecision: (rawOutputOptions) => {
112
+ if (rawOutputOptions.sourcemap !== true) return null;
113
+ const destination = getOutputDestination(rawOutputOptions);
114
+ const record = findDecision(destination, rawOutputOptions);
115
+ if (!record?.decision.enableHidden) return null;
116
+ setDecision(destination, {
117
+ ...record,
118
+ match: {
119
+ ...record.match,
120
+ sourcemap: "hidden"
121
+ }
122
+ });
123
+ return {
124
+ ...rawOutputOptions,
125
+ sourcemap: "hidden"
126
+ };
127
+ },
111
128
  stageSourceMaps: async (outputOptions, bundle, isWrite) => {
112
129
  const destination = getOutputDestination(outputOptions);
113
130
  const record = findDecision(destination, outputOptions);
@@ -119,7 +136,8 @@ function createSourceMapHandling(sentryBuildPluginManager) {
119
136
  sentryBuildPluginManager.sourceMaps.logDecision(record.decision);
120
137
  if (!record.decision.deleteAfterUpload) return;
121
138
  const removeAll = record.decision.removeAllSourceMaps === true;
122
- if (removeAll && record.kind !== "unset") dropAssetSourceMaps(bundle);
139
+ const deleteAll = sentryBuildPluginManager.normalizedOptions.sourcemaps?.delete === true;
140
+ if (removeAll && (record.kind !== "unset" || deleteAll)) dropAssetSourceMaps(bundle);
123
141
  if (!sentryBuildPluginManager.sourceMaps.uploadPossible) {
124
142
  dropSourceMaps(bundle, removeAll ? void 0 : (fileName) => sentryBuildPluginManager.sourceMaps.shouldUpload(path.join(destination, fileName)));
125
143
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"source-map-handling.js","names":[],"sources":["../../../src/rollup/source-map-handling.ts"],"sourcesContent":["import * as path from 'node:path';\nimport type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind, UploadStaging } from '../core';\nimport { isJsFile } from '../core';\nimport type { OutputBundle } from './debug-id-stamping';\n\nexport type RollupSourceMapSetting = boolean | 'inline' | 'hidden' | undefined;\n\nexport type OutputDestinationOptions = { dir?: string; file?: string };\n\n/**\n * The output options that tell outputs of one directory apart. Several outputs can write into the\n * same directory at once, for example an ES and a CJS build, each with its own `sourcemap` setting.\n * `sourcemap` holds the setting as the plugin left it, so an output it switched to hidden maps\n * differs from one the user set.\n */\nexport type OutputMatch = {\n dir?: unknown;\n file?: unknown;\n format?: unknown;\n entryFileNames?: unknown;\n chunkFileNames?: unknown;\n preserveModules?: unknown;\n sourcemap?: unknown;\n};\n\nexport type OutputOptions = OutputDestinationOptions & OutputMatch & { sourcemap?: RollupSourceMapSetting };\n\n/** Maps Rollup's (and Vite's) `sourcemap` setting onto the plugin's source map kinds. */\nexport function sourceMapKindFromRollupSetting(setting: RollupSourceMapSetting): SourceMapKind {\n switch (setting) {\n case undefined:\n return 'unset';\n case false:\n return 'off';\n case true:\n return 'visible';\n default:\n return setting;\n }\n}\n\n/** The directory an output writes to. Decisions and stagings are keyed by it. */\nexport function getOutputDestination(outputOptions: OutputDestinationOptions): string {\n return path.resolve(outputOptions.dir ?? path.dirname(outputOptions.file ?? '.'));\n}\n\nconst MATCH_KEYS = [\n 'dir',\n 'file',\n 'format',\n 'entryFileNames',\n 'chunkFileNames',\n 'preserveModules',\n 'sourcemap',\n] as const;\n\n/** The raw options accept aliases that the normalized options do not carry. */\nfunction normalizeFormat(format: unknown): unknown {\n switch (format) {\n case 'esm':\n case 'module':\n return 'es';\n case 'commonjs':\n return 'cjs';\n case 'systemjs':\n return 'system';\n default:\n return format;\n }\n}\n\n/** The fields of `OutputMatch` an output sets, in the form the normalized options carry them. */\nexport function getOutputMatch(outputOptions: OutputMatch): OutputMatch {\n const match: OutputMatch = {};\n for (const key of MATCH_KEYS) {\n const value = outputOptions[key];\n if (value === undefined) {\n continue;\n }\n match[key] =\n key === 'format' ? normalizeFormat(value) : key === 'dir' || key === 'file' ? path.resolve(String(value)) : value;\n }\n return match;\n}\n\nfunction matchesOutput(match: OutputMatch, outputOptions: OutputMatch): boolean {\n const actual = getOutputMatch(outputOptions);\n return MATCH_KEYS.every(key => match[key] === undefined || match[key] === actual[key]);\n}\n\nfunction isSameMatch(a: OutputMatch, b: OutputMatch): boolean {\n return MATCH_KEYS.every(key => a[key] === b[key]);\n}\n\nfunction countMatchFields(match: OutputMatch): number {\n return MATCH_KEYS.filter(key => match[key] !== undefined).length;\n}\n\nconst DEBUG_ID_PATTERN = /sentry-dbid-([0-9a-f-]{36})|\\/\\/# debugId=([0-9a-f-]{36})/i;\n\n/** Identifies the chunks of a bundle by name and debug ID, so a staging can be matched to its write. */\nfunction getBundleSignature(bundle: OutputBundle): string {\n const entries: string[] = [];\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk' && isJsFile(output.fileName)) {\n const match = output.code.match(DEBUG_ID_PATTERN);\n entries.push(`${output.fileName}:${match?.[1] ?? match?.[2] ?? ''}`);\n }\n }\n return entries.sort().join('\\n');\n}\n\nfunction getSourceMapFileName(output: { fileName: string; sourcemapFileName?: string | null }): string {\n return output.sourcemapFileName ?? `${output.fileName}.map`;\n}\n\ntype PendingStaging = { staging: UploadStaging; signature: string; match: OutputMatch };\n\nexport type DecisionRecord = { match: OutputMatch; kind: SourceMapKind; decision: SourceMapDecision };\n\nexport type SourceMapHandling = {\n /** Rollup's `outputOptions` hook: decides for the output and switches it to hidden source maps when needed. */\n outputOptions: (rawOutputOptions: OutputOptions) => OutputOptions | null;\n /** Records the decision for an output, for bundlers that decide outside `outputOptions`. */\n setDecision: (destination: string, record: DecisionRecord) => void;\n /**\n * `generateBundle` with `order: 'post'`: copies each chunk and its source map into a staging folder\n * and drops the map asset from the bundle, so the bundler never writes it.\n */\n stageSourceMaps: (outputOptions: OutputOptions, bundle: OutputBundle, isWrite?: boolean) => Promise<void>;\n /**\n * Hands the staging of this bundle to `writeBundle`. Without a bundle (SvelteKit calls the hook\n * with output options only) the oldest staging is taken.\n */\n takeStaging: (\n outputOptions: OutputDestinationOptions,\n bundle: OutputBundle | undefined,\n ) => Promise<UploadStaging | undefined>;\n};\n\n/**\n * Source map decisions and upload stagings of one plugin instance. Keyed by output destination\n * because one instance can serve several outputs, and watch mode or several `write()` calls\n * rebuild the same one. Outputs that share a directory are told apart by `OutputMatch`.\n */\nexport function createSourceMapHandling(sentryBuildPluginManager: SentryBuildPluginManager): SourceMapHandling {\n const decisions = new Map<string, DecisionRecord[]>();\n const pendingStagings = new Map<string, PendingStaging[]>();\n\n function setDecision(destination: string, record: DecisionRecord): void {\n const records = decisions.get(destination) ?? [];\n const index = records.findIndex(existing => isSameMatch(existing.match, record.match));\n if (index === -1) {\n records.push(record);\n } else {\n records[index] = record;\n }\n decisions.set(destination, records);\n }\n\n function findDecision(destination: string, outputOptions: OutputOptions): DecisionRecord | undefined {\n const candidates = (decisions.get(destination) ?? []).filter(record => matchesOutput(record.match, outputOptions));\n // The record that sets the most fields describes this output best. Equal\n // candidates keep their order, so the first one recorded wins.\n return candidates.sort((a, b) => countMatchFields(b.match) - countMatchFields(a.match))[0];\n }\n\n function dropSourceMaps(bundle: OutputBundle, shouldDrop: (fileName: string) => boolean = () => true): void {\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk' && isJsFile(output.fileName) && shouldDrop(output.fileName)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[getSourceMapFileName(output)];\n }\n }\n }\n\n // Other plugins emit maps as assets, e.g. for CSS or for Vite worker\n // bundles. Chunk maps stay here, because staging still needs them.\n function dropAssetSourceMaps(bundle: OutputBundle): void {\n const chunkMaps = new Set<string>();\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk') {\n chunkMaps.add(getSourceMapFileName(output));\n }\n }\n for (const [fileName, output] of Object.entries(bundle)) {\n if (output.type === 'asset' && fileName.endsWith('.map') && !chunkMaps.has(fileName)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[fileName];\n }\n }\n }\n\n return {\n outputOptions: rawOutputOptions => {\n const kind = sourceMapKindFromRollupSetting(rawOutputOptions.sourcemap);\n // Logged in `generateBundle`, which knows whether the output is written.\n const decision = sentryBuildPluginManager.sourceMaps.decide(kind, { log: false });\n const outputOptions = decision.enableHidden\n ? { ...rawOutputOptions, sourcemap: 'hidden' as const }\n : rawOutputOptions;\n setDecision(getOutputDestination(rawOutputOptions), { match: getOutputMatch(outputOptions), kind, decision });\n\n return decision.enableHidden ? outputOptions : null;\n },\n\n setDecision,\n\n stageSourceMaps: async (outputOptions, bundle, isWrite) => {\n const destination = getOutputDestination(outputOptions);\n const record = findDecision(destination, outputOptions);\n if (!record) {\n return;\n }\n\n // `generate()` never reaches `writeBundle`, so nothing would upload a staging. Maps the\n // plugin turned on are dropped, so the result holds what the user configured.\n if (isWrite === false) {\n if (record.kind === 'unset' && record.decision.enableHidden) {\n dropSourceMaps(bundle);\n }\n return;\n }\n\n sentryBuildPluginManager.sourceMaps.logDecision(record.decision);\n if (!record.decision.deleteAfterUpload) {\n return;\n }\n\n const removeAll = record.decision.removeAllSourceMaps === true;\n // With `unset` the plugin only turned on the chunk maps. Asset maps\n // come from other plugins' own settings.\n if (removeAll && record.kind !== 'unset') {\n dropAssetSourceMaps(bundle);\n }\n\n if (!sentryBuildPluginManager.sourceMaps.uploadPossible) {\n dropSourceMaps(\n bundle,\n removeAll\n ? undefined\n : fileName => sentryBuildPluginManager.sourceMaps.shouldUpload(path.join(destination, fileName)),\n );\n return;\n }\n\n const staging = await sentryBuildPluginManager.createUploadStaging();\n\n try {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !isJsFile(output.fileName)) {\n continue;\n }\n\n const mapFileName = getSourceMapFileName(output);\n const mapAsset = bundle[mapFileName];\n if (mapAsset?.type !== 'asset' || typeof mapAsset.source !== 'string') {\n continue;\n }\n\n const result = await staging.stage({\n code: output.code,\n mapSource: mapAsset.source,\n mapDir: path.join(destination, path.dirname(mapFileName)),\n chunkPath: path.join(destination, output.fileName),\n });\n\n // A map the plugin or the SDK turned on never reaches the output,\n // whether or not the chunk is uploaded. A map the user enabled\n // stays unless it was staged.\n if (result === 'staged' || removeAll) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[mapFileName];\n }\n if (result === 'skipped' || result === 'failed') {\n sentryBuildPluginManager.logger.warn(\n removeAll\n ? `Could not prepare ${output.fileName} for upload, so it is not uploaded and its source map ${mapFileName} was removed from the build output.`\n : `Could not prepare ${output.fileName} for upload, so its source map ${mapFileName} stays in the build output.`,\n );\n }\n }\n } catch (e) {\n // The error fails the build before anything is written.\n await staging.discard();\n throw e;\n }\n\n // A staging of the same output that no `writeBundle` took belongs to a\n // write that never finished. Stagings of other outputs to this directory\n // may still be in flight, so the shared list changes in place and without\n // an await in between.\n const stagings = pendingStagings.get(destination) ?? [];\n pendingStagings.set(destination, stagings);\n const superseded = stagings.filter(pending => isSameMatch(pending.match, record.match));\n for (const pending of superseded) {\n stagings.splice(stagings.indexOf(pending), 1);\n }\n stagings.push({ staging, signature: getBundleSignature(bundle), match: record.match });\n\n for (const pending of superseded) {\n sentryBuildPluginManager.logger.debug(\n `Discarding staged source maps of an earlier build of ${destination} that was never written.`,\n );\n await pending.staging.discard();\n }\n },\n\n takeStaging: async (outputOptions, bundle) => {\n const destination = getOutputDestination(outputOptions);\n const stagings = pendingStagings.get(destination) ?? [];\n\n if (!bundle) {\n return stagings.shift()?.staging;\n }\n\n const signature = getBundleSignature(bundle);\n const index = stagings.findIndex(pending => pending.signature === signature);\n return index === -1 ? undefined : stagings.splice(index, 1)[0]?.staging;\n },\n };\n}\n"],"mappings":";;;;AA4BA,SAAgB,+BAA+B,SAAgD;CAC7F,QAAQ,SAAR;EACE,KAAK,KAAA,GACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,MACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;AAGA,SAAgB,qBAAqB,eAAiD;CACpF,OAAO,KAAK,QAAQ,cAAc,OAAO,KAAK,QAAQ,cAAc,QAAQ,GAAG,CAAC;AAClF;AAEA,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,gBAAgB,QAA0B;CACjD,QAAQ,QAAR;EACE,KAAK;EACL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,yBAAyB,OAAO,KAC9B,YACI,qBAAqB,OAAO,SAAS,wDAAwD,YAAY,uCACzG,qBAAqB,OAAO,SAAS,iCAAiC,YAAY,4BACxF;IAEJ;GACF,SAAS,GAAG;IAEV,MAAM,QAAQ,QAAQ;IACtB,MAAM;GACR;GAMA,MAAM,WAAW,gBAAgB,IAAI,WAAW,KAAK,CAAC;GACtD,gBAAgB,IAAI,aAAa,QAAQ;GACzC,MAAM,aAAa,SAAS,QAAO,YAAW,YAAY,QAAQ,OAAO,OAAO,KAAK,CAAC;GACtF,KAAK,MAAM,WAAW,YACpB,SAAS,OAAO,SAAS,QAAQ,OAAO,GAAG,CAAC;GAE9C,SAAS,KAAK;IAAE;IAAS,WAAW,mBAAmB,MAAM;IAAG,OAAO,OAAO;GAAM,CAAC;GAErF,KAAK,MAAM,WAAW,YAAY;IAChC,yBAAyB,OAAO,MAC9B,wDAAwD,YAAY,yBACtE;IACA,MAAM,QAAQ,QAAQ,QAAQ;GAChC;EACF;EAEA,aAAa,OAAO,eAAe,WAAW;GAC5C,MAAM,cAAc,qBAAqB,aAAa;GACtD,MAAM,WAAW,gBAAgB,IAAI,WAAW,KAAK,CAAC;GAEtD,IAAI,CAAC,QACH,OAAO,SAAS,MAAM,CAAC,EAAE;GAG3B,MAAM,YAAY,mBAAmB,MAAM;GAC3C,MAAM,QAAQ,SAAS,WAAU,YAAW,QAAQ,cAAc,SAAS;GAC3E,OAAO,UAAU,KAAK,KAAA,IAAY,SAAS,OAAO,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;EAClE;CACF;AACF"}
1
+ {"version":3,"file":"source-map-handling.js","names":[],"sources":["../../../src/rollup/source-map-handling.ts"],"sourcesContent":["import * as path from 'node:path';\nimport type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind, UploadStaging } from '../core';\nimport { isJsFile } from '../core';\nimport type { OutputBundle } from './debug-id-stamping';\n\nexport type RollupSourceMapSetting = boolean | 'inline' | 'hidden' | undefined;\n\nexport type OutputDestinationOptions = { dir?: string; file?: string };\n\n/**\n * The output options that tell outputs of one directory apart. Several outputs can write into the\n * same directory at once, for example an ES and a CJS build, each with its own `sourcemap` setting.\n * `sourcemap` holds the setting as the plugin left it, so an output it switched to hidden maps\n * differs from one the user set.\n */\nexport type OutputMatch = {\n dir?: unknown;\n file?: unknown;\n format?: unknown;\n entryFileNames?: unknown;\n chunkFileNames?: unknown;\n preserveModules?: unknown;\n sourcemap?: unknown;\n};\n\nexport type OutputOptions = OutputDestinationOptions & OutputMatch & { sourcemap?: RollupSourceMapSetting };\n\n/** Maps Rollup's (and Vite's) `sourcemap` setting onto the plugin's source map kinds. */\nexport function sourceMapKindFromRollupSetting(setting: RollupSourceMapSetting): SourceMapKind {\n switch (setting) {\n case undefined:\n return 'unset';\n case false:\n return 'off';\n case true:\n return 'visible';\n default:\n return setting;\n }\n}\n\n/** The directory an output writes to. Decisions and stagings are keyed by it. */\nexport function getOutputDestination(outputOptions: OutputDestinationOptions): string {\n return path.resolve(outputOptions.dir ?? path.dirname(outputOptions.file ?? '.'));\n}\n\nconst MATCH_KEYS = [\n 'dir',\n 'file',\n 'format',\n 'entryFileNames',\n 'chunkFileNames',\n 'preserveModules',\n 'sourcemap',\n] as const;\n\n/** The raw options accept aliases that the normalized options do not carry. */\nfunction normalizeFormat(format: unknown): unknown {\n switch (format) {\n case 'esm':\n case 'module':\n return 'es';\n case 'commonjs':\n return 'cjs';\n case 'systemjs':\n return 'system';\n default:\n return format;\n }\n}\n\n/** The fields of `OutputMatch` an output sets, in the form the normalized options carry them. */\nexport function getOutputMatch(outputOptions: OutputMatch): OutputMatch {\n const match: OutputMatch = {};\n for (const key of MATCH_KEYS) {\n const value = outputOptions[key];\n if (value === undefined) {\n continue;\n }\n match[key] =\n key === 'format' ? normalizeFormat(value) : key === 'dir' || key === 'file' ? path.resolve(String(value)) : value;\n }\n return match;\n}\n\nfunction matchesOutput(match: OutputMatch, outputOptions: OutputMatch): boolean {\n const actual = getOutputMatch(outputOptions);\n return MATCH_KEYS.every(key => match[key] === undefined || match[key] === actual[key]);\n}\n\nfunction isSameMatch(a: OutputMatch, b: OutputMatch): boolean {\n return MATCH_KEYS.every(key => a[key] === b[key]);\n}\n\nfunction countMatchFields(match: OutputMatch): number {\n return MATCH_KEYS.filter(key => match[key] !== undefined).length;\n}\n\nconst DEBUG_ID_PATTERN = /sentry-dbid-([0-9a-f-]{36})|\\/\\/# debugId=([0-9a-f-]{36})/i;\n\n/** Identifies the chunks of a bundle by name and debug ID, so a staging can be matched to its write. */\nfunction getBundleSignature(bundle: OutputBundle): string {\n const entries: string[] = [];\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk' && isJsFile(output.fileName)) {\n const match = output.code.match(DEBUG_ID_PATTERN);\n entries.push(`${output.fileName}:${match?.[1] ?? match?.[2] ?? ''}`);\n }\n }\n return entries.sort().join('\\n');\n}\n\nfunction getSourceMapFileName(output: { fileName: string; sourcemapFileName?: string | null }): string {\n return output.sourcemapFileName ?? `${output.fileName}.map`;\n}\n\ntype PendingStaging = { staging: UploadStaging; signature: string; match: OutputMatch };\n\nexport type DecisionRecord = { match: OutputMatch; kind: SourceMapKind; decision: SourceMapDecision };\n\nexport type SourceMapHandling = {\n /** Rollup's `outputOptions` hook: decides for the output and switches it to hidden source maps when needed. */\n outputOptions: (rawOutputOptions: OutputOptions) => OutputOptions | null;\n /** Records the decision for an output, for bundlers that decide outside `outputOptions`. */\n setDecision: (destination: string, record: DecisionRecord) => void;\n /**\n * Vite's `outputOptions` hook: switches an output with its own visible setting to hidden source\n * maps when its recorded decision removes them.\n */\n applyHiddenDecision: (rawOutputOptions: OutputOptions) => OutputOptions | null;\n /**\n * `generateBundle` with `order: 'post'`: copies each chunk and its source map into a staging folder\n * and drops the map asset from the bundle, so the bundler never writes it.\n */\n stageSourceMaps: (outputOptions: OutputOptions, bundle: OutputBundle, isWrite?: boolean) => Promise<void>;\n /**\n * Hands the staging of this bundle to `writeBundle`. Without a bundle (SvelteKit calls the hook\n * with output options only) the oldest staging is taken.\n */\n takeStaging: (\n outputOptions: OutputDestinationOptions,\n bundle: OutputBundle | undefined,\n ) => Promise<UploadStaging | undefined>;\n};\n\n/**\n * Source map decisions and upload stagings of one plugin instance. Keyed by output destination\n * because one instance can serve several outputs, and watch mode or several `write()` calls\n * rebuild the same one. Outputs that share a directory are told apart by `OutputMatch`.\n */\nexport function createSourceMapHandling(sentryBuildPluginManager: SentryBuildPluginManager): SourceMapHandling {\n const decisions = new Map<string, DecisionRecord[]>();\n const pendingStagings = new Map<string, PendingStaging[]>();\n\n function setDecision(destination: string, record: DecisionRecord): void {\n const records = decisions.get(destination) ?? [];\n const index = records.findIndex(existing => isSameMatch(existing.match, record.match));\n if (index === -1) {\n records.push(record);\n } else {\n records[index] = record;\n }\n decisions.set(destination, records);\n }\n\n function findDecision(destination: string, outputOptions: OutputOptions): DecisionRecord | undefined {\n const candidates = (decisions.get(destination) ?? []).filter(record => matchesOutput(record.match, outputOptions));\n // The record that sets the most fields describes this output best. Equal\n // candidates keep their order, so the first one recorded wins.\n return candidates.sort((a, b) => countMatchFields(b.match) - countMatchFields(a.match))[0];\n }\n\n function dropSourceMaps(bundle: OutputBundle, shouldDrop: (fileName: string) => boolean = () => true): void {\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk' && isJsFile(output.fileName) && shouldDrop(output.fileName)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[getSourceMapFileName(output)];\n }\n }\n }\n\n // Other plugins emit maps as assets, e.g. for CSS or for Vite worker\n // bundles. Chunk maps stay here, because staging still needs them.\n function dropAssetSourceMaps(bundle: OutputBundle): void {\n const chunkMaps = new Set<string>();\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk') {\n chunkMaps.add(getSourceMapFileName(output));\n }\n }\n for (const [fileName, output] of Object.entries(bundle)) {\n if (output.type === 'asset' && fileName.endsWith('.map') && !chunkMaps.has(fileName)) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[fileName];\n }\n }\n }\n\n return {\n outputOptions: rawOutputOptions => {\n const kind = sourceMapKindFromRollupSetting(rawOutputOptions.sourcemap);\n // Logged in `generateBundle`, which knows whether the output is written.\n const decision = sentryBuildPluginManager.sourceMaps.decide(kind, { log: false });\n const outputOptions = decision.enableHidden\n ? { ...rawOutputOptions, sourcemap: 'hidden' as const }\n : rawOutputOptions;\n setDecision(getOutputDestination(rawOutputOptions), { match: getOutputMatch(outputOptions), kind, decision });\n\n return decision.enableHidden ? outputOptions : null;\n },\n\n setDecision,\n\n applyHiddenDecision: rawOutputOptions => {\n if (rawOutputOptions.sourcemap !== true) {\n return null;\n }\n const destination = getOutputDestination(rawOutputOptions);\n const record = findDecision(destination, rawOutputOptions);\n if (!record?.decision.enableHidden) {\n return null;\n }\n // Later hooks see the hidden setting, so the record has to match it.\n setDecision(destination, { ...record, match: { ...record.match, sourcemap: 'hidden' } });\n return { ...rawOutputOptions, sourcemap: 'hidden' };\n },\n\n stageSourceMaps: async (outputOptions, bundle, isWrite) => {\n const destination = getOutputDestination(outputOptions);\n const record = findDecision(destination, outputOptions);\n if (!record) {\n return;\n }\n\n // `generate()` never reaches `writeBundle`, so nothing would upload a staging. Maps the\n // plugin turned on are dropped, so the result holds what the user configured.\n if (isWrite === false) {\n if (record.kind === 'unset' && record.decision.enableHidden) {\n dropSourceMaps(bundle);\n }\n return;\n }\n\n sentryBuildPluginManager.sourceMaps.logDecision(record.decision);\n if (!record.decision.deleteAfterUpload) {\n return;\n }\n\n const removeAll = record.decision.removeAllSourceMaps === true;\n // With `unset` the plugin only turned on the chunk maps. Asset maps\n // come from other plugins' own settings. `sourcemaps.delete: true`\n // removes them too, because it applies to every map of the build.\n const deleteAll = sentryBuildPluginManager.normalizedOptions.sourcemaps?.delete === true;\n if (removeAll && (record.kind !== 'unset' || deleteAll)) {\n dropAssetSourceMaps(bundle);\n }\n\n if (!sentryBuildPluginManager.sourceMaps.uploadPossible) {\n dropSourceMaps(\n bundle,\n removeAll\n ? undefined\n : fileName => sentryBuildPluginManager.sourceMaps.shouldUpload(path.join(destination, fileName)),\n );\n return;\n }\n\n const staging = await sentryBuildPluginManager.createUploadStaging();\n\n try {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !isJsFile(output.fileName)) {\n continue;\n }\n\n const mapFileName = getSourceMapFileName(output);\n const mapAsset = bundle[mapFileName];\n if (mapAsset?.type !== 'asset' || typeof mapAsset.source !== 'string') {\n continue;\n }\n\n const result = await staging.stage({\n code: output.code,\n mapSource: mapAsset.source,\n mapDir: path.join(destination, path.dirname(mapFileName)),\n chunkPath: path.join(destination, output.fileName),\n });\n\n // A map the plugin or the SDK turned on never reaches the output,\n // whether or not the chunk is uploaded. A map the user enabled\n // stays unless it was staged.\n if (result === 'staged' || removeAll) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- Rollup drops an asset when its key is deleted from the bundle\n delete bundle[mapFileName];\n }\n if (result === 'skipped' || result === 'failed') {\n sentryBuildPluginManager.logger.warn(\n removeAll\n ? `Could not prepare ${output.fileName} for upload, so it is not uploaded and its source map ${mapFileName} was removed from the build output.`\n : `Could not prepare ${output.fileName} for upload, so its source map ${mapFileName} stays in the build output.`,\n );\n }\n }\n } catch (e) {\n // The error fails the build before anything is written.\n await staging.discard();\n throw e;\n }\n\n // A staging of the same output that no `writeBundle` took belongs to a\n // write that never finished. Stagings of other outputs to this directory\n // may still be in flight, so the shared list changes in place and without\n // an await in between.\n const stagings = pendingStagings.get(destination) ?? [];\n pendingStagings.set(destination, stagings);\n const superseded = stagings.filter(pending => isSameMatch(pending.match, record.match));\n for (const pending of superseded) {\n stagings.splice(stagings.indexOf(pending), 1);\n }\n stagings.push({ staging, signature: getBundleSignature(bundle), match: record.match });\n\n for (const pending of superseded) {\n sentryBuildPluginManager.logger.debug(\n `Discarding staged source maps of an earlier build of ${destination} that was never written.`,\n );\n await pending.staging.discard();\n }\n },\n\n takeStaging: async (outputOptions, bundle) => {\n const destination = getOutputDestination(outputOptions);\n const stagings = pendingStagings.get(destination) ?? [];\n\n if (!bundle) {\n return stagings.shift()?.staging;\n }\n\n const signature = getBundleSignature(bundle);\n const index = stagings.findIndex(pending => pending.signature === signature);\n return index === -1 ? undefined : stagings.splice(index, 1)[0]?.staging;\n },\n };\n}\n"],"mappings":";;;;AA4BA,SAAgB,+BAA+B,SAAgD;CAC7F,QAAQ,SAAR;EACE,KAAK,KAAA,GACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,MACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;AAGA,SAAgB,qBAAqB,eAAiD;CACpF,OAAO,KAAK,QAAQ,cAAc,OAAO,KAAK,QAAQ,cAAc,QAAQ,GAAG,CAAC;AAClF;AAEA,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,gBAAgB,QAA0B;CACjD,QAAQ,QAAR;EACE,KAAK;EACL,KAAK,UACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;AAGA,SAAgB,eAAe,eAAyC;CACtE,MAAM,QAAqB,CAAC;CAC5B,KAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,QAAQ,cAAc;EAC5B,IAAI,UAAU,KAAA,GACZ;EAEF,MAAM,OACJ,QAAQ,WAAW,gBAAgB,KAAK,IAAI,QAAQ,SAAS,QAAQ,SAAS,KAAK,QAAQ,OAAO,KAAK,CAAC,IAAI;CAChH;CACA,OAAO;AACT;AAEA,SAAS,cAAc,OAAoB,eAAqC;CAC9E,MAAM,SAAS,eAAe,aAAa;CAC3C,OAAO,WAAW,OAAM,QAAO,MAAM,SAAS,KAAA,KAAa,MAAM,SAAS,OAAO,IAAI;AACvF;AAEA,SAAS,YAAY,GAAgB,GAAyB;CAC5D,OAAO,WAAW,OAAM,QAAO,EAAE,SAAS,EAAE,IAAI;AAClD;AAEA,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IAAI,aAAa,QAAQ;GACzC,MAAM,aAAa,SAAS,QAAO,YAAW,YAAY,QAAQ,OAAO,OAAO,KAAK,CAAC;GACtF,KAAK,MAAM,WAAW,YACpB,SAAS,OAAO,SAAS,QAAQ,OAAO,GAAG,CAAC;GAE9C,SAAS,KAAK;IAAE;IAAS,WAAW,mBAAmB,MAAM;IAAG,OAAO,OAAO;GAAM,CAAC;GAErF,KAAK,MAAM,WAAW,YAAY;IAChC,yBAAyB,OAAO,MAC9B,wDAAwD,YAAY,yBACtE;IACA,MAAM,QAAQ,QAAQ,QAAQ;GAChC;EACF;EAEA,aAAa,OAAO,eAAe,WAAW;GAC5C,MAAM,cAAc,qBAAqB,aAAa;GACtD,MAAM,WAAW,gBAAgB,IAAI,WAAW,KAAK,CAAC;GAEtD,IAAI,CAAC,QACH,OAAO,SAAS,MAAM,CAAC,EAAE;GAG3B,MAAM,YAAY,mBAAmB,MAAM;GAC3C,MAAM,QAAQ,SAAS,WAAU,YAAW,QAAQ,cAAc,SAAS;GAC3E,OAAO,UAAU,KAAK,KAAA,IAAY,SAAS,OAAO,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;EAClE;CACF;AACF"}
@@ -0,0 +1,33 @@
1
+ // src/vite/release-html-injection.ts
2
+ /**
3
+ * Puts the release snippet into the HTML pages of a Vite build (`release.inject: 'html'`), so the
4
+ * content hashes of the chunks do not change when only the release changes.
5
+ */
6
+ function createViteReleaseHtmlInjection(releaseInjectionCode, logger) {
7
+ const inHtmlByEnvironment = /* @__PURE__ */ new WeakMap();
8
+ let inHtmlWithoutEnvironment = false;
9
+ let warned = false;
10
+ return {
11
+ inHtml: (context) => context?.environment ? inHtmlByEnvironment.get(context.environment) ?? false : inHtmlWithoutEnvironment,
12
+ buildStart(context, inputOptions) {
13
+ const inHtml = Object.values(inputOptions?.input ?? {}).some((input) => /\.html$/.test(input));
14
+ if (context?.environment) inHtmlByEnvironment.set(context.environment, inHtml);
15
+ else inHtmlWithoutEnvironment = inHtml;
16
+ if (!inHtml && !warned && context?.environment?.config?.consumer !== "server") {
17
+ warned = true;
18
+ logger.warn("`release.inject: 'html'` needs a build with HTML entry points, and this build has none. Injecting the release into the startup chunks instead.");
19
+ }
20
+ },
21
+ transformIndexHtml(_html, ctx) {
22
+ if (ctx.server) return;
23
+ return [{
24
+ tag: "script",
25
+ children: releaseInjectionCode.code(),
26
+ injectTo: "head"
27
+ }];
28
+ }
29
+ };
30
+ }
31
+ export { createViteReleaseHtmlInjection };
32
+
33
+ //# sourceMappingURL=release-html-injection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"release-html-injection.js","names":[],"sources":["../../../src/vite/release-html-injection.ts"],"sourcesContent":["import type { CodeInjection, Logger } from '../core';\n\n// Vite 6+ sets `environment` on the plugin context.\nexport type ViteHookContext = { environment?: { config?: { consumer?: string } } };\n\nexport type BuildInputOptions = { input?: string[] | Record<string, string> };\n\ntype HtmlTagDescriptor = { tag: string; children: string; injectTo: 'head' };\n\nexport type ViteReleaseHtmlInjection = {\n /** Whether the build of the hook's environment puts the release into its HTML pages instead of its chunks. */\n inHtml: (context: ViteHookContext | undefined) => boolean;\n buildStart: (context: ViteHookContext | undefined, inputOptions: BuildInputOptions | undefined) => void;\n transformIndexHtml: (html: string, ctx: { server?: unknown }) => HtmlTagDescriptor[] | undefined;\n};\n\n/**\n * Puts the release snippet into the HTML pages of a Vite build (`release.inject: 'html'`), so the\n * content hashes of the chunks do not change when only the release changes.\n */\nexport function createViteReleaseHtmlInjection(\n releaseInjectionCode: CodeInjection,\n logger: Logger,\n): ViteReleaseHtmlInjection {\n // Only a build with HTML entry points runs `transformIndexHtml`. Without one, the release goes\n // into the chunks so it is not lost.\n // In Vite 6+, one plugin instance serves every environment, and environments can build in parallel.\n const inHtmlByEnvironment = new WeakMap<object, boolean>();\n let inHtmlWithoutEnvironment = false;\n let warned = false;\n\n return {\n inHtml: context =>\n context?.environment ? (inHtmlByEnvironment.get(context.environment) ?? false) : inHtmlWithoutEnvironment,\n\n buildStart(context, inputOptions) {\n const inHtml = Object.values(inputOptions?.input ?? {}).some(input => /\\.html$/.test(input));\n if (context?.environment) {\n inHtmlByEnvironment.set(context.environment, inHtml);\n } else {\n inHtmlWithoutEnvironment = inHtml;\n }\n\n // The server build of an SSR app has no HTML, and browsers do not cache its chunks.\n if (!inHtml && !warned && context?.environment?.config?.consumer !== 'server') {\n warned = true;\n logger.warn(\n \"`release.inject: 'html'` needs a build with HTML entry points, and this build has none. Injecting the release into the startup chunks instead.\",\n );\n }\n },\n\n transformIndexHtml(_html, ctx) {\n // The dev server does not inject the release into chunks either.\n if (ctx.server) {\n return undefined;\n }\n // Vite emits its entry scripts as deferred module scripts, so this runs before them.\n return [{ tag: 'script', children: releaseInjectionCode.code(), injectTo: 'head' }];\n },\n };\n}\n"],"mappings":";;;;;AAoBA,SAAgB,+BACd,sBACA,QAC0B;CAI1B,MAAM,sCAAsB,IAAI,QAAyB;CACzD,IAAI,2BAA2B;CAC/B,IAAI,SAAS;CAEb,OAAO;EACL,SAAQ,YACN,SAAS,cAAe,oBAAoB,IAAI,QAAQ,WAAW,KAAK,QAAS;EAEnF,WAAW,SAAS,cAAc;GAChC,MAAM,SAAS,OAAO,OAAO,cAAc,SAAS,CAAC,CAAC,CAAC,CAAC,MAAK,UAAS,UAAU,KAAK,KAAK,CAAC;GAC3F,IAAI,SAAS,aACX,oBAAoB,IAAI,QAAQ,aAAa,MAAM;QAEnD,2BAA2B;GAI7B,IAAI,CAAC,UAAU,CAAC,UAAU,SAAS,aAAa,QAAQ,aAAa,UAAU;IAC7E,SAAS;IACT,OAAO,KACL,gJACF;GACF;EACF;EAEA,mBAAmB,OAAO,KAAK;GAE7B,IAAI,IAAI,QACN;GAGF,OAAO,CAAC;IAAE,KAAK;IAAU,UAAU,qBAAqB,KAAK;IAAG,UAAU;GAAO,CAAC;EACpF;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps } from "../core/sourcemap-settings.js";
1
+ import { getDeleteOption, getSdkEnabledSourceMaps } from "../core/sourcemap-settings.js";
2
2
  import "../core/index.js";
3
3
  import { getOutputMatch, sourceMapKindFromRollupSetting } from "../rollup/source-map-handling.js";
4
4
  import * as path from "node:path";
@@ -75,18 +75,19 @@ function createViteSourceMapHooks(sentryBuildPluginManager, sourceMapHandling) {
75
75
  };
76
76
  const environmentName = decisions.has(name) ? name : void 0;
77
77
  const { normalizedOptions } = sentryBuildPluginManager;
78
- const deleteOption = getDeleteSourcemapsAfterUpload(normalizedOptions, environmentName);
79
- const sdkEnabledSourceMaps = getSdkEnabledSourceMaps(normalizedOptions, environmentName);
78
+ const deleteOption = getDeleteOption(normalizedOptions, environmentName);
79
+ const removeAll = normalizedOptions.sourcemaps?.delete === true || getSdkEnabledSourceMaps(normalizedOptions, environmentName);
80
80
  for (const output of getOutputs(config.root, environment.build)) {
81
81
  if (output.ownSetting) {
82
82
  const outputKind = sourceMapKindFromRollupSetting(output.sourcemap);
83
- const removeAllSourceMaps = sdkEnabledSourceMaps && (outputKind === "hidden" || outputKind === "visible");
83
+ const removeAllSourceMaps = removeAll && (outputKind === "hidden" || outputKind === "visible");
84
+ const deleteAfterUpload = deleteOption === true && (outputKind === "hidden" || removeAllSourceMaps);
84
85
  sourceMapHandling.setDecision(output.destination, {
85
86
  match: output.match,
86
87
  kind: outputKind,
87
88
  decision: {
88
- enableHidden: false,
89
- deleteAfterUpload: deleteOption === true && (outputKind === "hidden" || removeAllSourceMaps),
89
+ enableHidden: outputKind === "visible" && deleteAfterUpload,
90
+ deleteAfterUpload,
90
91
  removeAllSourceMaps
91
92
  }
92
93
  });
@@ -106,7 +107,8 @@ function createViteSourceMapHooks(sentryBuildPluginManager, sourceMapHandling) {
106
107
  });
107
108
  }
108
109
  }
109
- }
110
+ },
111
+ outputOptions: sourceMapHandling.applyHiddenDecision
110
112
  };
111
113
  }
112
114
  export { createViteSourceMapHooks };
@@ -1 +1 @@
1
- {"version":3,"file":"source-map-hooks.js","names":[],"sources":["../../../src/vite/source-map-hooks.ts"],"sourcesContent":["import * as path from 'node:path';\nimport type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind } from '../core';\nimport { getDeleteSourcemapsAfterUpload, getSdkEnabledSourceMaps } from '../core';\nimport type { OutputMatch, RollupSourceMapSetting, SourceMapHandling } from '../rollup/source-map-handling';\nimport { getOutputMatch, sourceMapKindFromRollupSetting } from '../rollup/source-map-handling';\n\ntype BundlerOutput = OutputMatch & { dir?: string; sourcemap?: RollupSourceMapSetting };\ntype BundlerOutputOptions = BundlerOutput | BundlerOutput[] | undefined;\n\ntype ViteBuildOptions = {\n sourcemap?: RollupSourceMapSetting;\n outDir?: string;\n rollupOptions?: { output?: BundlerOutputOptions };\n rolldownOptions?: { output?: BundlerOutputOptions };\n};\n\nexport type ViteUserConfig = {\n build?: ViteBuildOptions;\n environments?: Record<string, { build?: ViteBuildOptions } | undefined>;\n};\n\nexport type ViteResolvedConfig = {\n root: string;\n build: ViteBuildOptions;\n environments?: Record<string, { build: ViteBuildOptions }>;\n};\n\nexport type ViteSourceMapHooks = {\n config: (userConfig: ViteUserConfig, env: { command: string }) => ViteUserConfig | null;\n configResolved: (config: ViteResolvedConfig) => void;\n};\n\nconst NO_CHANGE: SourceMapDecision = { enableHidden: false, deleteAfterUpload: false };\n\ntype EnvironmentOutput = {\n destination: string;\n match: OutputMatch;\n sourcemap: RollupSourceMapSetting;\n /** The output sets `sourcemap` itself, which overrides `build.sourcemap`. */\n ownSetting: boolean;\n};\n\n/**\n * The outputs an environment writes: one per entry of `rollupOptions.output` or\n * `rolldownOptions.output`. An output writes to `build.outDir` (relative to the root) unless it\n * sets its own `dir`, which the bundler resolves from the working directory. An output's own\n * `sourcemap` overrides `build.sourcemap`.\n */\nfunction getOutputs(root: string, build: ViteBuildOptions): EnvironmentOutput[] {\n const configured = build.rolldownOptions?.output ?? build.rollupOptions?.output;\n const outputs = Array.isArray(configured) ? configured : [configured ?? {}];\n\n return outputs.map(output => {\n const sourcemap = output.sourcemap ?? build.sourcemap;\n return {\n destination: output.dir === undefined ? path.resolve(root, build.outDir ?? 'dist') : path.resolve(output.dir),\n match: getOutputMatch({ ...output, sourcemap }),\n sourcemap,\n ownSetting: output.sourcemap !== undefined,\n };\n });\n}\n\n/**\n * Vite warns about `rollupOptions.output.sourcemap`, so the Vite plugin decides on `build.sourcemap`\n * in a `config` hook. The hook belongs on the post plugin: framework plugins that set\n * `build.sourcemap` themselves run first, and the decision sees the merged setting. The output\n * directories are only known in `configResolved`, which then records the decision for each of them.\n */\nexport function createViteSourceMapHooks(\n sentryBuildPluginManager: SentryBuildPluginManager,\n sourceMapHandling: SourceMapHandling,\n): ViteSourceMapHooks {\n // `'*'` for the top-level setting, otherwise the name of an environment with its own.\n const decisions = new Map<string, { kind: SourceMapKind; decision: SourceMapDecision }>();\n\n return {\n config: (userConfig, env) => {\n if (env.command !== 'build') {\n return null;\n }\n\n // The same plugin instances can serve several builds in a row.\n decisions.clear();\n\n const kind = sourceMapKindFromRollupSetting(userConfig.build?.sourcemap);\n // Logged in `generateBundle`, which knows whether the output is written.\n const decision = sentryBuildPluginManager.sourceMaps.decide(kind, { log: false });\n decisions.set('*', { kind, decision });\n\n const result: ViteUserConfig = decision.enableHidden ? { build: { sourcemap: 'hidden' } } : {};\n\n for (const [name, environment] of Object.entries(userConfig.environments ?? {})) {\n const setting = environment?.build?.sourcemap;\n if (setting === undefined) {\n continue;\n }\n\n const environmentKind = sourceMapKindFromRollupSetting(setting);\n const environmentDecision = sentryBuildPluginManager.sourceMaps.decide(environmentKind, {\n log: false,\n environment: name,\n });\n decisions.set(name, { kind: environmentKind, decision: environmentDecision });\n\n if (environmentDecision.enableHidden) {\n result.environments = { ...result.environments, [name]: { build: { sourcemap: 'hidden' } } };\n }\n }\n\n return result;\n },\n\n configResolved: config => {\n const environments = config.environments ?? { client: { build: config.build } };\n\n for (const [name, environment] of Object.entries(environments)) {\n const { kind, decision } = decisions.get(name) ?? decisions.get('*') ?? { kind: 'unset', decision: NO_CHANGE };\n const environmentName = decisions.has(name) ? name : undefined;\n const { normalizedOptions } = sentryBuildPluginManager;\n const deleteOption = getDeleteSourcemapsAfterUpload(normalizedOptions, environmentName);\n const sdkEnabledSourceMaps = getSdkEnabledSourceMaps(normalizedOptions, environmentName);\n\n for (const output of getOutputs(config.root, environment.build)) {\n // The plugin never changes an output's own setting. Hidden maps are\n // removed when the user asks for it, visible ones only when the SDK\n // turned source maps on.\n if (output.ownSetting) {\n const outputKind = sourceMapKindFromRollupSetting(output.sourcemap);\n const removeAllSourceMaps = sdkEnabledSourceMaps && (outputKind === 'hidden' || outputKind === 'visible');\n sourceMapHandling.setDecision(output.destination, {\n match: output.match,\n kind: outputKind,\n decision: {\n enableHidden: false,\n deleteAfterUpload: deleteOption === true && (outputKind === 'hidden' || removeAllSourceMaps),\n removeAllSourceMaps,\n },\n });\n continue;\n }\n\n // A plugin that ran after ours may have changed the setting again.\n if (decision.deleteAfterUpload && output.sourcemap !== 'hidden') {\n sentryBuildPluginManager.logger.debug(\n `Source maps of the \"${name}\" environment are set to ${JSON.stringify(output.sourcemap)}. Not removing them after upload.`,\n );\n sourceMapHandling.setDecision(output.destination, { match: output.match, kind, decision: NO_CHANGE });\n } else {\n sourceMapHandling.setDecision(output.destination, { match: output.match, kind, decision });\n }\n }\n }\n },\n };\n}\n"],"mappings":";;;;;AAgCA,MAAM,YAA+B;CAAE,cAAc;CAAO,mBAAmB;AAAM;;;;;;;AAgBrF,SAAS,WAAW,MAAc,OAA8C;CAC9E,MAAM,aAAa,MAAM,iBAAiB,UAAU,MAAM,eAAe;CAGzE,QAFgB,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,cAAc,CAAC,CAAC,EAAA,CAE3D,KAAI,WAAU;EAC3B,MAAM,YAAY,OAAO,aAAa,MAAM;EAC5C,OAAO;GACL,aAAa,OAAO,QAAQ,KAAA,IAAY,KAAK,QAAQ,MAAM,MAAM,UAAU,MAAM,IAAI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,GAAG,KAAK;KAAE,MAAM;KAAS,UAAU;IAAU;IAC7G,MAAM,kBAAkB,UAAU,IAAI,IAAI,IAAI,OAAO,KAAA;IACrD,MAAM,EAAE,sBAAsB;IAC9B,MAAM,eAAe,+BAA+B,mBAAmB,eAAe;IACtF,MAAM,uBAAuB,wBAAwB,mBAAmB,eAAe;IAEvF,KAAK,MAAM,UAAU,WAAW,OAAO,MAAM,YAAY,KAAK,GAAG;KAI/D,IAAI,OAAO,YAAY;MACrB,MAAM,aAAa,+BAA+B,OAAO,SAAS;MAClE,MAAM,sBAAsB,yBAAyB,eAAe,YAAY,eAAe;MAC/F,kBAAkB,YAAY,OAAO,aAAa;OAChD,OAAO,OAAO;OACd,MAAM;OACN,UAAU;QACR,cAAc;QACd,mBAAmB,iBAAiB,SAAS,eAAe,YAAY;QACxE;OACF;MACF,CAAC;MACD;KACF;KAGA,IAAI,SAAS,qBAAqB,OAAO,cAAc,UAAU;MAC/D,yBAAyB,OAAO,MAC9B,uBAAuB,KAAK,2BAA2B,KAAK,UAAU,OAAO,SAAS,EAAE,kCAC1F;MACA,kBAAkB,YAAY,OAAO,aAAa;OAAE,OAAO,OAAO;OAAO;OAAM,UAAU;MAAU,CAAC;KACtG,OACE,kBAAkB,YAAY,OAAO,aAAa;MAAE,OAAO,OAAO;MAAO;MAAM;KAAS,CAAC;IAE7F;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"source-map-hooks.js","names":[],"sources":["../../../src/vite/source-map-hooks.ts"],"sourcesContent":["import * as path from 'node:path';\nimport type { SentryBuildPluginManager, SourceMapDecision, SourceMapKind } from '../core';\nimport { getDeleteOption, getSdkEnabledSourceMaps } from '../core';\nimport type { OutputMatch, RollupSourceMapSetting, SourceMapHandling } from '../rollup/source-map-handling';\nimport { getOutputMatch, sourceMapKindFromRollupSetting } from '../rollup/source-map-handling';\n\ntype BundlerOutput = OutputMatch & { dir?: string; sourcemap?: RollupSourceMapSetting };\ntype BundlerOutputOptions = BundlerOutput | BundlerOutput[] | undefined;\n\ntype ViteBuildOptions = {\n sourcemap?: RollupSourceMapSetting;\n outDir?: string;\n rollupOptions?: { output?: BundlerOutputOptions };\n rolldownOptions?: { output?: BundlerOutputOptions };\n};\n\nexport type ViteUserConfig = {\n build?: ViteBuildOptions;\n environments?: Record<string, { build?: ViteBuildOptions } | undefined>;\n};\n\nexport type ViteResolvedConfig = {\n root: string;\n build: ViteBuildOptions;\n environments?: Record<string, { build: ViteBuildOptions }>;\n};\n\nexport type ViteSourceMapHooks = {\n config: (userConfig: ViteUserConfig, env: { command: string }) => ViteUserConfig | null;\n configResolved: (config: ViteResolvedConfig) => void;\n outputOptions: SourceMapHandling['applyHiddenDecision'];\n};\n\nconst NO_CHANGE: SourceMapDecision = { enableHidden: false, deleteAfterUpload: false };\n\ntype EnvironmentOutput = {\n destination: string;\n match: OutputMatch;\n sourcemap: RollupSourceMapSetting;\n /** The output sets `sourcemap` itself, which overrides `build.sourcemap`. */\n ownSetting: boolean;\n};\n\n/**\n * The outputs an environment writes: one per entry of `rollupOptions.output` or\n * `rolldownOptions.output`. An output writes to `build.outDir` (relative to the root) unless it\n * sets its own `dir`, which the bundler resolves from the working directory. An output's own\n * `sourcemap` overrides `build.sourcemap`.\n */\nfunction getOutputs(root: string, build: ViteBuildOptions): EnvironmentOutput[] {\n const configured = build.rolldownOptions?.output ?? build.rollupOptions?.output;\n const outputs = Array.isArray(configured) ? configured : [configured ?? {}];\n\n return outputs.map(output => {\n const sourcemap = output.sourcemap ?? build.sourcemap;\n return {\n destination: output.dir === undefined ? path.resolve(root, build.outDir ?? 'dist') : path.resolve(output.dir),\n match: getOutputMatch({ ...output, sourcemap }),\n sourcemap,\n ownSetting: output.sourcemap !== undefined,\n };\n });\n}\n\n/**\n * Vite warns about `rollupOptions.output.sourcemap`, so the Vite plugin decides on `build.sourcemap`\n * in a `config` hook. The hook belongs on the post plugin: framework plugins that set\n * `build.sourcemap` themselves run first, and the decision sees the merged setting. The output\n * directories are only known in `configResolved`, which then records the decision for each of them.\n */\nexport function createViteSourceMapHooks(\n sentryBuildPluginManager: SentryBuildPluginManager,\n sourceMapHandling: SourceMapHandling,\n): ViteSourceMapHooks {\n // `'*'` for the top-level setting, otherwise the name of an environment with its own.\n const decisions = new Map<string, { kind: SourceMapKind; decision: SourceMapDecision }>();\n\n return {\n config: (userConfig, env) => {\n if (env.command !== 'build') {\n return null;\n }\n\n // The same plugin instances can serve several builds in a row.\n decisions.clear();\n\n const kind = sourceMapKindFromRollupSetting(userConfig.build?.sourcemap);\n // Logged in `generateBundle`, which knows whether the output is written.\n const decision = sentryBuildPluginManager.sourceMaps.decide(kind, { log: false });\n decisions.set('*', { kind, decision });\n\n const result: ViteUserConfig = decision.enableHidden ? { build: { sourcemap: 'hidden' } } : {};\n\n for (const [name, environment] of Object.entries(userConfig.environments ?? {})) {\n const setting = environment?.build?.sourcemap;\n if (setting === undefined) {\n continue;\n }\n\n const environmentKind = sourceMapKindFromRollupSetting(setting);\n const environmentDecision = sentryBuildPluginManager.sourceMaps.decide(environmentKind, {\n log: false,\n environment: name,\n });\n decisions.set(name, { kind: environmentKind, decision: environmentDecision });\n\n if (environmentDecision.enableHidden) {\n result.environments = { ...result.environments, [name]: { build: { sourcemap: 'hidden' } } };\n }\n }\n\n return result;\n },\n\n configResolved: config => {\n const environments = config.environments ?? { client: { build: config.build } };\n\n for (const [name, environment] of Object.entries(environments)) {\n const { kind, decision } = decisions.get(name) ?? decisions.get('*') ?? { kind: 'unset', decision: NO_CHANGE };\n const environmentName = decisions.has(name) ? name : undefined;\n const { normalizedOptions } = sentryBuildPluginManager;\n const deleteOption = getDeleteOption(normalizedOptions, environmentName);\n // `sourcemaps.delete: true` removes every source map, like for maps the SDK turned on.\n const removeAll =\n normalizedOptions.sourcemaps?.delete === true || getSdkEnabledSourceMaps(normalizedOptions, environmentName);\n\n for (const output of getOutputs(config.root, environment.build)) {\n // Hidden maps of an output's own setting are removed when the user\n // asks for it, visible ones only when every source map is removed.\n // Removed visible maps switch to hidden in `outputOptions`, so no\n // `sourceMappingURL` comment points at a removed file.\n if (output.ownSetting) {\n const outputKind = sourceMapKindFromRollupSetting(output.sourcemap);\n const removeAllSourceMaps = removeAll && (outputKind === 'hidden' || outputKind === 'visible');\n const deleteAfterUpload = deleteOption === true && (outputKind === 'hidden' || removeAllSourceMaps);\n sourceMapHandling.setDecision(output.destination, {\n match: output.match,\n kind: outputKind,\n decision: {\n enableHidden: outputKind === 'visible' && deleteAfterUpload,\n deleteAfterUpload,\n removeAllSourceMaps,\n },\n });\n continue;\n }\n\n // A plugin that ran after ours may have changed the setting again.\n if (decision.deleteAfterUpload && output.sourcemap !== 'hidden') {\n sentryBuildPluginManager.logger.debug(\n `Source maps of the \"${name}\" environment are set to ${JSON.stringify(output.sourcemap)}. Not removing them after upload.`,\n );\n sourceMapHandling.setDecision(output.destination, { match: output.match, kind, decision: NO_CHANGE });\n } else {\n sourceMapHandling.setDecision(output.destination, { match: output.match, kind, decision });\n }\n }\n }\n },\n\n outputOptions: sourceMapHandling.applyHiddenDecision,\n };\n}\n"],"mappings":";;;;;AAiCA,MAAM,YAA+B;CAAE,cAAc;CAAO,mBAAmB;AAAM;;;;;;;AAgBrF,SAAS,WAAW,MAAc,OAA8C;CAC9E,MAAM,aAAa,MAAM,iBAAiB,UAAU,MAAM,eAAe;CAGzE,QAFgB,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,cAAc,CAAC,CAAC,EAAA,CAE3D,KAAI,WAAU;EAC3B,MAAM,YAAY,OAAO,aAAa,MAAM;EAC5C,OAAO;GACL,aAAa,OAAO,QAAQ,KAAA,IAAY,KAAK,QAAQ,MAAM,MAAM,UAAU,MAAM,IAAI,KAAK,QAAQ,OAAO,GAAG;GAC5G,OAAO,eAAe;IAAE,GAAG;IAAQ;GAAU,CAAC;GAC9C;GACA,YAAY,OAAO,cAAc,KAAA;EACnC;CACF,CAAC;AACH;;;;;;;AAQA,SAAgB,yBACd,0BACA,mBACoB;CAEpB,M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YACJ,kBAAkB,YAAY,WAAW,QAAQ,wBAAwB,mBAAmB,eAAe;IAE7G,KAAK,MAAM,UAAU,WAAW,OAAO,MAAM,YAAY,KAAK,GAAG;KAK/D,IAAI,OAAO,YAAY;MACrB,MAAM,aAAa,+BAA+B,OAAO,SAAS;MAClE,MAAM,sBAAsB,cAAc,eAAe,YAAY,eAAe;MACpF,MAAM,oBAAoB,iBAAiB,SAAS,eAAe,YAAY;MAC/E,kBAAkB,YAAY,OAAO,aAAa;OAChD,OAAO,OAAO;OACd,MAAM;OACN,UAAU;QACR,cAAc,eAAe,aAAa;QAC1C;QACA;OACF;MACF,CAAC;MACD;KACF;KAGA,IAAI,SAAS,qBAAqB,OAAO,cAAc,UAAU;MAC/D,yBAAyB,OAAO,MAC9B,uBAAuB,KAAK,2BAA2B,KAAK,UAAU,OAAO,SAAS,EAAE,kCAC1F;MACA,kBAAkB,YAAY,OAAO,aAAa;OAAE,OAAO,OAAO;OAAO;OAAM,UAAU;MAAU,CAAC;KACtG,OACE,kBAAkB,YAAY,OAAO,aAAa;MAAE,OAAO,OAAO;MAAO;MAAM;KAAS,CAAC;IAE7F;GACF;EACF;EAEA,eAAe,kBAAkB;CACnC;AACF"}
@@ -3,6 +3,7 @@ import { CodeInjection, generateModuleMetadataInjectorCode, generateReleaseInjec
3
3
  import { getCodeInjectionPosition } from "../core/get-code-injection-position.js";
4
4
  import { createComponentNameAnnotateHooks } from "../core/component-annotate-hooks.js";
5
5
  import { createDebugIdUploadFunction, stampDebugId } from "../core/debug-id-upload.js";
6
+ import { getSourceMapFeatures } from "../core/sourcemap-settings.js";
6
7
  import { createSentryBuildPluginManager } from "../core/build-plugin-manager.js";
7
8
  import { getDebugIdSnippet, isJsFile } from "../core/index.js";
8
9
  import { createRequire } from "node:module";
@@ -19,6 +20,12 @@ try {
19
20
  COMPONENT_ANNOTATION_LOADER = path.resolve(dirname, "component-annotation-transform.js");
20
21
  }
21
22
  const WEBPACK_JAVASCRIPT_ASSET_REGEX = /\.(?:js|ts|jsx|tsx|mjs|cjs|mts|cts)(?:\?[^?]*)?(?:#[^#]*)?$/;
23
+ function findHtmlWebpackPlugin(compiler) {
24
+ for (const plugin of compiler.options.plugins ?? []) {
25
+ const pluginClass = plugin?.constructor;
26
+ if (pluginClass?.name === "HtmlWebpackPlugin" && typeof pluginClass.getHooks === "function") return pluginClass;
27
+ }
28
+ }
22
29
  /**
23
30
  * Maps webpack's `devtool` onto the plugin's source map kinds. A user who sets `devtool: false`
24
31
  * and adds a `SourceMapDevToolPlugin` manages source maps themselves.
@@ -114,7 +121,7 @@ function createSentryWebpackPlugin(userOptions = {}) {
114
121
  const { logger, normalizedOptions: options, bundleSizeOptimizationReplacementValues: replacementValues, bundleMetadata, createDependencyOnBuildArtifacts } = sentryBuildPluginManager;
115
122
  if (options.disable) return { apply() {} };
116
123
  if (process.cwd().match(/\\node_modules\\|\/node_modules\//)) logger.warn("Running Sentry plugin from within a `node_modules` folder. Some features may not work.");
117
- const sourcemapsEnabled = options.sourcemaps?.disable !== true;
124
+ const { injectDebugIds, upload: uploadEnabled, stampEmittedFiles } = getSourceMapFeatures(options);
118
125
  const releaseInjectionCode = new CodeInjection();
119
126
  const chunkInjectionCode = new CodeInjection();
120
127
  if (!options.release.inject) logger.debug("Release injection disabled via `release.inject` option. Will not inject release.");
@@ -139,8 +146,33 @@ function createSentryWebpackPlugin(userOptions = {}) {
139
146
  decision
140
147
  };
141
148
  }
142
- function addCodeInjection(compiler) {
143
- if (releaseInjectionCode.isEmpty() && chunkInjectionCode.isEmpty() && !sourcemapsEnabled) return;
149
+ /**
150
+ * Adds the release snippet to the `<head>` of every page that `html-webpack-plugin` generates.
151
+ * Returns `false` when the build has no `html-webpack-plugin`.
152
+ */
153
+ function addReleaseToHtml(compiler) {
154
+ const HtmlWebpackPlugin = findHtmlWebpackPlugin(compiler);
155
+ if (!HtmlWebpackPlugin) {
156
+ logger.warn("`release.inject: 'html'` needs `html-webpack-plugin` to generate the HTML, and this build does not use it. Injecting the release into the startup chunks instead.");
157
+ return false;
158
+ }
159
+ const tag = {
160
+ tagName: "script",
161
+ voidTag: false,
162
+ attributes: {},
163
+ meta: { plugin: "sentry-webpack-plugin" },
164
+ innerHTML: releaseInjectionCode.code()
165
+ };
166
+ compiler.hooks.thisCompilation.tap("sentry-webpack-plugin", (compilation) => {
167
+ HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap("sentry-webpack-plugin", (data) => {
168
+ data.headTags.unshift(tag);
169
+ return data;
170
+ });
171
+ });
172
+ return true;
173
+ }
174
+ function addCodeInjection(compiler, injectRelease) {
175
+ if ((!injectRelease || releaseInjectionCode.isEmpty()) && chunkInjectionCode.isEmpty() && !injectDebugIds) return;
144
176
  const ReplaceSource = compiler.webpack?.sources?.ReplaceSource;
145
177
  const processAssetsStage = compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_ADDITIONS;
146
178
  if (!ReplaceSource || processAssetsStage === void 0) {
@@ -161,9 +193,9 @@ function createSentryWebpackPlugin(userOptions = {}) {
161
193
  const sourceContents = source.source();
162
194
  const code = typeof sourceContents === "string" ? sourceContents : Buffer.from(sourceContents).toString();
163
195
  const codeToInject = new CodeInjection();
164
- if (chunk.canBeInitial?.() ?? true) codeToInject.append(releaseInjectionCode);
196
+ if (injectRelease && (chunk.canBeInitial?.() ?? true)) codeToInject.append(releaseInjectionCode);
165
197
  codeToInject.append(chunkInjectionCode);
166
- if (sourcemapsEnabled) {
198
+ if (injectDebugIds) {
167
199
  const hash = chunk.contentHash?.javascript ?? chunk.hash;
168
200
  codeToInject.append(getDebugIdSnippet(hash ? stringToUUID(hash) : randomUUID()));
169
201
  }
@@ -215,8 +247,8 @@ function createSentryWebpackPlugin(userOptions = {}) {
215
247
  compiler.hooks.done.tap("sentry-webpack-plugin", settlePendingStagings);
216
248
  compiler.hooks.failed?.tap("sentry-webpack-plugin", settlePendingStagings);
217
249
  }
218
- addCodeInjection(compiler);
219
- if (sourcemapsEnabled && options.sourcemaps?.disable === "disable-upload") {
250
+ addCodeInjection(compiler, !(options.release.inject === "html" && !releaseInjectionCode.isEmpty() && addReleaseToHtml(compiler)));
251
+ if (stampEmittedFiles) {
220
252
  const RawSource = compiler.webpack?.sources?.RawSource;
221
253
  const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING ?? 500) + 1;
222
254
  if (!RawSource) logger.warn("Webpack sources are not available. Skipping debug ID injection into emitted source maps. This usually means webpack is not properly configured.");
@@ -255,7 +287,7 @@ function createSentryWebpackPlugin(userOptions = {}) {
255
287
  const run = async () => {
256
288
  try {
257
289
  await sentryBuildPluginManager.createRelease();
258
- if (sourcemapsEnabled && options.sourcemaps?.disable !== "disable-upload") {
290
+ if (uploadEnabled) {
259
291
  const outputPath = compilation.outputOptions.path ?? path.resolve();
260
292
  const buildArtifacts = Object.keys(compilation.assets).map((asset) => path.join(outputPath, asset));
261
293
  stagingHandedOver = true;