GithubHelp home page GithubHelp logo

bugsnag / webpack-bugsnag-plugins Goto Github PK

View Code? Open in Web Editor NEW
32.0 28.0 28.0 438 KB

Webpack plugins for common BugSnag actions.

License: MIT License

JavaScript 96.07% Shell 3.93%
bugsnag webpack-plugin platforms

webpack-bugsnag-plugins's Introduction

webpack-bugsnag-plugins

Build status NPM

Webpack plugins for common Bugsnag actions.

Installation

npm install --save-dev webpack-bugsnag-plugins

Plugins

new BugsnagBuildReporterPlugin(build, opts):WebpackPlugin

const { BugsnagBuildReporterPlugin } = require('webpack-bugsnag-plugins')

Reports your application's build to Bugsnag. It can auto detect source control from .git, .hg and package.json. This plugin hooks into the 'after-emit' event once all output files have been generated by the Webpack compiler. If anything causes the compilation to fail before this step, the build report will not get sent.

  • build describes the build you are reporting to Bugsnag
    • apiKey: string your Bugsnag API key [required]
    • appVersion: string the version of the application you are building [required]
    • releaseStage: string 'production', 'staging' etc. (leave blank if this build can be released to different releaseStages)
    • sourceControl: object an object describing the source control of the build (if not specified, the module will attempt to detect source control information from .git, .hg and the nearest package.json)
      • provider: string can be one of: 'github', 'github-enterprise', 'gitlab', 'gitlab-onpremise', 'bitbucket', 'bitbucket-server'
      • repository: string a URL (git/ssh/https) pointing to the repository, or webpage representing the repository
      • revision: string the unique identifier for the commit (e.g. git SHA)
    • builderName: string the name of the person/machine that created this build (defaults to the result of the whoami command)
    • autoAssignRelease: boolean automatically associate this build with any new error events and sessions that are received for the releaseStage until a subsequent build notification is received. If this is set to true and no releaseStage is provided the build will be applied to 'production'.
    • metadata: object an object describing key/value pairs containing any custom build information that provides useful metadata about the build. e.g. build configuration parameters, versions of dependencies, reason for the build etc.
  • opts
    • logLevel: string the minimum severity of log to output ('debug', 'info', 'warn', 'error'), default 'warn'
    • logger: object provide a different logger object { debug, info, warn, error }
    • path: string the path to search for source control info, defaults to process.cwd()
    • endpoint: string post the build payload to a URL other than the default (https://build.bugsnag.com)

Usage

const { BugsnagBuildReporterPlugin } = require('webpack-bugsnag-plugins')

module.exports = {
  entry: './app.js',
  output: {
    path: __dirname,
    filename: './bundle.js'
  },
  plugins: [].concat(
    // It's a good idea to only run this plugin when you're building a bundle
    // that will be released, rather than for every development build
    isDistEnv
      ? new BugsnagBuildReporterPlugin({
          apiKey: 'YOUR_API_KEY',
          appVersion: '1.2.3'
        }, { /* opts */ })
      : []
  )
}

new BugsnagSourceMapUploaderPlugin(opts):WebpackPlugin

const { BugsnagSourceMapUploaderPlugin } = require('webpack-bugsnag-plugins')

Upload your application's sourcemap(s) to Bugsnag. When Webpack is done producing output, this plugin detects sourcemaps for any output chunks and uploads them to Bugsnag.

  • opts provide options to the sourcemap uploader
    • apiKey: string your Bugsnag API key [required]
    • publicPath: string the path to your bundled assets (as the browser will see them). This option must either be provided here, or as output.publicPath in your Webpack config.
    • appVersion: string the version of the application you are building (defaults to the version set in your project's package.json file, if one is specified there)
    • codeBundleId: string the codeBundleId (e.g. for NativeScript projects)
    • overwrite: boolean whether you want to overwrite previously uploaded sourcemaps
    • endpoint: string post the build payload to a URL other than the default (https://upload.bugsnag.com)
    • ignoredBundleExtensions: string[] a list of bundle file extensions which shouldn't be uploaded (default [ '.css' ])

Usage

const { BugsnagSourceMapUploaderPlugin } = require('webpack-bugsnag-plugins')

module.exports = {
  entry: './app.js',
  devtool: 'source-map',
  output: {
    path: __dirname,
    filename: './bundle.js',
    publicPath: 'https://your-app.xyz/assets/'
  },
  plugins: [].concat(
    // It's a good idea to only run this plugin when you're building a bundle
    // that will be released, rather than for every development build
    isDistEnv
      ? new BugsnagSourceMapUploaderPlugin({
          apiKey: 'YOUR_API_KEY',
          appVersion: '1.2.3'
        })
      : []
  )
}

Supported Webpack versions

These plugins have been tested with webpack versions 3, 4 and 5.

Support

Contributing

All contributors are welcome! See our contributing guide.

License

This module is free software released under the MIT License. See LICENSE.txt for details.

webpack-bugsnag-plugins's People

Contributors

bengourley avatar bregenspan avatar chadrien avatar charliegroll avatar djskinner avatar farfromrefug avatar imjoehaines avatar johnkiely1 avatar mattdyoung avatar twometresteve avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-bugsnag-plugins's Issues

Introduce retry logic to upload

When we upload sourcemaps in our CI runs, we occasionally get the following error:

ERROR in BugsnagSourceMapPlugin (Bad Gateway (502) - 
<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>502 Server Error</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Server Error</h1>
<h2>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.</h2>
<h2></h2>
</body></html>
)

It happens quite rarely, but it is pretty annoying to get failed CI runs because of it, so could you consider adding some kind of retry logic (with some sane backoff) to the upload phase?

Error: socket hang up

Sometimes I get socket hang up error during the source map upload and the whole build fails.

> Build error occurred

       { Error: socket hang up

           at createHangUpError (_http_client.js:322:15)

           at TLSSocket.socketOnEnd (_http_client.js:425:23)

           at TLSSocket.emit (events.js:187:15)

           at endReadableNT (_stream_readable.js:1092:12)

           at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }

       error Command failed with exit code 1.

Has anyone else experienced this problem?

Source maps is not differentiate by release stages

You can run different sources on different stages, but you only can use one source map per app version. Now the only workaround is to append release stage to the app version. Would be great to have differentiation on release stages for source maps.

TypeError: Cannot read property 'existsAt' of undefined

I'm trying to use this with the vue-cli 3.0 build.

vue.config.js

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionPlugin = require('compression-webpack-plugin');
const BrotliPlugin = require('brotli-webpack-plugin');
const { BugsnagSourceMapUploaderPlugin } = require('webpack-bugsnag-plugins');

module.exports = {
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      return {
        plugins: [
          new BugsnagSourceMapUploaderPlugin({
            apiKey: '<api key>',
            // appVersion: '1.0.0',
          }),
          new CompressionPlugin(),
          new BrotliPlugin(),
          new BundleAnalyzerPlugin({ analyzerMode: 'static' }),
        ],
      };
    }
    return {
      plugins: [
        new BundleAnalyzerPlugin({ openAnalyzer: false }),
      ],
    };
  },
  chainWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      return config.plugins.delete('fork-ts-checker');
    }
    return config;
  },
};
yarn run v1.9.4
$ vue-cli-service build

⠋  Building for production.../<vue project>/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:54
            map: compilation.assets[map].existsAt,
                                         ^

TypeError: Cannot read property 'existsAt' of undefined
    at maps.map.map (/<vue project>/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:54:42)
    at Array.map (<anonymous>)
    at chunkToSourceMapDescriptors (/<vue project>/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:43:21)
    at Array.map (<anonymous>)
    at plugin (/<vue project>/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:67:39)
    at _err0 (eval at create (/<vue project>/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:12:1)
    at callback (/<vue project>/node_modules/copy-webpack-plugin/dist/index.js:126:17)
    at afterEmit (/<vue project>/node_modules/copy-webpack-plugin/dist/index.js:220:13)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/<vue project>/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:7:1)
    at AsyncSeriesHook.lazyCompileHook (/<vue project>/node_modules/tapable/lib/Hook.js:154:20)
    at asyncLib.forEach.err (/<vue project>/node_modules/@vue/cli-service/node_modules/webpack/lib/Compiler.js:355:27)
    at done (/<vue project>/node_modules/neo-async/async.js:2854:11)
    at /<vue project>/node_modules/neo-async/async.js:2805:7
    at /<vue project>/node_modules/graceful-fs/graceful-fs.js:43:10
    at FSReqWrap.oncomplete (fs.js:141:20)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Issue with webpack v4.29.0 and futureEmitAssets

Stacktrace:

path.js:28
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at extname (path.js:1471:5)
    at maps.map.map (/app/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:70:52)
    at Array.map (<anonymous>)
    at chunkToSourceMapDescriptors (/app/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:47:21)
    at Array.map (<anonymous>)
    at plugin (/app/node_modules/webpack-bugsnag-plugins/source-map-uploader-plugin.js:89:39)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/app/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:7:1)
    at AsyncSeriesHook.lazyCompileHook (/app/node_modules/tapable/lib/Hook.js:154:20)
    at asyncLib.forEachLimit.err (/app/node_modules/next/node_modules/webpack/lib/Compiler.js:432:27)
    at /app/node_modules/neo-async/async.js:2813:7
    at done (/app/node_modules/neo-async/async.js:3521:9)
    at outputFileSystem.writeFile.err (/app/node_modules/next/node_modules/webpack/lib/Compiler.js:400:9)
    at /app/node_modules/graceful-fs/graceful-fs.js:45:10
    at FSReqWrap.oncomplete (fs.js:135:15)

Related to output.futureEmitAssets introduced in webpack v4.29.0 which prevents plugins from accessing asset contents in afterEmit. Setting options.output.futureEmitAssets to false appears to fix this for now but is used by Next.js v8 projects.

Related: honeybadger-io/honeybadger-webpack#85, thredup/rollbar-sourcemap-webpack-plugin#61

Can dependency on App Version be removed?

Hey, so we have some caching of javascript assets across versions following this guide.
https://webpack.js.org/guides/caching/

But the sourcemap uploader plugin has a dependency on app version because bugsnag website matches version and url both to extract sourcemap.

And then it fails fetching sourcemap for our error where we have retained a javascript asset across versions.

TypeError: Cannot read property 'Debug' of undefined

I am using webpack version 4.43.0
node 14

When I installed this package @1.7.0 I cannot even require it.

It throws right away.

When I downgraded to @1.4.0 the code stopped throwing.

const { BugsnagSourceMapUploaderPlugin } = require('webpack-bugsnag-plugins')
// ^^^ throws TypeError: Cannot read property 'Debug' of undefined

Not recognizing multiple sourcemaps in the same chunk

Hi, I'm running into an issue similar to #6 . My app has a single chunk: [ 'main.css', 'main.js', 'main.css.map', 'main.js.map' ]. For each chunk, chunkToSourceMapDescriptor will only find and select the first .map pair it finds, causing the css sourcemap to be the only one to be uploaded.

I'm on Webpack 4.8.3 and webpack-bugsnag-plugins 1.2.1. I'm using mini-css-extract-plugin to extract my css - any help would be appreciated, thanks!

[Bug] Public Path not being fully added

I've tried to add this to our webpack build script, however even if I use our full path with publicPath, it's not working since it resolves to the root url path. Let me explain:

Adding the plugin:

new BugsnagSourceMapUploaderPlugin({
    apiKey: 'api-key-here',
    publicPath: 'http://example.com/some-path/',
    overwrite: true,
})

The files are uploaded successfully, however they have the http://example.com/ base path, and not the full http://example.com/some-path/.

I've taken a quick look on the source code and seems to be here:

url: resolve(
// ensure publicPath has a trailing slash
publicPath.replace(/[^/]$/, '$&/'),
source
).toString()

Quickly testing on Node CLI:

const url = require('url')

url.resolve('http://example.com/some-path/', '/main.js')
// 'http://example.com/main.js'

url.resolve('http://example.com/some-path/another-path/', '/main.js')
// 'http://example.com/main.js'

url.resolve('http://example.com/some-path/', 'main.js')
// 'http://example.com/some-path/main.js'

url.resolve('http://example.com/some-path/another-path/', 'main.js')
// 'http://example.com/some-path/another-path/main.js' 

It seems that the source variable have the / before the name. Perhaps removing the / before the file name or even adding a callback option as suggested on #8 (comment) may be an option.

By the way, we are using laravel-mix as webpack wrapper.

Plugin does not upload *.map file

I am not 100% sure this is bug or not. If it is not, sorry to post here.

Webpack generates about 100 chunks and file name is actually 4.js?v=8fddedf76030
I am also deleting source map files from server after source map files are uploaded to bugsnag server.

Generated chunks
4.js.map?v=8fddedf76030 558 KiB 4 [emitted] [big]
4.js?v=8fddedf76030

Webpack setup for source map
devtool: 'source-map',

Plugin configuration

  new BugsnagSourceMapUploaderPlugin({
        apiKey: BUGSNAG_API_KEY,
        appVersion: version,
        publicPath: '/dist',
        overwrite: true,
      }),

What Bugsnag uploads after Webpack generated sourcemap.
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "/dist/4.js?v=8fddedf76030"

And I can see uploaded file from setting -> sourcemap.

Query strings applied to source map names.

I'm using webpack 3.12 and I do codesplitting on my js into chunks and use query strings to version them e.g. page1.chunk.js?id=abcdef. The file is then saved as page1.chunk.js. Problem is, the query string is applied to the source map names page1.chunk.js.map?id=abcdef and that is the name used when uploading to Bugsnag, this results is Bugsnag not matching the file page1.chunk.js to the map page1.chunk.js.map?id=abcdef. This is my webpack config that generates chunks names

module.exports = {
  output: {
    chunkFilename: '[name].chunk.js?id=[chunkhash]'
  },
}

I've come across issue #8 and saw the proposal to have a config option to determine the minifiedUrl. Is it possible to have something similar for the sourceMap option like so

new BugsnagSourceMapUploaderPlugin({
  apiKey: 'YOUR_API_KEY',
  appVersion: '1.2.3',
  getSourceMap: (sourceMapName) => {
    // this will remove the query string from the sourcemap name
    return sourceMapName.replace(/\?id=.*/, '')
  }
})

This would enable me to get rid of the query string in the sourcemap name so that Bugsnag can match the file and the map correctly.


I've looked into source-map-uploader-plugin.js and seen that there a function used to strip query strings from sourcemap

const outputSourceMapLocation = stripQuery(compiler.outputFileSystem.join(outputPath, map))

// ...

// removes a querystring from a file path
const stripQuery = file => {
  const queryStringIdx = file.indexOf('?')
  if (queryStringIdx < 0) return file
  return file.substr(0, queryStringIdx)
}

But the query strings are still being included in the source map during upload.

Error 401 when uploading the source-map only with some files / uploads

Describe the bug

I was deploying the implementation of the source-map upload in our production build, when the deploy failed with this error:

[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/0-7e84539c28831fe607e7.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/1-cf1acf6cafb554718f1d.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/2-2b08f22fa36c994f75fa.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/3-f101a22be949833a71f4.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/4-2c0e6934e04006e67e0d.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/5-90c00338f30394396427.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/6-10660080fbcec74bda7d.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/7-c438222d7cf45f490e12.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/8-b6751746a819b4b756d7.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/cms/9-2ae8db8564fd8c9adb6d.js"
Error: HTTP status 401 received from upload API
    at /data/www/my_site/node_modules/bugsnag-sourcemaps/lib/request.js:41:21
    at ConcatStream.<anonymous> (/data/www/my_site/node_modules/bugsnag-sourcemaps/node_modules/concat-stream/index.js:37:43)
    at ConcatStream.emit (events.js:326:22)
    at ConcatStream.EventEmitter.emit (domain.js:548:15)
    at finishMaybe (/data/www/my_site/node_modules/bugsnag-sourcemaps/node_modules/readable-stream/lib/_stream_writable.js:624:14)
    at afterWrite (/data/www/my_site/node_modules/bugsnag-sourcemaps/node_modules/readable-stream/lib/_stream_writable.js:470:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  isRetryable: false
}


[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/0-bf973c8ec98d2c354e69.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/1-39bc5313ecd7d834e706.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/2-42ab8d74bf777cad2948.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/3-5fa84e8b0dd0bec05df5.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/4-4e41d7bb0b4a44d6e3ef.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/5-2cb9a658a641fde517e5.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/6-8dff268489e82c386243.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/7-83ca9c1eb0b701a2202f.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/8-1327d65833d914b96d16.js"
[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://mysite.com/build/node/node/9-ce094376488d6e41f6d0.js"

From what I read in the documentation, the error 401 means invalid apiKey, but if that's the case, why did it failed only with one specific file and not all of them?

Steps to reproduce

  1. Not sure

Environment

  • Node version: 14.14.0
  • yarn version: 1.22.10
  • Webpack version: 4.44.2

Example code snippet

module.exports = [
   ...stuff,
       plugins: [
        isProduction && new BugsnagSourceMapUploaderPlugin({
            apiKey: process.env.OUR_KEY,
            releaseStage: process.env.OUR_STAGE,
            overwrite: true,
        }),
    ],
]

`overwrite` not respected for css map files

It looks like when using the upload webpack plugin, the overwrite command is not respected for css map files. (js map files are overwritten as expected).

emittingError: Conflict (409) - duplicate source map file for */assets/app/common.82a452be015613a8991a.css version 02fdfce

Feature request: Allow to specify `minifiedUrl` directly

Hi team,

We are using Bugsnag in our React app built by webpack. In order to get more readable stacktrace, I'd like to upload source map when building it. However, it is deployed as a different file name from generated by webpack. (eg. app.js -> app.[digest].js)

Currently, minifiedUrl is automatically determined from publicUrl and file name, but I'd like to specify minifiedUrl directly with wildcards. For example:

const { BugsnagSourceMapUploaderPlugin } = require('webpack-bugsnag-plugins')

module.exports = {
  entry: './app.js',
  devtool: 'source-map',
  output: {
    path: __dirname,
    filename: './bundle.js',
    publicPath: 'https://your-app.xyz/assets/'
  },
  plugins: [].concat(
    // It's a good idea to only run this plugin when you're building a bundle
    // that will be released, rather than for every development build
    isDistEnv
      ? new BugsnagSourceMapUploaderPlugin({
          apiKey: 'YOUR_API_KEY',
          appVersion: '1.2.3',
          minifiedUrl: 'https://your-app.xyz/assets/bundle.*.js'
        })
      : []
  )
}

WDYT?

Throw an error if no source maps to upload

Description

if there is no source maps to upload, the plugin just sits there silently without doing anything.

Describe the solution you'd like

Would be beneficial if there was an error that would be thrown when there is nothing to upload. This would help troubleshooting a lot (in our case, no source maps were generated while I thought it was the plugin that fails). After all, the plugin is used to upload source maps so it should also expect to have something to upload.

Feature request: Allow to ignore uploading errors

Hi there,

When I run BugsnagSourceMapUploaderPlugin on Windows, sometimes I encountered ENOTEMPTY error.

[BugsnagSourceMapUploaderPlugin] uploading sourcemap for "https://www.ikyu.com/common/dist/chunks/31-df37450caf0ee52e3c02.js"
.\build-assets.bat : Error: ENOTEMPTY: directory not empty, rmdir 'C:\Users\appveyor\AppData\Local\Temp\1\bugsnag-sourcemapsm9vVAa'

This error occurs when removing not empty directories:
https://github.com/bugsnag/bugsnag-sourcemaps/blob/master/index.js#L345

The root cause of this error is Windows file system and there are no easy solutions.
isaacs/rimraf#72

In my opinion, failure of removing tmp directories is a minor issue. So, I want to ignore this error.

If this plugin provides some error handling option, I can ignore errors.

new BugsnagSourceMapUploaderPlugin {
  apiKey: '...',
  publicPath: '...',
  onError: (err, callback) => {
    if (err.code === 'ENOTEMPTY') {
      callback(); // ignore error
    } else {
      callback(err);
    }
  }
}

Modification may be something like this:

BugsnagSourceMapUploaderPlugin {
  constructor(options) {
...
+    this.onError = options.onError
  }
...
  apply(compiler) {
...
      parallel(sourceMaps.map(sm => cb => {
        console.log(`${LOG_PREFIX} uploading sourcemap for "${sm.url}"`)
        upload(this.getUploadOpts(sm), cb)
-      }), 10, callback)
+      }), 10, err => {
+        if (err && this.onError) {
+          this.onError(err, callback)
+        } else {
+         callback(err)
+        }
+      })
...
  }
}

What do you think?

Cannot get sourcemaps to work for uploaded files

I have no idea where to post this and I do apologize if this is not the place, but the docs are incredibly unclear as to which options you're supposed to use for what for the source map uploads. I'm trying to add the source map upload plugin to a webpack template

Basically, I have a setup running in dev behind an internal firewall. I've integrated the webpack sourcemap upload plugin and configured it like so:

new BugsnagSourceMapUploaderPlugin({
      apiKey: '*****',
      appVersion: appVersion,
      uploadSource: true
})

This correctly uploads them and I can see them in he bugsnag console. However, when an error comes in it does not match. The app versions are all correctly aligned. Now, the public path is configured relatively based on an index.html file like this:

    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

Great. The sourcemaps are uploaded and look like this in the console: /static/js/vendor.3f9cb3774b75d70c28a4.js

What configuration option am I missing here? Is this a matter of the original source files living behind the firewall? I thought that was the whole point of uploading the files? If this isn't the place to ask this, please direct me where I should go to try and figure this out.

Wildcards character in publicPath not working for uploading source map

The resolve function from url package doesn't support wildcard characters.

Problem explaining
Let's assume we have a project, that outputs scripts.js and scripts.js.map in the root dist folder. The code is served from a subdomain of example.com, e.g. app.example.com and the files would be available at https://app.example.com/scripts.js and https://app.example.com/scripts.js.map

Webpack config

  new BugsnagSourceMapUploaderPlugin({
    apiKey: 'YOUR_API_KEY',
    publicPath: 'https://*.example.com/',
  })

Expected
Source map files would be uploaded where url matches: https://*.example.com/scripts.js
Actual
The url that is being matched is https:///*.example.com/scripts.js (note the extra / before the wildcard).

Problem shooting
Turns out that the resolve function of the url package doesn't support * and hence resolves the URL to something unexpected. See source-map-uploader-plugin.js line 77

Changing publicPath in the webpack config produces following results:
publicPath: 'https:/*.example.com/' results https:/*.example.com/scripts.js
publicPath: 'https://*.example.com' results https:///scripts.js

Guess the publicPath: 'https:/*.example.com/' would work, since the wildcard in the result would then include the missing slash / in the protocol. However that would be a hack to circumvent the problem.

rush rebuild/build will return 1 instead of 0 although uploading source map successfully

Describe the bug

Rush build/rebuild command which will trigger webpack build to uploading source map, although uploading successfully but command return 1 instead of 0.
Run webpack command directly, everything is ok.

Steps to reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Environment

  • Node version: 12.16.1
  • NPM version: 6.13.4
  • Webpack version: 4

Example Repo

  • Create a minimal repository that can reproduce the issue
  • Link to it here:

Example code snippet

# (Insert code sample to reproduce the problem)
Error messages:
==[ SUCCESS WITH WARNINGS: 1 project ]=========================================

--[ WARNING: xxxxxxxx ]-------------------------[ 54.61 seconds ]--

<i> [BugsnagSourceMapUploaderPlugin] uploading sourcemap for "*/x"


Projects succeeded with warnings.

Next.js project Cannot determine "minifiedUrl" argument for bugsnag-sourcemaps

Hello :)
bugsnag requires the publicPath, but in nextjs generated project, the public path is always with chunkhash, but the file is under .next/bundle.

So when I upload the sourcemap under ./next/bundle, it wont work with the caught error in minified production code.

is there any other way to fix this issue? thanks!

website:

image

error in bugsnag

image

uploaded source map

image

Sourcemaps wildcard matching seems to be broken

It seems that Bugsnag dashboard is unable to load sourcemaps files for wildcard URLs. I use this configuration:

new BugsnagSourceMapUploaderPlugin({
  apiKey: process.env.BUGSNAG_CLIENT_API_KEY,
  overwrite: true,
  publicPath: "https://*.--hidden--.co/_next/"
}),

These are the results:
bugsnag-issue

Dashboard doesn't match source map file to the error. Any ideas?

publicPath field doesn't work for AWS Lambda + webpack + bugsnag

Tried all the combination of wildcards and file entries, the source map does get uploaded, but it is an incorrect one. Cause it does not trace back to the original source code and just shows the minified weback version instead.

My webpack config (in parts) is as follows:

new BugsnagSourceMapUploaderPlugin({
            apiKey: bugsnagApiKey,
            overwrite: true,
            publicPath: 'dist/email-notifications/src/'
          }),
devtool: 'source-map',
    output: {
      path: join(__dirname, '/dist/email-notifications/src/'),
      filename: 'index.js'
    },

My folder structure is as follows:

- email-notifications
   - src (has the source code on which webpack works)
       - index.js
       - other folders (with functions called from index.js)
   - dist
       - email-notifications
           - index.js
           - index.js.map

My lambda bundle consists of just the dist/email-notifications/index.js file

Not working with webpack 4

Hi it looks like the plugin isn't working with webpack 4.
There is a small warning about using .hooks, which can easily be correct by using compiler.hooks.afterEmit.tapAsync(...

However, the main issue I'm having is that I'm getting my chunks something like this: (so stats.chunks.length is 2)

[ 'vendor.css',
  'vendor.fc6c3b79.js',
  'vendor.css.map',
  'vendor.fc6c3b79.js.map' ],
[ 'main.css',
  'main.da7c09d0.js',
  'main.css.map',
  'main.da7c09d0.js.map' ]

And so in the chunkToSourceMapDescriptor it's only picking up the first *.css.map files and uploads them. I'm not sure if I need to change my webpack config or do we need to adapt the plugin. Any help is appreciated.

More flexible behavior if source map exists instead of error or overwrite

Description

Currently, there is an overwrite: boolean field that if false, will throw an error and quit the build, if true, it will overwrite the source map files.

Describe the solution you'd like
Overwrite handles 2 out of the 3 possible use cases I can think of. The third missing use case is a soft warning (without overwriting). My usecase which I don't think is uncommon is as follows:

  1. Make some changes to fix a bug
  2. Make a production build to see if it's fixed (the version has not been upped yet because we don't know what kind of release it will be until we do subsequent changes)
  3. Test the production build
  4. Make more changes
  5. Finally up the versions once we know what's changed for this release
  6. A production build where we do upload sourcemaps

Describe alternatives you've considered
Completely disabling the plugin manually. This doesn't give me the benefit of a warning that it didn't upload sourcemaps though.

Encoded URI for source URLs (Next.js)

This is a specific problem with Next.js but I'm wondering how many others might be affected by this.

Problem

When uploading source map URLs to Bugsnag, the URL uses characters that aren't encoded. For example, */_next/chunks/pages/posts/[id]/index-7bb752abed79eb3123b5.js. When this URL gets loaded in the browser, it tries to match against */_next/chunks/pages/posts/%5Bid%5D/index-7bb752abed79eb3123b5.js. The source map misses.

Fix

url: '' +
// ensure publicPath has a trailing slash
publicPath.replace(/[^/]$/, '$&/') +
// remove leading / or ./ from source
source.replace(/^\.?\//, '')

This url should use encodeURI so properly escape characters like [ so that URLs match.

Integration into Laravel Vue Application with Laravel Mix

Been reading on adding / uploading source maps for easier debugging JavaScript/Vue. That besides PHP debugging . So found your documentation on using the webpack plugin https://docs.bugsnag.com/build-integrations/webpack/ .

Not clear however on the integration into webpack.mix.js . Miss that at https://github.com/bugsnag/webpack-bugsnag-plugins and in documentation https://docs.bugsnag.com/platforms/php/laravel/ .

If we use this in webpack.mix.js:

const mix = require('laravel-mix')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { BugsnagBuildReporterPlugin } = require('webpack-bugsnag-plugins')

if (mix.inProduction()) {
  mix.webpackConfig({
    plugins: [
      new CleanWebpackPlugin({
        cleanStaleWebpackAssets: false,
        protectWebpackAssets: true,
        cleanOnceBeforeBuildPatterns: ['js/components/*'],
      }),
      new BugsnagBuildReporterPlugin({
        apiKey: 'api-key-here',
        publicPath: 'https://site.com/public',
        overwrite: true,
    }),
    
    ],

    output: {
      chunkFilename: 'js/components/[name].js?id=[contenthash]',
    },
  })
} else {
  mix.webpackConfig({
    output: {
      chunkFilename: 'js/components/[name].js',
    },
  });
}


mix.options({
    processCssUrls: false
});

mix.sass('resources/sass/editor.scss', 'public/css')
    .sass('resources/sass/login.scss', 'public/css')
    .sass('resources/sass/preview.scss', 'public/css')
    .sass('resources/sass/published.scss', 'public/css')
    .sass('resources/sass/dashboard.scss', 'public/css')
    .js('resources/js/editor.js', 'public/js')
    .js('resources/js/preview.js', 'public/js')
    .js('resources/js/published-vendor.js', 'public/js')
    .js('resources/js/published-utils.js', 'public/js')
    .js('resources/js/published.js', 'public/js')
    .js('resources/js/dashboard.js', 'public/js')
    .vue()

if (mix.inProduction()) {
    mix.version();
}
....
  1. What should normally be the publicPath here? Should it be https://site.com/public ? Or do I need to add a slash?
  2. What if staging and production both use inProduction , but different domains(staging.domain.com and domain.com)?
  3. Any recommended Laravel Mix template available?

NB Reading #11 some now as well, but not quite clear yet and would appreciate some feedback.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.