@sentry/bundler-plugins 11.0.0-beta.2 → 11.0.0-rc.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 (39) hide show
  1. package/build/cjs/core/debug-id-upload.js +77 -2
  2. package/build/cjs/core/debug-id-upload.js.map +1 -1
  3. package/build/cjs/core/index.js +2 -0
  4. package/build/cjs/core/index.js.map +1 -1
  5. package/build/cjs/core/version.js +1 -1
  6. package/build/cjs/core/version.js.map +1 -1
  7. package/build/cjs/esbuild/index.js +17 -2
  8. package/build/cjs/esbuild/index.js.map +1 -1
  9. package/build/cjs/rollup/index.js +23 -13
  10. package/build/cjs/rollup/index.js.map +1 -1
  11. package/build/cjs/webpack/webpack4and5.js +34 -0
  12. package/build/cjs/webpack/webpack4and5.js.map +1 -1
  13. package/build/esm/core/debug-id-upload.js +76 -3
  14. package/build/esm/core/debug-id-upload.js.map +1 -1
  15. package/build/esm/core/index.js +1 -1
  16. package/build/esm/core/index.js.map +1 -1
  17. package/build/esm/core/version.js +1 -1
  18. package/build/esm/core/version.js.map +1 -1
  19. package/build/esm/esbuild/index.js +19 -4
  20. package/build/esm/esbuild/index.js.map +1 -1
  21. package/build/esm/package.json +1 -1
  22. package/build/esm/rollup/index.js +24 -14
  23. package/build/esm/rollup/index.js.map +1 -1
  24. package/build/esm/webpack/webpack4and5.js +36 -2
  25. package/build/esm/webpack/webpack4and5.js.map +1 -1
  26. package/build/types/core/debug-id-upload.d.ts +28 -0
  27. package/build/types/core/debug-id-upload.d.ts.map +1 -1
  28. package/build/types/core/index.d.ts +1 -1
  29. package/build/types/core/index.d.ts.map +1 -1
  30. package/build/types/core/types.d.ts +7 -2
  31. package/build/types/core/types.d.ts.map +1 -1
  32. package/build/types/core/version.d.ts +1 -1
  33. package/build/types/core/version.d.ts.map +1 -1
  34. package/build/types/esbuild/index.d.ts.map +1 -1
  35. package/build/types/rollup/index.d.ts +16 -25
  36. package/build/types/rollup/index.d.ts.map +1 -1
  37. package/build/types/webpack/webpack4and5.d.ts +20 -21
  38. package/build/types/webpack/webpack4and5.d.ts.map +1 -1
  39. package/package.json +2 -2
@@ -95,6 +95,80 @@ function addDebugIdToBundleSource(bundleSource, debugId) {
95
95
  //# debugId=${debugId}`;
96
96
  }
97
97
  }
98
+ function setDebugIdOnSourceMap(map, debugId) {
99
+ map["debug_id"] = debugId;
100
+ map["debugId"] = debugId;
101
+ }
102
+ function parseSourceMap(sourceMapSource) {
103
+ let map;
104
+ try {
105
+ map = JSON.parse(sourceMapSource);
106
+ } catch {
107
+ return void 0;
108
+ }
109
+ return map && typeof map === "object" ? map : void 0;
110
+ }
111
+ function stampDebugId(bundleSource, sourceMapSource) {
112
+ const debugId = determineDebugIdFromBundleSource(bundleSource);
113
+ if (debugId === void 0) {
114
+ return void 0;
115
+ }
116
+ if (sourceMapSource === void 0) {
117
+ if (!bundleHasInlineSourceMap(bundleSource)) {
118
+ return void 0;
119
+ }
120
+ return { bundleSource: addDebugIdToBundleSource(bundleSource, debugId), sourceMapSource: void 0 };
121
+ }
122
+ const map = parseSourceMap(sourceMapSource);
123
+ if (!map) {
124
+ return void 0;
125
+ }
126
+ setDebugIdOnSourceMap(map, debugId);
127
+ return {
128
+ bundleSource: addDebugIdToBundleSource(bundleSource, debugId),
129
+ sourceMapSource: JSON.stringify(map)
130
+ };
131
+ }
132
+ async function addDebugIdToEmittedArtifacts(bundleFilePath, logger, resolveSourceMapHook) {
133
+ let bundleSource;
134
+ try {
135
+ bundleSource = await fs__default.promises.readFile(bundleFilePath, "utf8");
136
+ } catch (e) {
137
+ logger.error(`Could not read bundle to stamp debug ID: ${bundleFilePath}`, e);
138
+ return;
139
+ }
140
+ const sourceMapPath = await determineSourceMapPathFromBundle(
141
+ bundleFilePath,
142
+ bundleSource,
143
+ logger,
144
+ resolveSourceMapHook
145
+ );
146
+ let sourceMapSource;
147
+ if (sourceMapPath) {
148
+ try {
149
+ sourceMapSource = await fs__default.promises.readFile(sourceMapPath, "utf8");
150
+ } catch (e) {
151
+ logger.error(`Could not read source map to stamp debug ID: ${sourceMapPath}`, e);
152
+ return;
153
+ }
154
+ }
155
+ const stamped = stampDebugId(bundleSource, sourceMapSource);
156
+ if (!stamped) {
157
+ logger.debug(
158
+ `Could not stamp debug ID (no debug ID in bundle, no source map, or invalid source map): ${bundleFilePath}`
159
+ );
160
+ return;
161
+ }
162
+ const writes = [fs__default.promises.writeFile(bundleFilePath, stamped.bundleSource, "utf8")];
163
+ if (sourceMapPath && stamped.sourceMapSource !== void 0) {
164
+ writes.push(fs__default.promises.writeFile(sourceMapPath, stamped.sourceMapSource, "utf8"));
165
+ }
166
+ try {
167
+ await Promise.all(writes);
168
+ } catch (e) {
169
+ logger.error(`Could not write debug ID into build artifacts: ${bundleFilePath}`, e);
170
+ }
171
+ }
98
172
  function bundleHasInlineSourceMap(bundleSource) {
99
173
  return /^\s*\/\/# sourceMappingURL=data:/m.test(bundleSource);
100
174
  }
@@ -153,8 +227,7 @@ async function prepareSourceMapForDebugIdUpload(sourceMapPath, targetPath, debug
153
227
  let map;
154
228
  try {
155
229
  map = JSON.parse(sourceMapFileContent);
156
- map["debug_id"] = debugId;
157
- map["debugId"] = debugId;
230
+ setDebugIdOnSourceMap(map, debugId);
158
231
  } catch {
159
232
  logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);
160
233
  return;
@@ -181,8 +254,10 @@ function defaultRewriteSourcesHook(source) {
181
254
  }
182
255
  }
183
256
 
257
+ exports.addDebugIdToEmittedArtifacts = addDebugIdToEmittedArtifacts;
184
258
  exports.createDebugIdUploadFunction = createDebugIdUploadFunction;
185
259
  exports.defaultRewriteSourcesHook = defaultRewriteSourcesHook;
186
260
  exports.determineSourceMapPathFromBundle = determineSourceMapPathFromBundle;
187
261
  exports.prepareBundleForDebugIdUpload = prepareBundleForDebugIdUpload;
262
+ exports.stampDebugId = stampDebugId;
188
263
  //# sourceMappingURL=debug-id-upload.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"debug-id-upload.js","sources":["../../../src/core/debug-id-upload.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport * as url from 'url';\nimport * as util from 'util';\nimport { promisify } from 'util';\nimport type { SentryBuildPluginManager } from './build-plugin-manager';\nimport type { Logger } from './logger';\nimport type { ResolveSourceMapHook, RewriteSourcesHook } from './types';\nimport { stripQueryAndHashFromPath } from './utils';\n\ninterface DebugIdUploadPluginOptions {\n sentryBuildPluginManager: SentryBuildPluginManager;\n}\n\nexport function createDebugIdUploadFunction({ sentryBuildPluginManager }: DebugIdUploadPluginOptions) {\n return async (buildArtifactPaths: string[]) => {\n // Webpack and perhaps other bundlers allow you to append query strings to\n // filenames for cache busting purposes. We should strip these before upload.\n const cleanedPaths = buildArtifactPaths.map(stripQueryAndHashFromPath);\n await sentryBuildPluginManager.uploadSourcemaps(cleanedPaths);\n };\n}\n\nexport async function prepareBundleForDebugIdUpload(\n bundleFilePath: string,\n uploadFolder: string,\n chunkIndex: number,\n logger: Logger,\n rewriteSourcesHook: RewriteSourcesHook,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleContent;\n try {\n bundleContent = await promisify(fs.readFile)(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to determine debug ID and source map: ${bundleFilePath}`, e);\n return;\n }\n\n const debugId = determineDebugIdFromBundleSource(bundleContent);\n if (debugId === undefined) {\n logger.debug(\n `Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ${bundleFilePath}`,\n );\n return;\n }\n\n const uniqueUploadName = `${debugId}-${chunkIndex}`;\n\n bundleContent = addDebugIdToBundleSource(bundleContent, debugId);\n\n const sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\n logger,\n resolveSourceMapHook,\n );\n\n // A chunk with a debug ID but no resolvable source map\n // (e.g. framework-generated stub chunks that never emit one) can't be\n // symbolicated, so uploading its minified source alone accomplishes\n // nothing and only makes the uploader warn about a missing source map ref.\n // Skip it, unless the source map is inlined into the bundle, in which case\n // the source file carries the map itself and must still be uploaded.\n if (!sourceMapPath && !bundleHasInlineSourceMap(bundleContent)) {\n logger.debug(`Not uploading bundle without a source map: ${bundleFilePath}`);\n return;\n }\n\n const writeSourceFilePromise = fs.promises.writeFile(\n path.join(uploadFolder, `${uniqueUploadName}.js`),\n bundleContent,\n 'utf-8',\n );\n\n const writeSourceMapFilePromise = sourceMapPath\n ? prepareSourceMapForDebugIdUpload(\n sourceMapPath,\n path.join(uploadFolder, `${uniqueUploadName}.js.map`),\n debugId,\n rewriteSourcesHook,\n logger,\n )\n : Promise.resolve();\n\n await writeSourceFilePromise;\n await writeSourceMapFilePromise;\n}\n\n/**\n * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle\n * source and extracts the bundle's debug ID from it.\n *\n * The string pattern is injected via the debug ID injection snipped.\n */\nfunction determineDebugIdFromBundleSource(code: string): string | undefined {\n const match = code.match(\n /sentry-dbid-([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})/,\n );\n\n if (match) {\n return match[1];\n } else {\n return undefined;\n }\n}\n\nconst SPEC_LAST_DEBUG_ID_REGEX = /\\/\\/# debugId=([a-fA-F0-9-]+)(?![\\s\\S]*\\/\\/# debugId=)/m;\n\nfunction hasSpecCompliantDebugId(bundleSource: string): boolean {\n return SPEC_LAST_DEBUG_ID_REGEX.test(bundleSource);\n}\n\nfunction addDebugIdToBundleSource(bundleSource: string, debugId: string): string {\n if (hasSpecCompliantDebugId(bundleSource)) {\n return bundleSource.replace(SPEC_LAST_DEBUG_ID_REGEX, `//# debugId=${debugId}`);\n } else {\n return `${bundleSource}\\n//# debugId=${debugId}`;\n }\n}\n\n/**\n * Whether the bundle carries its source map inlined as `sourceMappingURL=data:`\n * URI, rather than referencing a separate `.map` file. Such bundles must still\n * be uploaded even when no `.map` file is found, because the source file itself\n * contains the map.\n */\nfunction bundleHasInlineSourceMap(bundleSource: string): boolean {\n return /^\\s*\\/\\/# sourceMappingURL=data:/m.test(bundleSource);\n}\n\n/**\n * Applies a set of heuristics to find the source map for a particular bundle.\n *\n * @returns the path to the bundle's source map or `undefined` if none could be found.\n */\nexport async function determineSourceMapPathFromBundle(\n bundlePath: string,\n bundleSource: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<string | undefined> {\n const sourceMappingUrlMatch = bundleSource.match(/^\\s*\\/\\/# sourceMappingURL=(.*)$/m);\n const sourceMappingUrl = sourceMappingUrlMatch ? (sourceMappingUrlMatch[1] as string) : undefined;\n\n const searchLocations: string[] = [];\n\n if (resolveSourceMapHook) {\n logger.debug(\n `Calling sourcemaps.resolveSourceMap(${JSON.stringify(bundlePath)}, ${JSON.stringify(sourceMappingUrl)})`,\n );\n const customPath = await resolveSourceMapHook(bundlePath, sourceMappingUrl);\n logger.debug(`resolveSourceMap hook returned: ${JSON.stringify(customPath)}`);\n\n if (customPath) {\n searchLocations.push(customPath);\n }\n }\n\n // 1. try to find source map at `sourceMappingURL` location\n if (sourceMappingUrl) {\n let parsedUrl: URL | undefined;\n try {\n parsedUrl = new URL(sourceMappingUrl);\n } catch {\n // noop\n }\n\n if (parsedUrl?.protocol === 'file:') {\n searchLocations.push(url.fileURLToPath(sourceMappingUrl));\n } else if (parsedUrl) {\n // noop, non-file urls don't translate to a local sourcemap file\n } else if (path.isAbsolute(sourceMappingUrl)) {\n searchLocations.push(path.normalize(sourceMappingUrl));\n } else {\n searchLocations.push(path.normalize(path.join(path.dirname(bundlePath), sourceMappingUrl)));\n }\n }\n\n // 2. try to find source map at path adjacent to chunk source, but with `.map` appended\n searchLocations.push(`${bundlePath}.map`);\n\n for (const searchLocation of searchLocations) {\n try {\n await util.promisify(fs.access)(searchLocation);\n logger.debug(`Source map found for bundle \\`${bundlePath}\\`: \\`${searchLocation}\\``);\n return searchLocation;\n } catch {\n // noop\n }\n }\n\n // This is just a debug message because it can be quite spammy for some frameworks\n logger.debug(\n `Could not determine source map path for bundle \\`${bundlePath}\\`` +\n ` with sourceMappingURL=${sourceMappingUrl === undefined ? 'undefined' : `\\`${sourceMappingUrl}\\``}` +\n ` - Did you turn on source map generation in your bundler?` +\n ` (Attempted paths: ${searchLocations.map(e => `\\`${e}\\``).join(', ')})`,\n );\n return undefined;\n}\n\n/**\n * Reads a source map, injects debug ID fields, and writes the source map to the target path.\n */\nasync function prepareSourceMapForDebugIdUpload(\n sourceMapPath: string,\n targetPath: string,\n debugId: string,\n rewriteSourcesHook: RewriteSourcesHook,\n logger: Logger,\n): Promise<void> {\n let sourceMapFileContent: string;\n try {\n sourceMapFileContent = await util.promisify(fs.readFile)(sourceMapPath, {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n\n let map: Record<string, unknown>;\n try {\n map = JSON.parse(sourceMapFileContent) as { sources: unknown; [key: string]: unknown };\n // For now we write both fields until we know what will become the standard - if ever.\n map['debug_id'] = debugId;\n map['debugId'] = debugId;\n } catch {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n return;\n }\n\n if (map['sources'] && Array.isArray(map['sources'])) {\n const mapDir = path.dirname(sourceMapPath);\n map['sources'] = map['sources'].map((source: string) => rewriteSourcesHook(source, map, { mapDir }));\n }\n\n try {\n await util.promisify(fs.writeFile)(targetPath, JSON.stringify(map), {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to prepare source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n}\n\nconst PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\\-.]*:\\/\\//;\nexport function defaultRewriteSourcesHook(source: string): string {\n if (source.match(PROTOCOL_REGEX)) {\n return source.replace(PROTOCOL_REGEX, '');\n } else {\n return path.relative(process.cwd(), path.normalize(source));\n }\n}\n"],"names":["stripQueryAnd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,CAAO,KAAA,CAAM,cAAc,CAAA,EAAG;AAChC,IAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,cAAA,EAAgB,EAAE,CAAA;AAAA,EAC1C,CAAA,MAAO;AACL,IAAA,OAAOC,aAAA,CAAK,SAAS,OAAA,CAAQ,GAAA,IAAOA,aAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA,EAC5D;AACF;;;;;;;"}
1
+ {"version":3,"file":"debug-id-upload.js","sources":["../../../src/core/debug-id-upload.ts"],"sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport * as url from 'url';\nimport * as util from 'util';\nimport { promisify } from 'util';\nimport type { SentryBuildPluginManager } from './build-plugin-manager';\nimport type { Logger } from './logger';\nimport type { ResolveSourceMapHook, RewriteSourcesHook } from './types';\nimport { stripQueryAndHashFromPath } from './utils';\n\ninterface DebugIdUploadPluginOptions {\n sentryBuildPluginManager: SentryBuildPluginManager;\n}\n\nexport function createDebugIdUploadFunction({ sentryBuildPluginManager }: DebugIdUploadPluginOptions) {\n return async (buildArtifactPaths: string[]) => {\n // Webpack and perhaps other bundlers allow you to append query strings to\n // filenames for cache busting purposes. We should strip these before upload.\n const cleanedPaths = buildArtifactPaths.map(stripQueryAndHashFromPath);\n await sentryBuildPluginManager.uploadSourcemaps(cleanedPaths);\n };\n}\n\nexport async function prepareBundleForDebugIdUpload(\n bundleFilePath: string,\n uploadFolder: string,\n chunkIndex: number,\n logger: Logger,\n rewriteSourcesHook: RewriteSourcesHook,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleContent;\n try {\n bundleContent = await promisify(fs.readFile)(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to determine debug ID and source map: ${bundleFilePath}`, e);\n return;\n }\n\n const debugId = determineDebugIdFromBundleSource(bundleContent);\n if (debugId === undefined) {\n logger.debug(\n `Could not determine debug ID from bundle. This can happen if you did not clean your output folder before installing the Sentry plugin. File will not be source mapped: ${bundleFilePath}`,\n );\n return;\n }\n\n const uniqueUploadName = `${debugId}-${chunkIndex}`;\n\n bundleContent = addDebugIdToBundleSource(bundleContent, debugId);\n\n const sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleContent,\n logger,\n resolveSourceMapHook,\n );\n\n // A chunk with a debug ID but no resolvable source map\n // (e.g. framework-generated stub chunks that never emit one) can't be\n // symbolicated, so uploading its minified source alone accomplishes\n // nothing and only makes the uploader warn about a missing source map ref.\n // Skip it, unless the source map is inlined into the bundle, in which case\n // the source file carries the map itself and must still be uploaded.\n if (!sourceMapPath && !bundleHasInlineSourceMap(bundleContent)) {\n logger.debug(`Not uploading bundle without a source map: ${bundleFilePath}`);\n return;\n }\n\n const writeSourceFilePromise = fs.promises.writeFile(\n path.join(uploadFolder, `${uniqueUploadName}.js`),\n bundleContent,\n 'utf-8',\n );\n\n const writeSourceMapFilePromise = sourceMapPath\n ? prepareSourceMapForDebugIdUpload(\n sourceMapPath,\n path.join(uploadFolder, `${uniqueUploadName}.js.map`),\n debugId,\n rewriteSourcesHook,\n logger,\n )\n : Promise.resolve();\n\n await writeSourceFilePromise;\n await writeSourceMapFilePromise;\n}\n\n/**\n * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle\n * source and extracts the bundle's debug ID from it.\n *\n * The string pattern is injected via the debug ID injection snipped.\n */\nfunction determineDebugIdFromBundleSource(code: string): string | undefined {\n const match = code.match(\n /sentry-dbid-([0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12})/,\n );\n\n if (match) {\n return match[1];\n } else {\n return undefined;\n }\n}\n\nconst SPEC_LAST_DEBUG_ID_REGEX = /\\/\\/# debugId=([a-fA-F0-9-]+)(?![\\s\\S]*\\/\\/# debugId=)/m;\n\nfunction hasSpecCompliantDebugId(bundleSource: string): boolean {\n return SPEC_LAST_DEBUG_ID_REGEX.test(bundleSource);\n}\n\nfunction addDebugIdToBundleSource(bundleSource: string, debugId: string): string {\n if (hasSpecCompliantDebugId(bundleSource)) {\n return bundleSource.replace(SPEC_LAST_DEBUG_ID_REGEX, `//# debugId=${debugId}`);\n } else {\n return `${bundleSource}\\n//# debugId=${debugId}`;\n }\n}\n\nfunction setDebugIdOnSourceMap(map: Record<string, unknown>, debugId: string): void {\n // For now we write both fields until we know what will become the standard - if ever.\n map['debug_id'] = debugId;\n map['debugId'] = debugId;\n}\n\nexport type StampedArtifacts = {\n bundleSource: string;\n /** `undefined` when the bundle has no separate source map (i.e. the map is inlined). */\n sourceMapSource: string | undefined;\n};\n\nfunction parseSourceMap(sourceMapSource: string): Record<string, unknown> | undefined {\n let map: unknown;\n try {\n map = JSON.parse(sourceMapSource);\n } catch {\n return undefined;\n }\n\n return map && typeof map === 'object' ? (map as Record<string, unknown>) : undefined;\n}\n\n/**\n * Stamps the debug ID injected into `bundleSource` into the bundle (as `//# debugId=` comment) and its\n * source map (as `debug_id`/`debugId` fields).\n *\n * This exists for `sourcemaps.disable: \"disable-upload\"`: the regular upload path only stamps\n * temporary copies of the artifacts (see `prepareBundleForDebugIdUpload`), so without this the\n * emitted artifacts would carry no debug ID and a later manual upload could not match them.\n * Callers must apply the result inside the bundler's asset pipeline (or, for bundlers without one,\n * before the build resolves) so that integrity hashes computed by later build steps include it.\n *\n * Pass `sourceMapSource: undefined` when the bundle has no separate source map. A bundle with an\n * inlined map still gets the comment, which is all the CLI and Symbolicator read the debug ID from.\n *\n * @returns the stamped artifacts, or `undefined` for bundles without a debug ID, without any source\n * map, or with an unparseable map.\n */\nexport function stampDebugId(bundleSource: string, sourceMapSource: string | undefined): StampedArtifacts | undefined {\n const debugId = determineDebugIdFromBundleSource(bundleSource);\n if (debugId === undefined) {\n return undefined;\n }\n\n if (sourceMapSource === undefined) {\n if (!bundleHasInlineSourceMap(bundleSource)) {\n return undefined;\n }\n\n return { bundleSource: addDebugIdToBundleSource(bundleSource, debugId), sourceMapSource: undefined };\n }\n\n const map = parseSourceMap(sourceMapSource);\n if (!map) {\n return undefined;\n }\n\n setDebugIdOnSourceMap(map, debugId);\n\n return {\n bundleSource: addDebugIdToBundleSource(bundleSource, debugId),\n sourceMapSource: JSON.stringify(map),\n };\n}\n\n/**\n * Stamps the debug ID of an emitted bundle into the bundle and its source map on disk.\n *\n * Used by bundlers that offer no hook to modify assets before they are written (esbuild).\n */\nexport async function addDebugIdToEmittedArtifacts(\n bundleFilePath: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<void> {\n let bundleSource: string;\n try {\n bundleSource = await fs.promises.readFile(bundleFilePath, 'utf8');\n } catch (e) {\n logger.error(`Could not read bundle to stamp debug ID: ${bundleFilePath}`, e);\n return;\n }\n\n const sourceMapPath = await determineSourceMapPathFromBundle(\n bundleFilePath,\n bundleSource,\n logger,\n resolveSourceMapHook,\n );\n\n let sourceMapSource: string | undefined;\n if (sourceMapPath) {\n try {\n sourceMapSource = await fs.promises.readFile(sourceMapPath, 'utf8');\n } catch (e) {\n logger.error(`Could not read source map to stamp debug ID: ${sourceMapPath}`, e);\n return;\n }\n }\n\n const stamped = stampDebugId(bundleSource, sourceMapSource);\n if (!stamped) {\n logger.debug(\n `Could not stamp debug ID (no debug ID in bundle, no source map, or invalid source map): ${bundleFilePath}`,\n );\n return;\n }\n\n const writes = [fs.promises.writeFile(bundleFilePath, stamped.bundleSource, 'utf8')];\n if (sourceMapPath && stamped.sourceMapSource !== undefined) {\n writes.push(fs.promises.writeFile(sourceMapPath, stamped.sourceMapSource, 'utf8'));\n }\n\n try {\n await Promise.all(writes);\n } catch (e) {\n logger.error(`Could not write debug ID into build artifacts: ${bundleFilePath}`, e);\n }\n}\n\n/**\n * Whether the bundle carries its source map inlined as `sourceMappingURL=data:`\n * URI, rather than referencing a separate `.map` file. Such bundles must still\n * be uploaded even when no `.map` file is found, because the source file itself\n * contains the map.\n */\nfunction bundleHasInlineSourceMap(bundleSource: string): boolean {\n return /^\\s*\\/\\/# sourceMappingURL=data:/m.test(bundleSource);\n}\n\n/**\n * Applies a set of heuristics to find the source map for a particular bundle.\n *\n * @returns the path to the bundle's source map or `undefined` if none could be found.\n */\nexport async function determineSourceMapPathFromBundle(\n bundlePath: string,\n bundleSource: string,\n logger: Logger,\n resolveSourceMapHook: ResolveSourceMapHook | undefined,\n): Promise<string | undefined> {\n const sourceMappingUrlMatch = bundleSource.match(/^\\s*\\/\\/# sourceMappingURL=(.*)$/m);\n const sourceMappingUrl = sourceMappingUrlMatch ? (sourceMappingUrlMatch[1] as string) : undefined;\n\n const searchLocations: string[] = [];\n\n if (resolveSourceMapHook) {\n logger.debug(\n `Calling sourcemaps.resolveSourceMap(${JSON.stringify(bundlePath)}, ${JSON.stringify(sourceMappingUrl)})`,\n );\n const customPath = await resolveSourceMapHook(bundlePath, sourceMappingUrl);\n logger.debug(`resolveSourceMap hook returned: ${JSON.stringify(customPath)}`);\n\n if (customPath) {\n searchLocations.push(customPath);\n }\n }\n\n // 1. try to find source map at `sourceMappingURL` location\n if (sourceMappingUrl) {\n let parsedUrl: URL | undefined;\n try {\n parsedUrl = new URL(sourceMappingUrl);\n } catch {\n // noop\n }\n\n if (parsedUrl?.protocol === 'file:') {\n searchLocations.push(url.fileURLToPath(sourceMappingUrl));\n } else if (parsedUrl) {\n // noop, non-file urls don't translate to a local sourcemap file\n } else if (path.isAbsolute(sourceMappingUrl)) {\n searchLocations.push(path.normalize(sourceMappingUrl));\n } else {\n searchLocations.push(path.normalize(path.join(path.dirname(bundlePath), sourceMappingUrl)));\n }\n }\n\n // 2. try to find source map at path adjacent to chunk source, but with `.map` appended\n searchLocations.push(`${bundlePath}.map`);\n\n for (const searchLocation of searchLocations) {\n try {\n await util.promisify(fs.access)(searchLocation);\n logger.debug(`Source map found for bundle \\`${bundlePath}\\`: \\`${searchLocation}\\``);\n return searchLocation;\n } catch {\n // noop\n }\n }\n\n // This is just a debug message because it can be quite spammy for some frameworks\n logger.debug(\n `Could not determine source map path for bundle \\`${bundlePath}\\`` +\n ` with sourceMappingURL=${sourceMappingUrl === undefined ? 'undefined' : `\\`${sourceMappingUrl}\\``}` +\n ` - Did you turn on source map generation in your bundler?` +\n ` (Attempted paths: ${searchLocations.map(e => `\\`${e}\\``).join(', ')})`,\n );\n return undefined;\n}\n\n/**\n * Reads a source map, injects debug ID fields, and writes the source map to the target path.\n */\nasync function prepareSourceMapForDebugIdUpload(\n sourceMapPath: string,\n targetPath: string,\n debugId: string,\n rewriteSourcesHook: RewriteSourcesHook,\n logger: Logger,\n): Promise<void> {\n let sourceMapFileContent: string;\n try {\n sourceMapFileContent = await util.promisify(fs.readFile)(sourceMapPath, {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to read source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n\n let map: Record<string, unknown>;\n try {\n map = JSON.parse(sourceMapFileContent) as { sources: unknown; [key: string]: unknown };\n setDebugIdOnSourceMap(map, debugId);\n } catch {\n logger.error(`Failed to parse source map for debug ID upload: ${sourceMapPath}`);\n return;\n }\n\n if (map['sources'] && Array.isArray(map['sources'])) {\n const mapDir = path.dirname(sourceMapPath);\n map['sources'] = map['sources'].map((source: string) => rewriteSourcesHook(source, map, { mapDir }));\n }\n\n try {\n await util.promisify(fs.writeFile)(targetPath, JSON.stringify(map), {\n encoding: 'utf8',\n });\n } catch (e) {\n logger.error(`Failed to prepare source map for debug ID upload: ${sourceMapPath}`, e);\n return;\n }\n}\n\nconst PROTOCOL_REGEX = /^[a-zA-Z][a-zA-Z0-9+\\-.]*:\\/\\//;\nexport function defaultRewriteSourcesHook(source: string): string {\n if (source.match(PROTOCOL_REGEX)) {\n return source.replace(PROTOCOL_REGEX, '');\n } else {\n return path.relative(process.cwd(), path.normalize(source));\n }\n}\n"],"names":["stripQueryAndHashFromPath","promisify","fs","path","url","util"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,SAAS,2BAAA,CAA4B,EAAE,wBAAA,EAAyB,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AAA,IAAI,MAAA,CAAO,KAAA,CAAM,cAAc,CAAA,EAAG;AAChC,IAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,cAAA,EAAgB,EAAE,CAAA;AAAA,EAC1C,CAAA,MAAO;AACL,IAAA,OAAOC,aAAA,CAAK,SAAS,OAAA,CAAQ,GAAA,IAAOA,aAAA,CAAK,SAAA,CAAU,MAAM,CAAC,CAAA;AAAA,EAC5D;AACF;;;;;;;;;"}
@@ -95,7 +95,9 @@ exports.replaceBooleanFlagsInCode = utils.replaceBooleanFlagsInCode;
95
95
  exports.stringToUUID = utils.stringToUUID;
96
96
  exports.globFiles = glob.globFiles;
97
97
  exports.createSentryBuildPluginManager = buildPluginManager.createSentryBuildPluginManager;
98
+ exports.addDebugIdToEmittedArtifacts = debugIdUpload.addDebugIdToEmittedArtifacts;
98
99
  exports.createDebugIdUploadFunction = debugIdUpload.createDebugIdUploadFunction;
100
+ exports.stampDebugId = debugIdUpload.stampDebugId;
99
101
  exports.COMMENT_USE_STRICT_REGEX = COMMENT_USE_STRICT_REGEX;
100
102
  exports.createComponentNameAnnotateHooks = createComponentNameAnnotateHooks;
101
103
  exports.getDebugIdSnippet = getDebugIdSnippet;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n// We need to be careful not to inject the snippet before any `\"use strict\";`s.\n// As an additional complication `\"use strict\";`s may come after any number of comments.\nexport const COMMENT_USE_STRICT_REGEX =\n // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.\n /^(?:\\s*|\\/\\*(?:.|\\r|\\n)*?\\*\\/|\\/\\/.*[\\n\\r])*(?:\"[^\"]*\";|'[^']*';)?/;\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction } from './debug-id-upload';\n"],"names":["stripQueryAndHashFromPath","containsOnlyImports","debug","CodeInjection"],"mappings":";;;;;;;;AAcA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GAAA,CAAI,CAAC,OAAO,aAAa,GAAG,qCAAO,0BAAiB,EAAC,CAAC,CAAA,CAAE,IAAA;AAAA,MAC9F,CAAC,CAAC,KAAA,EAAO,WAAW,CAAA,KAAM;AACxB,QAAA,OAAO;AAAA,UACL,gBAAgB,KAAA,CAAM,cAAA;AAAA,UACtB,6BAA6B,WAAA,CAAY,OAAA;AAAA,UACzC,yCAAyC,WAAA,CAAY;AAAA,SACvD;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,6BAAA;AACT;AAIO,MAAM,wBAAA;AAAA;AAAA,EAEX;AAAA;AAMK,SAAS,SAAS,QAAA,EAA2B;AAClD,EAAA,MAAM,aAAA,GAAgBA,gCAA0B,QAAQ,CAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA,CAAE,KAAK,CAAA,GAAA,KAAO,aAAA,CAAc,QAAA,CAAS,GAAG,CAAC,CAAA;AACxE;AAgBO,SAAS,uBAAA,CAAwB,MAAc,cAAA,EAAoD;AAExG,EAAA,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA,EAAG;AAC5B,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,kBAAkBA,+BAAA,CAA0B,cAAc,CAAA,CAAE,QAAA,CAAS,OAAO,CAAA,E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QAAA;AAAA,YACZ,yBAAA,EAA2B,IAAA;AAAA,YAC3B,OAAA,EAAS;AAAA,WACX;AAAA,UACA,aAAA,EAAe;AAAA,YACb,sBAAA,EAAwB;AAAA,WAC1B;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,QAAQ,IAAA,IAAQ,IAAA;AAAA,UACtB,KAAK,MAAA,EAAQ;AAAA,SACf;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAAE,UAAA,CAAM,KAAA,CAAM,yCAAyC,CAAC,CAAA;AAAA,MACxD;AAEA,MAAA,OAAO,EAAE,IAAA,EAAK;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAIC,mBAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/core/index.ts"],"sourcesContent":["import { debug } from '@sentry/core';\nimport { CodeInjection, containsOnlyImports, stripQueryAndHashFromPath } from './utils';\nimport type { transformAsync as babelTransformAsync } from '@babel/core';\nimport type componentNameAnnotatePlugin from '../babel-plugin';\nimport type { experimentalComponentNameAnnotatePlugin } from '../babel-plugin';\n\ntype BabelTransformAsync = typeof babelTransformAsync;\ntype BabelParserPlugins = NonNullable<NonNullable<Parameters<BabelTransformAsync>[1]>['parserOpts']>['plugins'];\ntype BabelAnnotationRuntime = {\n transformAsync: BabelTransformAsync;\n componentNameAnnotatePlugin: typeof componentNameAnnotatePlugin;\n experimentalComponentNameAnnotatePlugin: typeof experimentalComponentNameAnnotatePlugin;\n};\n\nlet babelAnnotationRuntimePromise: Promise<BabelAnnotationRuntime> | undefined;\n\nfunction loadBabelAnnotationRuntime(): Promise<BabelAnnotationRuntime> {\n if (!babelAnnotationRuntimePromise) {\n babelAnnotationRuntimePromise = Promise.all([import('@babel/core'), import('../babel-plugin')]).then(\n ([babel, babelPlugin]) => {\n return {\n transformAsync: babel.transformAsync,\n componentNameAnnotatePlugin: babelPlugin.default,\n experimentalComponentNameAnnotatePlugin: babelPlugin.experimentalComponentNameAnnotatePlugin,\n };\n },\n );\n }\n\n return babelAnnotationRuntimePromise;\n}\n\n// We need to be careful not to inject the snippet before any `\"use strict\";`s.\n// As an additional complication `\"use strict\";`s may come after any number of comments.\nexport const COMMENT_USE_STRICT_REGEX =\n // Note: CodeQL complains that this regex potentially has n^2 runtime. This likely won't affect realistic files.\n /^(?:\\s*|\\/\\*(?:.|\\r|\\n)*?\\*\\/|\\/\\/.*[\\n\\r])*(?:\"[^\"]*\";|'[^']*';)?/;\n\n/**\n * Checks if a file is a JavaScript file based on its extension.\n * Handles query strings and hashes in the filename.\n */\nexport function isJsFile(fileName: string): boolean {\n const cleanFileName = stripQueryAndHashFromPath(fileName);\n return ['.js', '.mjs', '.cjs'].some(ext => cleanFileName.endsWith(ext));\n}\n\n/**\n * Checks if a chunk should be skipped for code injection\n *\n * This is necessary to handle Vite's MPA (multi-page application) mode where\n * HTML entry points create \"facade\" chunks that should not contain injected code.\n * See: https://github.com/getsentry/sentry-javascript-bundler-plugins/issues/829\n *\n * However, in SPA mode, the main bundle also has an HTML facade but contains\n * substantial application code. We should NOT skip injection for these bundles.\n *\n * @param code - The chunk's code content\n * @param facadeModuleId - The facade module ID (if any) - HTML files create facade chunks\n * @returns true if the chunk should be skipped\n */\nexport function shouldSkipCodeInjection(code: string, facadeModuleId: string | null | undefined): boolean {\n // Skip empty chunks - these are placeholder chunks that should be optimized away\n if (code.trim().length === 0) {\n return true;\n }\n\n // For HTML facade chunks, only skip if they contain only import statements\n if (facadeModuleId && stripQueryAndHashFromPath(facadeModuleId).endsWith('.html')) {\n return containsOnlyImports(code);\n }\n\n return false;\n}\n\nexport { globFiles } from './glob';\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function createComponentNameAnnotateHooks(ignoredComponents: string[], injectIntoHtml: boolean) {\n return {\n async transform(this: void, code: string, id: string) {\n // id may contain query and hash which will trip up our file extension logic below\n const idWithoutQueryAndHash = stripQueryAndHashFromPath(id);\n\n if (idWithoutQueryAndHash.match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n return null;\n }\n\n // We will only apply this plugin on jsx and tsx files\n if (!['.jsx', '.tsx'].some(ending => idWithoutQueryAndHash.endsWith(ending))) {\n return null;\n }\n\n const parserPlugins: BabelParserPlugins = [];\n if (idWithoutQueryAndHash.endsWith('.jsx')) {\n parserPlugins.push('jsx');\n } else if (idWithoutQueryAndHash.endsWith('.tsx')) {\n parserPlugins.push('jsx', 'typescript');\n }\n\n const { transformAsync, componentNameAnnotatePlugin, experimentalComponentNameAnnotatePlugin } =\n await loadBabelAnnotationRuntime();\n const plugin = injectIntoHtml ? experimentalComponentNameAnnotatePlugin : componentNameAnnotatePlugin;\n\n try {\n const result = await transformAsync(code, {\n plugins: [[plugin, { ignoredComponents }]],\n filename: id,\n sourceFileName: idWithoutQueryAndHash,\n parserOpts: {\n sourceType: 'module',\n allowAwaitOutsideFunction: true,\n plugins: parserPlugins,\n },\n generatorOpts: {\n decoratorsBeforeExport: true,\n },\n sourceMaps: true,\n });\n\n return {\n code: result?.code ?? code,\n map: result?.map,\n };\n } catch (e) {\n debug.error(`Failed to apply react annotate plugin`, e);\n }\n\n return { code };\n },\n };\n}\n\nexport function getDebugIdSnippet(debugId: string): CodeInjection {\n return new CodeInjection(\n `var n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]=\"${debugId}\",e._sentryDebugIdIdentifier=\"sentry-dbid-${debugId}\");`,\n );\n}\n\nexport type { Logger } from './logger';\nexport type { Options, SentrySDKBuildFlags } from './types';\nexport {\n CodeInjection,\n replaceBooleanFlagsInCode,\n stringToUUID,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n} from './utils';\nexport { createSentryBuildPluginManager } from './build-plugin-manager';\nexport { createDebugIdUploadFunction, addDebugIdToEmittedArtifacts, stampDebugId } from './debug-id-upload';\n"],"names":["stripQueryAndHashFromPath","containsOnlyImports","debug","CodeInjection"],"mappings":";;;;;;;;AAcA,IAAI,6BAAA;AAEJ,SAAS,0BAAA,GAA8D;AACrE,EAAA,IAAI,CAAC,6BAAA,EAA+B;AAClC,IAAA,6BAAA,GAAgC,OAAA,CAAQ,GAAA,CAAI,CAAC,OAAO,aAAa,GAAG,qCAAO,0BAAiB,EAAC,CAAC,CAAA,CAAE,IAAA;AAAA,MAC9F,CAAC,CAAC,KAAA,EAAO,WAAW,CAAA,KAAM;AACxB,QAAA,OAAO;AAAA,UACL,gBAAgB,KAAA,CAAM,cAAA;AAAA,UACtB,6BAA6B,WAAA,CAAY,OAAA;AAAA,UACzC,yCAAyC,WAAA,CAAY;AAAA,SACvD;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,6BAAA;AACT;AAIO,MAAM,wBAAA;AAAA;AAAA,EAEX;AAAA;AAMK,SAAS,SAAS,QAAA,EAA2B;AAClD,EAAA,MAAM,aAAA,GAAgBA,gCAA0B,QAAQ,CAAA;AACxD,EAAA,OAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA,CAAE,KAAK,CAAA,GAAA,KAAO,aAAA,CAAc,QAAA,CAAS,GAAG,CAAC,CAAA;AACxE;AAgBO,SAAS,uBAAA,CAAwB,MAAc,cAAA,EAAoD;AAExG,EAAA,IAAI,IAAA,CAAK,IAAA,EAAK,CAAE,MAAA,KAAW,CAAA,EAAG;AAC5B,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,kBAAkBA,+BAAA,CAA0B,cAAc,CAAA,CAAE,QAAA,CAAS,OAAO,CAAA,EAAG;AACjF,IAAA,OAAOC,0BAAoB,IAAI,CAAA;AAAA,EACjC;AAEA,EAAA,OAAO,KAAA;AACT;AAKO,SAAS,gCAA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,YACb,sBAAA,EAAwB;AAAA,WAC1B;AAAA,UACA,UAAA,EAAY;AAAA,SACb,CAAA;AAED,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,QAAQ,IAAA,IAAQ,IAAA;AAAA,UACtB,KAAK,MAAA,EAAQ;AAAA,SACf;AAAA,MACF,SAAS,CAAA,EAAG;AACV,QAAAE,UAAA,CAAM,KAAA,CAAM,yCAAyC,CAAC,CAAA;AAAA,MACxD;AAEA,MAAA,OAAO,EAAE,IAAA,EAAK;AAAA,IAChB;AAAA,GACF;AACF;AAEO,SAAS,kBAAkB,OAAA,EAAgC;AAChE,EAAA,OAAO,IAAIC,mBAAA;AAAA,IACT,CAAA,4FAAA,EAA+F,OAAO,CAAA,0CAAA,EAA6C,OAAO,CAAA,GAAA;AAAA,GAC5J;AACF;;;;;;;;;;;;;;;;;;"}
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
- const LIB_VERSION = "11.0.0-beta.2";
3
+ const LIB_VERSION = "11.0.0-rc.0";
4
4
 
5
5
  exports.LIB_VERSION = LIB_VERSION;
6
6
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.0.0-beta.2\";\n"],"names":[],"mappings":";;AAAO,MAAM,WAAA,GAAc;;;;"}
1
+ {"version":3,"file":"version.js","sources":["../../../src/core/version.ts"],"sourcesContent":["export const LIB_VERSION = \"11.0.0-rc.0\";\n"],"names":[],"mappings":";;AAAO,MAAM,WAAA,GAAc;;;;"}
@@ -189,9 +189,24 @@ function sentryEsbuildPlugin(userOptions = {}) {
189
189
  onEnd(async (result) => {
190
190
  try {
191
191
  await sentryBuildPluginManager.createRelease();
192
- if (sourcemapsEnabled && options.sourcemaps?.disable !== "disable-upload") {
192
+ if (sourcemapsEnabled) {
193
193
  const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];
194
- await upload(buildArtifacts);
194
+ if (options.sourcemaps?.disable !== "disable-upload") {
195
+ await upload(buildArtifacts);
196
+ } else if (initialOptions.write === false) {
197
+ logger.debug("Build output is not written to disk. Skipping debug ID injection into build artifacts.");
198
+ } else {
199
+ const outputDir = initialOptions.absWorkingDir ?? process.cwd();
200
+ await Promise.all(
201
+ buildArtifacts.filter(index.isJsFile).map(
202
+ (bundle) => debugIdUpload.addDebugIdToEmittedArtifacts(
203
+ path__namespace.resolve(outputDir, bundle),
204
+ logger,
205
+ options.sourcemaps?.resolveSourceMap
206
+ )
207
+ )
208
+ );
209
+ }
195
210
  }
196
211
  } finally {
197
212
  freeGlobalDependencyOnBuildArtifacts();
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n await upload(buildArtifacts);\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\n"],"names":["createRequire","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","path","randomUUID","getDebugIdSnippet","createDebugIdUploadFunction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAS,sBAAA,GAA6C;AACpD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAMA,yBAAA,CAAc,kQAAe,CAAA;AACzC,IAAA,MAAM,OAAA,GAAU,IAAI,SAAS,CAAA;AAE7B,IAAA,OAAO,OAAA,CAAQ,OAAA,EAAS,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAAA,EACtC,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,MAAM,UAAA,GAAa,uBAAA;AAGZ,SAAS,mBAAA,CAAoB,WAAA,GAAuB,EAAC,EAAQ;AAClE,EAAA,MAAM,wBAAA,GAA2BC,kDAA+B,WAAA,EAAa;AAAA,IAC3E,YAAA,EAAc,WAAA,CAAY,YAAA,EAAc,oBAAA,IAAwB,IAAI,UAAU,CAAA,CAAA,CAAA;AAAA,IAC9E,SAAA,EAAW,SAAA;AAAA,IACX,uBAAuB,sBAAA;AAAuB,GAC/C,CAAA;AAED,EAA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CAAA;AAAA,MACH;AAGA,MAAA,MAAM,uCAAuC,gCAAA,EAAiC;AAC9E,MAAA,MAAM,MAAA,GAASE,yCAAA,CAA4B,EAAE,wBAAA,EAA0B,CAAA;AAEvE,MAAA,cAAA,CAAe,QAAA,GAAW,IAAA;AAC1B,MAAA,KAAA,CAAM,OAAM,MAAA,KAAU;AACpB,QAAA,IAAI;AACF,UAAA,MAAM,yBAAyB,aAAA,EAAc;AAE7C,UAAA,IAAI,iBAAA,IAAqB,OAAA,CAAQ,UAAA,EAAY,OAAA,KAAY,gBAAA,EAAkB;AACzE,YAAA,MAAM,cAAA,GAAiB,OAAO,QAAA,GAAW,MAAA,CAAO,KAAK,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA,GAAI,EAAC;AACjF,YAAA,MAAM,OAAO,cAAc,CAAA;AAAA,UAC7B;AAAA,QACF,CAAA,SAAE;AACA,UAAA,oCAAA,EAAqC;AACrC,UAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/esbuild/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n getDebugIdSnippet,\n createDebugIdUploadFunction,\n CodeInjection,\n addDebugIdToEmittedArtifacts,\n isJsFile,\n} from '../core';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { randomUUID } from 'node:crypto';\n\ninterface EsbuildOnResolveArgs {\n path: string;\n kind: string;\n importer?: string;\n resolveDir: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnResolveResult {\n path: string;\n sideEffects?: boolean;\n pluginName?: string;\n namespace?: string;\n suffix?: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadArgs {\n path: string;\n pluginData?: unknown;\n}\n\ninterface EsbuildOnLoadResult {\n loader: string;\n pluginName: string;\n contents: string;\n resolveDir?: string;\n}\n\ninterface EsbuildOnEndArgs {\n metafile?: {\n outputs: Record<string, unknown>;\n };\n}\n\ninterface EsbuildInitialOptions {\n bundle?: boolean;\n inject?: string[];\n metafile?: boolean;\n define?: Record<string, string>;\n write?: boolean;\n absWorkingDir?: string;\n}\n\ninterface EsbuildPluginBuild {\n initialOptions: EsbuildInitialOptions;\n onLoad: (\n options: { filter: RegExp; namespace?: string },\n callback: (args: EsbuildOnLoadArgs) => EsbuildOnLoadResult | null,\n ) => void;\n onResolve: (\n options: { filter: RegExp },\n callback: (args: EsbuildOnResolveArgs) => EsbuildOnResolveResult | undefined,\n ) => void;\n onEnd: (callback: (result: EsbuildOnEndArgs) => void | Promise<void>) => void;\n}\n\nfunction getEsbuildMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - esbuild transpiles this for us\n const req = createRequire(import.meta.url);\n const esbuild = req('esbuild') as { version?: string };\n // esbuild hasn't released a v1 yet, so we'll return the minor version as the major version\n return esbuild.version?.split('.')[1];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nconst pluginName = 'sentry-esbuild-plugin';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function sentryEsbuildPlugin(userOptions: Options = {}): any {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[${pluginName}]`,\n buildTool: 'esbuild',\n buildToolMajorVersion: getEsbuildMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-esbuild-noop-plugin',\n setup() {\n // noop plugin\n },\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n // Component annotation warning\n if (options.reactComponentAnnotation?.enabled) {\n logger.warn(\n 'Component name annotation is not supported in esbuild. Please use a separate transform step or consider using a different bundler.',\n );\n }\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n\n // Track entry points wrapped for debug ID injection\n const debugIdWrappedPaths = new Set<string>();\n\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n\n return {\n name: pluginName,\n setup({ initialOptions, onLoad, onResolve, onEnd }: EsbuildPluginBuild) {\n // Release and/or metadata injection\n if (!staticInjectionCode.isEmpty()) {\n const virtualInjectionFilePath = path.resolve('_sentry-injection-stub');\n initialOptions.inject = initialOptions.inject || [];\n initialOptions.inject.push(virtualInjectionFilePath);\n\n onResolve({ filter: /_sentry-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n };\n });\n\n onLoad({ filter: /_sentry-injection-stub/ }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: staticInjectionCode.code(),\n };\n });\n }\n\n // Bundle size optimizations\n if (transformReplace) {\n const replacementStringValues: Record<string, string> = {};\n Object.entries(replacementValues).forEach(([key, value]) => {\n replacementStringValues[key] = JSON.stringify(value);\n });\n\n initialOptions.define = { ...initialOptions.define, ...replacementStringValues };\n }\n\n // Debug ID injection - requires per-entry-point unique IDs\n if (sourcemapsEnabled) {\n // Clear state from previous builds (important for watch mode and test suites)\n debugIdWrappedPaths.clear();\n\n if (!initialOptions.bundle) {\n logger.warn(\n 'The Sentry esbuild plugin only supports esbuild with `bundle: true` being set in the esbuild build options. Esbuild will probably crash now. Sorry about that. If you need to upload sourcemaps without `bundle: true`, it is recommended to use Sentry CLI instead: https://docs.sentry.io/platforms/javascript/sourcemaps/uploading/cli/',\n );\n }\n\n // Wrap entry points to inject debug IDs\n onResolve({ filter: /.*/ }, args => {\n if (args.kind !== 'entry-point') {\n return;\n }\n\n // Skip injecting debug IDs into modules specified in the esbuild `inject` option\n // since they're already part of the entry points\n if (initialOptions.inject?.includes(args.path)) {\n return;\n }\n\n const resolvedPath = path.isAbsolute(args.path) ? args.path : path.join(args.resolveDir, args.path);\n\n // Skip injecting debug IDs into paths that have already been wrapped\n if (debugIdWrappedPaths.has(resolvedPath)) {\n return;\n }\n debugIdWrappedPaths.add(resolvedPath);\n\n return {\n pluginName,\n path: resolvedPath,\n pluginData: {\n isDebugIdProxy: true,\n originalPath: args.path,\n originalResolveDir: args.resolveDir,\n },\n // We need to add a suffix here, otherwise esbuild will mark the entrypoint as resolved and won't traverse\n // the module tree any further down past the proxy module because we're essentially creating a dependency\n // loop back to the proxy module.\n // By setting a suffix we're telling esbuild that the entrypoint and proxy module are two different things,\n // making it re-resolve the entrypoint when it is imported from the proxy module.\n // Super confusing? Yes. Works? Apparently... Let's see.\n suffix: '?sentryDebugIdProxy=true',\n };\n });\n\n onLoad({ filter: /.*/ }, args => {\n if (!(args.pluginData as { isDebugIdProxy?: boolean })?.isDebugIdProxy) {\n return null;\n }\n\n const originalPath = (args.pluginData as { originalPath: string }).originalPath;\n const originalResolveDir = (args.pluginData as { originalResolveDir: string }).originalResolveDir;\n\n return {\n loader: 'js',\n pluginName,\n contents: `\n import \"_sentry-debug-id-injection-stub\";\n import * as OriginalModule from ${JSON.stringify(originalPath)};\n export default OriginalModule.default;\n export * from ${JSON.stringify(originalPath)};`,\n resolveDir: originalResolveDir,\n };\n });\n\n onResolve({ filter: /_sentry-debug-id-injection-stub/ }, args => {\n return {\n path: args.path,\n sideEffects: true,\n pluginName,\n namespace: 'sentry-debug-id-stub',\n suffix: `?sentry-module-id=${randomUUID()}`,\n };\n });\n\n onLoad({ filter: /_sentry-debug-id-injection-stub/, namespace: 'sentry-debug-id-stub' }, () => {\n return {\n loader: 'js',\n pluginName,\n contents: getDebugIdSnippet(randomUUID()).code(),\n };\n });\n }\n\n // Create release and optionally upload\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n\n initialOptions.metafile = true;\n onEnd(async result => {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled) {\n const buildArtifacts = result.metafile ? Object.keys(result.metafile.outputs) : [];\n\n if (options.sourcemaps?.disable !== 'disable-upload') {\n await upload(buildArtifacts);\n } else if (initialOptions.write === false) {\n logger.debug('Build output is not written to disk. Skipping debug ID injection into build artifacts.');\n } else {\n // The upload routine (which stamps debug IDs into temp copies of the artifacts) is\n // skipped with `disable-upload`. esbuild has no hook to modify outputs before they are\n // written, so the emitted artifacts get stamped on disk instead.\n const outputDir = initialOptions.absWorkingDir ?? process.cwd();\n await Promise.all(\n buildArtifacts\n .filter(isJsFile)\n .map(bundle =>\n addDebugIdToEmittedArtifacts(\n path.resolve(outputDir, bundle),\n logger,\n options.sourcemaps?.resolveSourceMap,\n ),\n ),\n );\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n });\n },\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport default sentryEsbuildPlugin;\nexport type { Options as SentryEsbuildPluginOptions } from '../core';\n"],"names":["createRequire","createSentryBuildPluginManager","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","path","randomUUID","getDebugIdSnippet","createDebugIdUploadFunction","isJsFile","addDebug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AW,cAAA,CAAe,KAAA,KAAU,KAAA,EAAO;AACzC,cAAA,MAAA,CAAO,MAAM,wFAAwF,CAAA;AAAA,YACvG,CAAA,MAAO;AAIL,cAAA,MAAM,SAAA,GAAY,cAAA,CAAe,aAAA,IAAiB,OAAA,CAAQ,GAAA,EAAI;AAC9D,cAAA,MAAM,OAAA,CAAQ,GAAA;AAAA,gBACZ,cAAA,CACG,MAAA,CAAOC,cAAQ,CAAA,CACf,GAAA;AAAA,kBAAI,CAAA,MAAA,KACHC,0CAAA;AAAA,oBACEL,eAAA,CAAK,OAAA,CAAQ,SAAA,EAAW,MAAM,CAAA;AAAA,oBAC9B,MAAA;AAAA,oBACA,QAAQ,UAAA,EAAY;AAAA;AACtB;AACF,eACJ;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAA,SAAE;AACA,UAAA,oCAAA,EAAqC;AACrC,UAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,QACjD;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;;"}
@@ -183,6 +183,23 @@ function _rollupPluginInternal(userOptions = {}, buildTool, buildToolMajorVersio
183
183
  map: ms.generateMap({ file: chunk.fileName, hires: "boundary" })
184
184
  };
185
185
  }
186
+ function generateBundle(_outputOptions, bundle) {
187
+ for (const output of Object.values(bundle)) {
188
+ if (output.type !== "chunk" || !index.isJsFile(output.fileName)) {
189
+ continue;
190
+ }
191
+ const sourceMapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];
192
+ const sourceMapSource = sourceMapAsset?.type === "asset" && typeof sourceMapAsset.source === "string" ? sourceMapAsset.source : void 0;
193
+ const stamped = debugIdUpload.stampDebugId(output.code, sourceMapSource);
194
+ if (!stamped) {
195
+ continue;
196
+ }
197
+ output.code = stamped.bundleSource;
198
+ if (stamped.sourceMapSource !== void 0 && sourceMapAsset?.type === "asset") {
199
+ sourceMapAsset.source = stamped.sourceMapSource;
200
+ }
201
+ }
202
+ }
186
203
  async function writeBundle(outputOptions, bundle) {
187
204
  try {
188
205
  await sentryBuildPluginManager.createRelease();
@@ -212,23 +229,16 @@ function _rollupPluginInternal(userOptions = {}, buildTool, buildToolMajorVersio
212
229
  }
213
230
  }
214
231
  const name = `sentry-${buildTool}-plugin`;
215
- if (shouldTransform) {
216
- const transformHook = buildTool === "vite" ? {
217
- filter: { id: JS_MODULE_ID_FILTER },
218
- handler: transform
219
- } : transform;
220
- return {
221
- name,
222
- buildStart,
223
- transform: transformHook,
224
- renderChunk,
225
- writeBundle
226
- };
227
- }
232
+ const transformHook = buildTool === "vite" ? {
233
+ filter: { id: JS_MODULE_ID_FILTER },
234
+ handler: transform
235
+ } : transform;
228
236
  return {
229
237
  name,
230
238
  buildStart,
239
+ ...shouldTransform ? { transform: transformHook } : {},
231
240
  renderChunk,
241
+ ...options.sourcemaps?.disable === "disable-upload" ? { generateBundle: { order: "pre", handler: generateBundle } } : {},
232
242
  writeBundle
233
243
  };
234
244
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/rollup/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n stringToUUID,\n COMMENT_USE_STRICT_REGEX,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n} from '../core';\nimport type {\n ComponentAnnotationTransformMeta,\n ComponentAnnotationTransformResult,\n} from '../core/component-annotation-vite';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\n\n// The subset of Rollup's `TransformResult` that this plugin's `transform`\n// hook actually returns. Defined locally instead of imported from `rollup`\n// because `rollup` is an optional dependency.\ntype TransformResult = { code: string; map?: SourceMap | string | { mappings: string } | null } | null | undefined;\n\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\ntype ViteAnnotationHooks = {\n transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<ComponentAnnotationTransformResult>;\n};\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\n\nfunction hasExistingDebugID(code: string): boolean {\n // Check if a debug ID has already been injected to avoid duplicate injection (e.g. by another plugin or Sentry CLI)\n const chunkStartSnippet = code.slice(0, 6000);\n const chunkEndSnippet = code.slice(-500);\n\n if (chunkStartSnippet.includes('_sentryDebugIdIdentifier') || chunkEndSnippet.includes('//# debugId=')) {\n return true; // Debug ID already present, skip injection\n }\n\n return false;\n}\n\nfunction getRollupMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const rollup = req('rollup') as { VERSION?: string };\n return rollup.VERSION?.split('.')[0];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nfunction getViteParseAstAsync(): Promise<ViteParseAstAsync | null> {\n if (!viteParseAstAsyncPromise) {\n viteParseAstAsyncPromise = Promise.resolve()\n .then(async () => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Vite is an optional runtime peer for this package\n const viteModule = createRequire(import.meta.url)('vite') as ViteModule;\n\n if (typeof viteModule.parseAstAsync !== 'function') {\n return null;\n }\n\n try {\n await viteModule.parseAstAsync('const x = <div />;', { lang: 'tsx' });\n } catch {\n return null;\n }\n\n return viteModule.parseAstAsync;\n })\n .catch(() => null);\n }\n\n return viteParseAstAsyncPromise;\n}\n\n/**\n * @ignore - this is the internal plugin factory function only used for the Vite plugin!\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _rollupPluginInternal(\n userOptions: Options = {},\n buildTool: 'rollup' | 'vite',\n buildToolMajorVersion?: string,\n) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[sentry-${buildTool}-plugin]`,\n buildTool,\n buildToolMajorVersion: buildToolMajorVersion || getRollupMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-noop-plugin',\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n const transformViteAnnotations =\n options.reactComponentAnnotation?.enabled &&\n buildTool === 'vite' &&\n buildToolMajorVersion === '8' &&\n !options.reactComponentAnnotation?._experimentalInjectIntoHtml\n ? (() => {\n let viteAnnotationHooksPromise: Promise<ViteAnnotationHooks> | undefined;\n\n return {\n transform(code: string, id: string, meta?: ComponentAnnotationTransformMeta) {\n if (!viteAnnotationHooksPromise) {\n viteAnnotationHooksPromise = import('../core/component-annotation-vite').then(\n ({ createViteComponentNameAnnotateHooks }) =>\n createViteComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n getViteParseAstAsync,\n ),\n );\n }\n\n return viteAnnotationHooksPromise.then(hooks => hooks.transform(code, id, meta));\n },\n };\n })()\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n const shouldTransform = transformAnnotations || transformReplace;\n\n function buildStart(): void {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n }\n\n async function transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<TransformResult> {\n // Component annotations are only in user code and boolean flag replacements are\n // only in Sentry code. If we successfully add annotations, we can return early.\n let shouldRunBabelAnnotations = true;\n\n if (transformViteAnnotations?.transform) {\n const result = await transformViteAnnotations.transform(code, id, meta);\n if (result) {\n return result;\n }\n\n if (result === null) {\n shouldRunBabelAnnotations = false;\n }\n }\n\n if (shouldRunBabelAnnotations && transformAnnotations?.transform) {\n const result = await transformAnnotations.transform(code, id);\n if (result) {\n return result;\n }\n }\n\n if (transformReplace) {\n return replaceBooleanFlagsInCode(code, replacementValues);\n }\n\n return null;\n }\n\n function renderChunk(\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null },\n _?: unknown,\n meta?: { magicString?: MagicString },\n ): {\n code: string;\n map?: SourceMap;\n } | null {\n if (!isJsFile(chunk.fileName)) {\n return null; // returning null means not modifying the chunk at all\n }\n\n // Skip empty chunks and HTML facade chunks (Vite MPA)\n if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) {\n return null;\n }\n\n const injectCode = staticInjectionCode.clone();\n\n if (sourcemapsEnabled && !hasExistingDebugID(code)) {\n const debugId = stringToUUID(code); // generate a deterministic debug ID\n injectCode.append(getDebugIdSnippet(debugId));\n }\n\n if (injectCode.isEmpty()) {\n return null;\n }\n\n const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });\n const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];\n\n if (match) {\n // Add injected code after any comments or \"use strict\" at the beginning of the bundle.\n ms.appendLeft(match.length, injectCode.code());\n } else {\n // ms.replace() doesn't work when there is an empty string match (which happens if\n // there is neither, a comment, nor a \"use strict\" at the top of the chunk) so we\n // need this special case here.\n ms.prepend(injectCode.code());\n }\n\n // Rolldown can pass a native MagicString instance in meta.magicString\n // https://rolldown.rs/in-depth/native-magic-string#usage-examples\n if (ms?.constructor?.name === 'BindingMagicString') {\n // Rolldown docs say to return the magic string instance directly in this case\n return { code: ms as unknown as string };\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ file: chunk.fileName, hires: 'boundary' as unknown as undefined }),\n };\n }\n\n async function writeBundle(\n outputOptions: { dir?: string; file?: string },\n bundle: { [fileName: string]: unknown },\n ): Promise<void> {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n if (outputOptions.dir) {\n const outputDir = outputOptions.dir;\n const JS_AND_MAP_PATTERNS = [\n '/**/*.js',\n '/**/*.mjs',\n '/**/*.cjs',\n '/**/*.js.map',\n '/**/*.mjs.map',\n '/**/*.cjs.map',\n ].map(q => `${q}?(\\\\?*)?(#*)`); // We want to allow query and hash strings at the end of files\n const buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n await upload(buildArtifacts);\n } else if (outputOptions.file) {\n await upload([outputOptions.file]);\n } else {\n const buildArtifacts = Object.keys(bundle).map(asset => path.join(path.resolve(), asset));\n await upload(buildArtifacts);\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n }\n\n const name = `sentry-${buildTool}-plugin`;\n\n if (shouldTransform) {\n const transformHook =\n buildTool === 'vite'\n ? {\n filter: { id: JS_MODULE_ID_FILTER },\n handler: transform,\n }\n : transform;\n\n return {\n name,\n buildStart,\n transform: transformHook,\n renderChunk,\n writeBundle,\n };\n }\n\n return {\n name,\n buildStart,\n renderChunk,\n writeBundle,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any\nexport function sentryRollupPlugin(userOptions: Options = {}): any {\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return [_rollupPluginInternal(userOptions, 'rollup')];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"names":["createRequire","createSentryBuildPluginManager","createDebugIdUploadFunction","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","replaceBooleanFlagsInCode","isJsFile","shouldSkipCodeInjection","stringToUUID","getDebugIdSnippet","MagicString","COMMENT_USE_STRICT_REGEX","globFiles","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAI,wBAAA;AAEJ,MAAM,mBAAA,GAAsB,4BAAA;AAE5B,SAAS,mBAAmB,IAAA,EAAuB;AAEjD,EAAA,MAAM,iBAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAI,CAAA;AAC5C,EAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAEvC,EAAA,IAAI,kBAAkB,QAAA,CAAS,0BAA0B,KAAK,eAAA,CAAgB,QAAA,CAAS,cAAc,CAAA,EAAG;AACtG,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,qBAAA,GAA4C;AACnD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAMA,yBAAA,CAAc,iQAAe,CAAA;AACzC,IAAA,MAAM,MAAA,GAAS,IAAI,QAAQ,CAAA;AAC3B,IAAA,OAAO,MAAA,CAAO,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AC/E,UAAA,MAAM,OAAO,cAAc,CAAA;AAAA,QAC7B,CAAA,MAAA,IAAW,cAAc,IAAA,EAAM;AAC7B,UAAA,MAAM,MAAA,CAAO,CAAC,aAAA,CAAc,IAAI,CAAC,CAAA;AAAA,QACnC,CAAA,MAAO;AACL,UAAA,MAAM,cAAA,GAAiB,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CAAE,GAAA,CAAI,CAAA,KAAA,KAASC,eAAA,CAAK,IAAA,CAAKA,eAAA,CAAK,OAAA,EAAQ,EAAG,KAAK,CAAC,CAAA;AACxF,UAAA,MAAM,OAAO,cAAc,CAAA;AAAA,QAC7B;AAAA,MACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,oCAAA,EAAqC;AACrC,MAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,IACjD;AAAA,EACF;AAEA,EAAA,MAAM,IAAA,GAAO,UAAU,SAAS,CAAA,OAAA,CAAA;AAEhC,EAAA,IAAI,eAAA,EAAiB;AACnB,IAAA,MAAM,aAAA,GACJ,cAAc,MAAA,GACV;AAAA,MACE,MAAA,EAAQ,EAAE,EAAA,EAAI,mBAAA,EAAoB;AAAA,MAClC,OAAA,EAAS;AAAA,KACX,GACA,SAAA;AAEN,IAAA,OAAO;AAAA,MACL,IAAA;AAAA,MACA,UAAA;AAAA,MACA,SAAA,EAAW,aAAA;AAAA,MACX,WAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF;AACF;AAGO,SAAS,kBAAA,CAAmB,WAAA,GAAuB,EAAC,EAAQ;AAGjE,EAAA,OAAO,CAAC,qBAAA,CAAsB,WAAA,EAAa,QAAQ,CAAC,CAAA;AACtD;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/rollup/index.ts"],"sourcesContent":["import type { Options } from '../core';\nimport {\n createSentryBuildPluginManager,\n generateReleaseInjectorCode,\n generateModuleMetadataInjectorCode,\n isJsFile,\n shouldSkipCodeInjection,\n getDebugIdSnippet,\n stringToUUID,\n COMMENT_USE_STRICT_REGEX,\n createDebugIdUploadFunction,\n globFiles,\n createComponentNameAnnotateHooks,\n replaceBooleanFlagsInCode,\n CodeInjection,\n stampDebugId,\n} from '../core';\nimport type {\n ComponentAnnotationTransformMeta,\n ComponentAnnotationTransformResult,\n} from '../core/component-annotation-vite';\nimport type { SourceMap } from 'magic-string';\nimport MagicString from 'magic-string';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\n\n// The subset of Rollup's `TransformResult` that this plugin's `transform`\n// hook actually returns. Defined locally instead of imported from `rollup`\n// because `rollup` is an optional dependency.\ntype TransformResult = { code: string; map?: SourceMap | string | { mappings: string } | null } | null | undefined;\n\n// The subset of Rollup's `OutputBundle` the stamping hook reads.\ntype OutputBundle = Record<\n string,\n | { type: 'chunk'; fileName: string; code: string; sourcemapFileName?: string | null }\n | { type: 'asset'; fileName: string; source: string | Uint8Array }\n>;\n\ntype ViteModule = {\n parseAstAsync?: (code: string, options: { lang: 'jsx' | 'tsx' }) => Promise<unknown>;\n};\n\ntype ViteParseAstAsync = NonNullable<ViteModule['parseAstAsync']>;\ntype ViteAnnotationHooks = {\n transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<ComponentAnnotationTransformResult>;\n};\n\nlet viteParseAstAsyncPromise: Promise<ViteParseAstAsync | null> | undefined;\n\nconst JS_MODULE_ID_FILTER = /\\.[cm]?[jt]sx?(?:[?#].*)?$/;\n\nfunction hasExistingDebugID(code: string): boolean {\n // Check if a debug ID has already been injected to avoid duplicate injection (e.g. by another plugin or Sentry CLI)\n const chunkStartSnippet = code.slice(0, 6000);\n const chunkEndSnippet = code.slice(-500);\n\n if (chunkStartSnippet.includes('_sentryDebugIdIdentifier') || chunkEndSnippet.includes('//# debugId=')) {\n return true; // Debug ID already present, skip injection\n }\n\n return false;\n}\n\nfunction getRollupMajorVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Rollup already transpiles this for us\n const req = createRequire(import.meta.url);\n const rollup = req('rollup') as { VERSION?: string };\n return rollup.VERSION?.split('.')[0];\n } catch {\n // do nothing, we'll just not report a version\n }\n\n return undefined;\n}\n\nfunction getViteParseAstAsync(): Promise<ViteParseAstAsync | null> {\n if (!viteParseAstAsyncPromise) {\n viteParseAstAsyncPromise = Promise.resolve()\n .then(async () => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - Vite is an optional runtime peer for this package\n const viteModule = createRequire(import.meta.url)('vite') as ViteModule;\n\n if (typeof viteModule.parseAstAsync !== 'function') {\n return null;\n }\n\n try {\n await viteModule.parseAstAsync('const x = <div />;', { lang: 'tsx' });\n } catch {\n return null;\n }\n\n return viteModule.parseAstAsync;\n })\n .catch(() => null);\n }\n\n return viteParseAstAsyncPromise;\n}\n\n/**\n * @ignore - this is the internal plugin factory function only used for the Vite plugin!\n */\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nexport function _rollupPluginInternal(\n userOptions: Options = {},\n buildTool: 'rollup' | 'vite',\n buildToolMajorVersion?: string,\n) {\n const sentryBuildPluginManager = createSentryBuildPluginManager(userOptions, {\n loggerPrefix: userOptions._metaOptions?.loggerPrefixOverride ?? `[sentry-${buildTool}-plugin]`,\n buildTool,\n buildToolMajorVersion: buildToolMajorVersion || getRollupMajorVersion(),\n });\n\n const {\n logger,\n normalizedOptions: options,\n bundleSizeOptimizationReplacementValues: replacementValues,\n bundleMetadata,\n createDependencyOnBuildArtifacts,\n } = sentryBuildPluginManager;\n\n if (options.disable) {\n return {\n name: 'sentry-noop-plugin',\n };\n }\n\n if (process.cwd().match(/\\\\node_modules\\\\|\\/node_modules\\//)) {\n logger.warn('Running Sentry plugin from within a `node_modules` folder. Some features may not work.');\n }\n\n const freeGlobalDependencyOnBuildArtifacts = createDependencyOnBuildArtifacts();\n const upload = createDebugIdUploadFunction({ sentryBuildPluginManager });\n const sourcemapsEnabled = options.sourcemaps?.disable !== true;\n const staticInjectionCode = new CodeInjection();\n\n if (!options.release.inject) {\n logger.debug('Release injection disabled via `release.inject` option. Will not inject release.');\n } else if (!options.release.name) {\n logger.debug(\n 'No release name provided. Will not inject release. Please set the `release.name` option to identify your release.',\n );\n } else {\n staticInjectionCode.append(\n generateReleaseInjectorCode({\n release: options.release.name,\n injectBuildInformation: options._experiments.injectBuildInformation || false,\n }),\n );\n }\n\n if (Object.keys(bundleMetadata).length > 0) {\n staticInjectionCode.append(generateModuleMetadataInjectorCode(bundleMetadata));\n }\n\n const transformAnnotations = options.reactComponentAnnotation?.enabled\n ? createComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n !!options.reactComponentAnnotation?._experimentalInjectIntoHtml,\n )\n : undefined;\n const transformViteAnnotations =\n options.reactComponentAnnotation?.enabled &&\n buildTool === 'vite' &&\n buildToolMajorVersion === '8' &&\n !options.reactComponentAnnotation?._experimentalInjectIntoHtml\n ? (() => {\n let viteAnnotationHooksPromise: Promise<ViteAnnotationHooks> | undefined;\n\n return {\n transform(code: string, id: string, meta?: ComponentAnnotationTransformMeta) {\n if (!viteAnnotationHooksPromise) {\n viteAnnotationHooksPromise = import('../core/component-annotation-vite').then(\n ({ createViteComponentNameAnnotateHooks }) =>\n createViteComponentNameAnnotateHooks(\n options.reactComponentAnnotation?.ignoredComponents || [],\n getViteParseAstAsync,\n ),\n );\n }\n\n return viteAnnotationHooksPromise.then(hooks => hooks.transform(code, id, meta));\n },\n };\n })()\n : undefined;\n\n const transformReplace = Object.keys(replacementValues).length > 0;\n const shouldTransform = transformAnnotations || transformReplace;\n\n function buildStart(): void {\n void sentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal().catch(() => {\n // Telemetry failures are acceptable\n });\n }\n\n async function transform(\n code: string,\n id: string,\n meta?: ComponentAnnotationTransformMeta,\n ): Promise<TransformResult> {\n // Component annotations are only in user code and boolean flag replacements are\n // only in Sentry code. If we successfully add annotations, we can return early.\n let shouldRunBabelAnnotations = true;\n\n if (transformViteAnnotations?.transform) {\n const result = await transformViteAnnotations.transform(code, id, meta);\n if (result) {\n return result;\n }\n\n if (result === null) {\n shouldRunBabelAnnotations = false;\n }\n }\n\n if (shouldRunBabelAnnotations && transformAnnotations?.transform) {\n const result = await transformAnnotations.transform(code, id);\n if (result) {\n return result;\n }\n }\n\n if (transformReplace) {\n return replaceBooleanFlagsInCode(code, replacementValues);\n }\n\n return null;\n }\n\n function renderChunk(\n code: string,\n chunk: { fileName: string; facadeModuleId?: string | null },\n _?: unknown,\n meta?: { magicString?: MagicString },\n ): {\n code: string;\n map?: SourceMap;\n } | null {\n if (!isJsFile(chunk.fileName)) {\n return null; // returning null means not modifying the chunk at all\n }\n\n // Skip empty chunks and HTML facade chunks (Vite MPA)\n if (shouldSkipCodeInjection(code, chunk.facadeModuleId)) {\n return null;\n }\n\n const injectCode = staticInjectionCode.clone();\n\n if (sourcemapsEnabled && !hasExistingDebugID(code)) {\n const debugId = stringToUUID(code); // generate a deterministic debug ID\n injectCode.append(getDebugIdSnippet(debugId));\n }\n\n if (injectCode.isEmpty()) {\n return null;\n }\n\n const ms = meta?.magicString || new MagicString(code, { filename: chunk.fileName });\n const match = code.match(COMMENT_USE_STRICT_REGEX)?.[0];\n\n if (match) {\n // Add injected code after any comments or \"use strict\" at the beginning of the bundle.\n ms.appendLeft(match.length, injectCode.code());\n } else {\n // ms.replace() doesn't work when there is an empty string match (which happens if\n // there is neither, a comment, nor a \"use strict\" at the top of the chunk) so we\n // need this special case here.\n ms.prepend(injectCode.code());\n }\n\n // Rolldown can pass a native MagicString instance in meta.magicString\n // https://rolldown.rs/in-depth/native-magic-string#usage-examples\n if (ms?.constructor?.name === 'BindingMagicString') {\n // Rolldown docs say to return the magic string instance directly in this case\n return { code: ms as unknown as string };\n }\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ file: chunk.fileName, hires: 'boundary' as unknown as undefined }),\n };\n }\n\n /**\n * Stamps debug IDs into the emitted chunks and source maps.\n *\n * `disable-upload` skips the upload routine (which stamps debug IDs into temp copies), so the emitted\n * artifacts get stamped here instead. Not in `renderChunk`: minifiers running after it would strip the\n * comment. Rollup computes `[hash]` file names before this hook, so only plugins that hash the final\n * assets afterwards (e.g. subresource integrity) see the stamped content.\n */\n function generateBundle(_outputOptions: unknown, bundle: OutputBundle): void {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !isJsFile(output.fileName)) {\n continue;\n }\n\n const sourceMapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];\n const sourceMapSource =\n sourceMapAsset?.type === 'asset' && typeof sourceMapAsset.source === 'string'\n ? sourceMapAsset.source\n : undefined;\n\n const stamped = stampDebugId(output.code, sourceMapSource);\n if (!stamped) {\n continue;\n }\n\n output.code = stamped.bundleSource;\n if (stamped.sourceMapSource !== undefined && sourceMapAsset?.type === 'asset') {\n sourceMapAsset.source = stamped.sourceMapSource;\n }\n }\n }\n\n async function writeBundle(\n outputOptions: { dir?: string; file?: string },\n bundle: { [fileName: string]: unknown },\n ): Promise<void> {\n try {\n await sentryBuildPluginManager.createRelease();\n\n if (sourcemapsEnabled && options.sourcemaps?.disable !== 'disable-upload') {\n if (outputOptions.dir) {\n const outputDir = outputOptions.dir;\n const JS_AND_MAP_PATTERNS = [\n '/**/*.js',\n '/**/*.mjs',\n '/**/*.cjs',\n '/**/*.js.map',\n '/**/*.mjs.map',\n '/**/*.cjs.map',\n ].map(q => `${q}?(\\\\?*)?(#*)`); // We want to allow query and hash strings at the end of files\n const buildArtifacts = await globFiles(JS_AND_MAP_PATTERNS, { root: outputDir });\n await upload(buildArtifacts);\n } else if (outputOptions.file) {\n await upload([outputOptions.file]);\n } else {\n const buildArtifacts = Object.keys(bundle).map(asset => path.join(path.resolve(), asset));\n await upload(buildArtifacts);\n }\n }\n } finally {\n freeGlobalDependencyOnBuildArtifacts();\n await sentryBuildPluginManager.deleteArtifacts();\n }\n }\n\n const name = `sentry-${buildTool}-plugin`;\n const transformHook =\n buildTool === 'vite'\n ? {\n filter: { id: JS_MODULE_ID_FILTER },\n handler: transform,\n }\n : transform;\n\n return {\n name,\n buildStart,\n ...(shouldTransform ? { transform: transformHook } : {}),\n renderChunk,\n ...(options.sourcemaps?.disable === 'disable-upload'\n ? { generateBundle: { order: 'pre' as const, handler: generateBundle } }\n : {}),\n writeBundle,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-explicit-any\nexport function sentryRollupPlugin(userOptions: Options = {}): any {\n // We return an array here so we don't break backwards compatibility with what\n // unplugin used to return\n return [_rollupPluginInternal(userOptions, 'rollup')];\n}\n\nexport type { Options as SentryRollupPluginOptions } from '../core';\n"],"names":["createRequire","createSentryBuildPluginManager","createDebugIdUploadFunction","CodeInjection","generateReleaseInjectorCode","generateModuleMetadataInjectorCode","createComponentNameAnnotateHooks","replaceBooleanFlagsInCode","isJsFile","shouldSkipCodeInjection","stringToUUID","getDebugIdSnippet","MagicString","COMMENT_USE_STRICT_REGEX","stampDebugId","globFiles","path"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAI,wBAAA;AAEJ,MAAM,mBAAA,GAAsB,4BAAA;AAE5B,SAAS,mBAAmB,IAAA,EAAuB;AAEjD,EAAA,MAAM,iBAAA,GAAoB,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,GAAI,CAAA;AAC5C,EAAA,MAAM,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAEvC,EAAA,IAAI,kBAAkB,QAAA,CAAS,0BAA0B,KAAK,eAAA,CAAgB,QAAA,CAAS,cAAc,CAAA,EAAG;AACtG,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,qBAAA,GAA4C;AACnD,EAAA,IAAI;AAGF,IAAA,MAAM,GAAA,GAAMA,yBA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KAAA,KAASC,eAAA,CAAK,IAAA,CAAKA,eAAA,CAAK,OAAA,EAAQ,EAAG,KAAK,CAAC,CAAA;AACxF,UAAA,MAAM,OAAO,cAAc,CAAA;AAAA,QAC7B;AAAA,MACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,oCAAA,EAAqC;AACrC,MAAA,MAAM,yBAAyB,eAAA,EAAgB;AAAA,IACjD;AAAA,EACF;AAEA,EAAA,MAAM,IAAA,GAAO,UAAU,SAAS,CAAA,OAAA,CAAA;AAChC,EAAA,MAAM,aAAA,GACJ,cAAc,MAAA,GACV;AAAA,IACE,MAAA,EAAQ,EAAE,EAAA,EAAI,mBAAA,EAAoB;AAAA,IAClC,OAAA,EAAS;AAAA,GACX,GACA,SAAA;AAEN,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,UAAA;AAAA,IACA,GAAI,eAAA,GAAkB,EAAE,SAAA,EAAW,aAAA,KAAkB,EAAC;AAAA,IACtD,WAAA;AAAA,IACA,GAAI,OAAA,CAAQ,UAAA,EAAY,OAAA,KAAY,mBAChC,EAAE,cAAA,EAAgB,EAAE,KAAA,EAAO,KAAA,EAAgB,OAAA,EAAS,cAAA,EAAe,KACnE,EAAC;AAAA,IACL;AAAA,GACF;AACF;AAGO,SAAS,kBAAA,CAAmB,WAAA,GAAuB,EAAC,EAAQ;AAGjE,EAAA,OAAO,CAAC,qBAAA,CAAsB,WAAA,EAAa,QAAQ,CAAC,CAAA;AACtD;;;;;"}
@@ -43,6 +43,25 @@ function getWebpackMajorVersion() {
43
43
  return void 0;
44
44
  }
45
45
  }
46
+ function addDebugIdsToAssets(compilation, RawSource) {
47
+ for (const asset of compilation.getAssets()) {
48
+ if (!index.isJsFile(asset.name)) {
49
+ continue;
50
+ }
51
+ const bundleSource = asset.source.source().toString();
52
+ const relatedSourceMap = asset.info.related?.sourceMap;
53
+ const sourceMapName = typeof relatedSourceMap === "string" ? relatedSourceMap : `${asset.name}.map`;
54
+ const sourceMapAsset = compilation.getAsset(sourceMapName);
55
+ const stamped = debugIdUpload.stampDebugId(bundleSource, sourceMapAsset?.source.source().toString());
56
+ if (!stamped) {
57
+ continue;
58
+ }
59
+ compilation.updateAsset(asset.name, new RawSource(stamped.bundleSource));
60
+ if (stamped.sourceMapSource !== void 0) {
61
+ compilation.updateAsset(sourceMapName, new RawSource(stamped.sourceMapSource));
62
+ }
63
+ }
64
+ }
46
65
  function sentryWebpackPluginFactory({
47
66
  BannerPlugin: UnsafeBannerPlugin,
48
67
  DefinePlugin: UnsafeDefinePlugin
@@ -123,6 +142,21 @@ function sentryWebpackPluginFactory({
123
142
  );
124
143
  }
125
144
  }
145
+ if (sourcemapsEnabled && options.sourcemaps?.disable === "disable-upload") {
146
+ const RawSource = compiler.webpack?.sources?.RawSource;
147
+ const stage = (compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_DEV_TOOLING ?? 500) + 1;
148
+ if (!RawSource) {
149
+ logger.warn(
150
+ "Webpack sources are not available. Skipping debug ID injection into emitted source maps. This usually means webpack is not properly configured."
151
+ );
152
+ } else {
153
+ compiler.hooks.thisCompilation.tap("sentry-webpack-plugin", (compilation) => {
154
+ compilation.hooks.processAssets.tap({ name: "sentry-webpack-plugin", stage }, () => {
155
+ addDebugIdsToAssets(compilation, RawSource);
156
+ });
157
+ });
158
+ }
159
+ }
126
160
  if (transformReplace && DefinePlugin) {
127
161
  compiler.options.plugins = compiler.options.plugins || [];
128
162
  compiler.options.plugins.push(new DefinePlugin(replacementValues));