@@ -30,6 +30,8 @@ import util from "util";
3030import { getDependencies , getPackageJson , parseMajorVersion } from "./utils" ;
3131import { glob } from "glob" ;
3232import { injectDebugIdSnippetIntoChunk , prepareBundleForDebugIdUpload } from "./debug-id" ;
33+ import { SourceMapSource } from "webpack-sources" ;
34+ import type { sources } from "webpack" ;
3335
3436const ALLOWED_TRANSFORMATION_FILE_ENDINGS = [ ".js" , ".ts" , ".jsx" , ".tsx" , ".mjs" ] ;
3537
@@ -389,6 +391,68 @@ const unplugin = createUnplugin<Options>((options, unpluginMetaContext) => {
389391 }
390392 } ,
391393 } ,
394+ webpack ( compiler ) {
395+ if ( options . _experiments ?. debugIdUpload ) {
396+ // Cache inspired by https://github.com/webpack/webpack/pull/15454
397+ const cache = new WeakMap < sources . Source , sources . Source > ( ) ;
398+
399+ compiler . hooks . compilation . tap ( "sentry-plugin" , ( compilation ) => {
400+ compilation . hooks . optimizeChunkAssets . tap ( "sentry-plugin" , ( chunks ) => {
401+ chunks . forEach ( ( chunk ) => {
402+ const fileNames = chunk . files ;
403+ fileNames . forEach ( ( fileName ) => {
404+ const source = compilation . assets [ fileName ] ;
405+
406+ if ( ! source ) {
407+ logger . warn (
408+ "Unable to access compilation assets. If you see this warning, it is likely a bug in the Sentry webpack plugin. Feel free to open an issue at https://github.com/getsentry/sentry-javascript-bundler-plugins with reproduction steps."
409+ ) ;
410+ return ;
411+ }
412+
413+ compilation . updateAsset ( fileName , ( oldSource ) => {
414+ const cached = cache . get ( oldSource ) ;
415+ if ( cached ) {
416+ return cached ;
417+ }
418+
419+ const originalCode = source . source ( ) . toString ( ) ;
420+
421+ // The source map type is very annoying :(
422+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
423+ const originalSourceMap = source . map ( ) as any ;
424+
425+ const { code : newCode , map : newSourceMap } = injectDebugIdSnippetIntoChunk (
426+ originalCode ,
427+ fileName
428+ ) ;
429+
430+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
431+ newSourceMap . sources = originalSourceMap . sources as string [ ] ;
432+
433+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
434+ newSourceMap . sourcesContent = originalSourceMap . sourcesContent as string [ ] ;
435+
436+ const newSource = new SourceMapSource (
437+ newCode ,
438+ fileName ,
439+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
440+ originalSourceMap ,
441+ originalCode ,
442+ newSourceMap ,
443+ false
444+ ) as sources . Source ;
445+
446+ cache . set ( oldSource , newSource ) ;
447+
448+ return newSource ;
449+ } ) ;
450+ } ) ;
451+ } ) ;
452+ } ) ;
453+ } ) ;
454+ }
455+ } ,
392456 } ;
393457} ) ;
394458
0 commit comments