webpack.config.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /* eslint-env node */
  2. import {WebpackReactSourcemapsPlugin} from '@acemarke/react-prod-sourcemaps';
  3. import {RsdoctorWebpackPlugin} from '@rsdoctor/webpack-plugin';
  4. import browserslist from 'browserslist';
  5. import CompressionPlugin from 'compression-webpack-plugin';
  6. import CopyPlugin from 'copy-webpack-plugin';
  7. import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
  8. import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
  9. import lightningcss from 'lightningcss';
  10. import MiniCssExtractPlugin from 'mini-css-extract-plugin';
  11. import fs from 'node:fs';
  12. import path from 'node:path';
  13. import TerserPlugin from 'terser-webpack-plugin';
  14. import webpack from 'webpack';
  15. import type {Configuration as DevServerConfig} from 'webpack-dev-server';
  16. import FixStyleOnlyEntriesPlugin from 'webpack-remove-empty-scripts';
  17. import LastBuiltPlugin from './build-utils/last-built-plugin';
  18. import SentryInstrumentation from './build-utils/sentry-instrumentation';
  19. import babelConfig from './babel.config';
  20. import packageJson from './package.json';
  21. type MinimizerPluginOptions = {
  22. targets: lightningcss.TransformAttributeOptions['targets'];
  23. };
  24. /**
  25. * Merges the devServer config into the webpack config
  26. *
  27. * See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43232
  28. */
  29. interface Configuration extends webpack.Configuration {
  30. devServer?: DevServerConfig;
  31. }
  32. const {env} = process;
  33. // Environment configuration
  34. env.NODE_ENV = env.NODE_ENV ?? 'development';
  35. const IS_PRODUCTION = env.NODE_ENV === 'production';
  36. const IS_TEST = env.NODE_ENV === 'test' || !!env.TEST_SUITE;
  37. // This is used to stop rendering dynamic content for tests/snapshots
  38. // We want it in the case where we are running tests and it is in CI,
  39. // this should not happen in local
  40. const IS_CI = !!env.CI;
  41. // We intentionally build in production mode for acceptance tests, so we explicitly use an env var to
  42. // say that the bundle will be used in acceptance tests. This affects webpack plugins and components
  43. // with dynamic data that render differently statically in tests.
  44. //
  45. // Note, cannot assume it is an acceptance test if `IS_CI` is true, as our image builds has the
  46. // `CI` env var set.
  47. const IS_ACCEPTANCE_TEST = !!env.IS_ACCEPTANCE_TEST;
  48. const IS_DEPLOY_PREVIEW = !!env.NOW_GITHUB_DEPLOYMENT;
  49. const IS_UI_DEV_ONLY = !!env.SENTRY_UI_DEV_ONLY;
  50. const DEV_MODE = !(IS_PRODUCTION || IS_CI);
  51. const WEBPACK_MODE: Configuration['mode'] = IS_PRODUCTION ? 'production' : 'development';
  52. const CONTROL_SILO_PORT = env.SENTRY_CONTROL_SILO_PORT;
  53. // Sentry Developer Tool flags. These flags are used to enable / disable different developer tool
  54. // features in the Sentry UI.
  55. const USE_REACT_QUERY_DEVTOOL = !!env.USE_REACT_QUERY_DEVTOOL;
  56. // Enable react 18 concurrent mode
  57. const USE_REACT_CONCURRENT_MODE =
  58. (DEV_MODE || IS_ACCEPTANCE_TEST) && !env.DISABLE_REACT_CONCURRENT_MODE;
  59. // Environment variables that are used by other tooling and should
  60. // not be user configurable.
  61. //
  62. // Ports used by webpack dev server to proxy to backend and webpack
  63. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  64. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  65. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  66. const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
  67. // Used by sentry devserver runner to force using webpack-dev-server
  68. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  69. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  70. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  71. // User/tooling configurable environment variables
  72. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  73. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  74. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  75. const SHOULD_ADD_RSDOCTOR = Boolean(env.RSDOCTOR);
  76. // Deploy previews are built using vercel. We can check if we're in vercel's
  77. // build process by checking the existence of the PULL_REQUEST env var.
  78. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  79. branch: env.NOW_GITHUB_COMMIT_REF,
  80. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  81. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  82. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  83. };
  84. // When deploy previews are enabled always enable experimental SPA mode --
  85. // deploy previews are served standalone. Otherwise fallback to the environment
  86. // configuration.
  87. const SENTRY_EXPERIMENTAL_SPA =
  88. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  89. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  90. // is true. This is to make sure we can validate that the experimental SPA mode is
  91. // working properly.
  92. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  93. const CODECOV_TOKEN = env.CODECOV_TOKEN;
  94. // value should come back as either 'true' or 'false' or undefined
  95. const ENABLE_CODECOV_BA = env.CODECOV_ENABLE_BA === 'true' ?? false;
  96. // this is the path to the django "sentry" app, we output the webpack build here to `dist`
  97. // so that `django collectstatic` and so that we can serve the post-webpack bundles
  98. const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
  99. const distPath = env.SENTRY_STATIC_DIST_PATH || path.join(sentryDjangoAppPath, 'dist');
  100. const staticPrefix = path.join(__dirname, 'static');
  101. // Locale file extraction build step
  102. if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
  103. babelConfig.plugins?.push([
  104. 'module:babel-gettext-extractor',
  105. {
  106. fileName: 'build/javascript.po',
  107. baseDirectory: path.join(__dirname),
  108. functionNames: {
  109. gettext: ['msgid'],
  110. ngettext: ['msgid', 'msgid_plural', 'count'],
  111. gettextComponentTemplate: ['msgid'],
  112. t: ['msgid'],
  113. tn: ['msgid', 'msgid_plural', 'count'],
  114. tct: ['msgid'],
  115. },
  116. },
  117. ]);
  118. }
  119. // Locale compilation and optimizations.
  120. //
  121. // Locales are code-split from the app and vendor chunk into separate chunks
  122. // that will be loaded by layout.html depending on the users configured locale.
  123. //
  124. // Code splitting happens using the splitChunks plugin, configured under the
  125. // `optimization` key of the webpack module. We create chunk (cache) groups for
  126. // each of our supported locales and extract the PO files and moment.js locale
  127. // files into each chunk.
  128. //
  129. // A plugin is used to remove the locale chunks from the app entry's chunk
  130. // dependency list, so that our compiled bundle does not expect that *all*
  131. // locale chunks must be loaded
  132. const localeCatalogPath = path.join(
  133. __dirname,
  134. 'src',
  135. 'sentry',
  136. 'locale',
  137. 'catalogs.json'
  138. );
  139. type LocaleCatalog = {
  140. supported_locales: string[];
  141. };
  142. const localeCatalog: LocaleCatalog = JSON.parse(
  143. fs.readFileSync(localeCatalogPath, 'utf8')
  144. );
  145. // Translates a locale name to a language code.
  146. //
  147. // * po files are kept in a directory represented by the locale name [0]
  148. // * moment.js locales are stored as language code files
  149. //
  150. // [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
  151. const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
  152. const supportedLocales = localeCatalog.supported_locales;
  153. const supportedLanguages = supportedLocales.map(localeToLanguage);
  154. type CacheGroups = Exclude<
  155. NonNullable<Configuration['optimization']>['splitChunks'],
  156. false | undefined
  157. >['cacheGroups'];
  158. type CacheGroupTest = (
  159. module: webpack.Module,
  160. context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
  161. ) => boolean;
  162. // A mapping of chunk groups used for locale code splitting
  163. const cacheGroups: CacheGroups = {};
  164. supportedLocales
  165. // No need to split the english locale out as it will be completely empty and
  166. // is not included in the django layout.html.
  167. .filter(l => l !== 'en')
  168. .forEach(locale => {
  169. const language = localeToLanguage(locale);
  170. const group = `locale/${language}`;
  171. // List of module path tests to group into locale chunks
  172. const localeGroupTests = [
  173. new RegExp(`locale\\/${locale}\\/.*\\.po$`),
  174. new RegExp(`moment\\/locale\\/${language}\\.js$`),
  175. ];
  176. // module test taken from [0] and modified to support testing against
  177. // multiple expressions.
  178. //
  179. // [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
  180. const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
  181. localeGroupTests.some(pattern =>
  182. pattern.test(module?.nameForCondition?.() ?? '')
  183. ? true
  184. : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
  185. );
  186. // We are defining a chunk that combines the django language files with
  187. // moment's locales as if you want one, you will want the other.
  188. //
  189. // In the application code you will still need to import via their module
  190. // paths and not the chunk name
  191. cacheGroups[group] = {
  192. chunks: 'async',
  193. name: group,
  194. test: groupTest,
  195. enforce: true,
  196. };
  197. });
  198. const babelOptions = {...babelConfig, cacheDirectory: true};
  199. const babelLoaderConfig = {
  200. loader: 'babel-loader',
  201. options: babelOptions,
  202. };
  203. /**
  204. * Main Webpack config for Sentry React SPA.
  205. */
  206. const appConfig: Configuration = {
  207. mode: WEBPACK_MODE,
  208. entry: {
  209. /**
  210. * Main Sentry SPA
  211. *
  212. * The order here matters for `getsentry`
  213. */
  214. app: ['sentry/utils/statics-setup', 'sentry'],
  215. /**
  216. * Pipeline View for integrations
  217. */
  218. pipeline: ['sentry/utils/statics-setup', 'sentry/views/integrationPipeline'],
  219. /**
  220. * Legacy CSS Webpack appConfig for Django-powered views.
  221. * This generates a single "sentry.css" file that imports ALL component styles
  222. * for use on Django-powered pages.
  223. */
  224. sentry: 'less/sentry.less',
  225. },
  226. context: staticPrefix,
  227. module: {
  228. /**
  229. * XXX: Modifying the order/contents of these rules may break `getsentry`
  230. * Please remember to test it.
  231. */
  232. rules: [
  233. {
  234. test: /\.[tj]sx?$/,
  235. include: [staticPrefix],
  236. exclude: /(vendor|node_modules|dist)/,
  237. use: babelLoaderConfig,
  238. },
  239. {
  240. test: /\.po$/,
  241. use: {
  242. loader: 'po-catalog-loader',
  243. options: {
  244. referenceExtensions: ['.js', '.jsx', '.tsx'],
  245. domain: 'sentry',
  246. },
  247. },
  248. },
  249. {
  250. test: /\.pegjs/,
  251. use: {loader: 'pegjs-loader'},
  252. },
  253. {
  254. test: /\.css/,
  255. use: ['style-loader', 'css-loader'],
  256. },
  257. {
  258. test: /\.less$/,
  259. include: [staticPrefix],
  260. use: [
  261. {
  262. loader: MiniCssExtractPlugin.loader,
  263. options: {
  264. publicPath: 'auto',
  265. },
  266. },
  267. 'css-loader',
  268. 'less-loader',
  269. ],
  270. },
  271. {
  272. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  273. type: 'asset',
  274. },
  275. ],
  276. noParse: [
  277. // don't parse known, pre-built javascript files (improves webpack perf)
  278. /jed\/jed\.js/,
  279. /marked\/lib\/marked\.js/,
  280. /terser\/dist\/bundle\.min\.js/,
  281. ],
  282. },
  283. plugins: [
  284. /**
  285. * Adds build time measurement instrumentation, which will be reported back
  286. * to sentry
  287. */
  288. new SentryInstrumentation(),
  289. // Do not bundle moment's locale files as we will lazy load them using
  290. // dynamic imports in the application code
  291. new webpack.IgnorePlugin({
  292. contextRegExp: /moment$/,
  293. resourceRegExp: /^\.\/locale$/,
  294. }),
  295. /**
  296. * TODO(epurkhiser): Figure out if we still need these
  297. */
  298. new webpack.ProvidePlugin({
  299. process: 'process/browser',
  300. Buffer: ['buffer', 'Buffer'],
  301. }),
  302. /**
  303. * Extract CSS into separate files.
  304. */
  305. new MiniCssExtractPlugin({
  306. // We want the sentry css file to be unversioned for frontend-only deploys
  307. // We will cache using `Cache-Control` headers
  308. filename: 'entrypoints/[name].css',
  309. }),
  310. /**
  311. * Defines environment specific flags.
  312. */
  313. new webpack.DefinePlugin({
  314. 'process.env': {
  315. NODE_ENV: JSON.stringify(env.NODE_ENV),
  316. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  317. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  318. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  319. SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
  320. SENTRY_RELEASE_VERSION: JSON.stringify(SENTRY_RELEASE_VERSION),
  321. USE_REACT_QUERY_DEVTOOL: JSON.stringify(USE_REACT_QUERY_DEVTOOL),
  322. USE_REACT_CONCURRENT_MODE: JSON.stringify(USE_REACT_CONCURRENT_MODE),
  323. },
  324. }),
  325. /**
  326. * This removes empty js files for style only entries (e.g. sentry.less)
  327. */
  328. new FixStyleOnlyEntriesPlugin({verbose: false}),
  329. ...(SHOULD_FORK_TS
  330. ? [
  331. new ForkTsCheckerWebpackPlugin({
  332. typescript: {
  333. configFile: path.resolve(__dirname, './config/tsconfig.build.json'),
  334. configOverwrite: {
  335. compilerOptions: {incremental: true},
  336. },
  337. },
  338. devServer: false,
  339. // memorylimit is configured in package.json
  340. }),
  341. ]
  342. : []),
  343. ...(SHOULD_ADD_RSDOCTOR ? [new RsdoctorWebpackPlugin({})] : []),
  344. /**
  345. * Restrict translation files that are pulled in through
  346. * initializeLocale.tsx and through moment/locale/* to only those which we
  347. * create bundles for via locale/catalogs.json.
  348. *
  349. * Without this, webpack will still output all of the unused locale files despite
  350. * the application never loading any of them.
  351. */
  352. new webpack.ContextReplacementPlugin(
  353. /sentry-locale$/,
  354. path.join(__dirname, 'src', 'sentry', 'locale', path.sep),
  355. true,
  356. new RegExp(`(${supportedLocales.join('|')})/.*\\.po$`)
  357. ),
  358. new webpack.ContextReplacementPlugin(
  359. /moment\/locale/,
  360. new RegExp(`(${supportedLanguages.join('|')})\\.js$`)
  361. ),
  362. /**
  363. * Copies file logo-sentry.svg to the dist/entrypoints directory so that it can be accessed by
  364. * the backend
  365. */
  366. new CopyPlugin({
  367. patterns: [
  368. {
  369. from: path.join(staticPrefix, 'images/logo-sentry.svg'),
  370. to: 'entrypoints/logo-sentry.svg',
  371. toType: 'file',
  372. },
  373. // Add robots.txt when deploying in preview mode so public previews do
  374. // not get indexed by bots.
  375. ...(IS_DEPLOY_PREVIEW
  376. ? [
  377. {
  378. from: path.join(staticPrefix, 'robots-dev.txt'),
  379. to: 'robots.txt',
  380. toType: 'file' as const,
  381. },
  382. ]
  383. : []),
  384. ],
  385. }),
  386. WebpackReactSourcemapsPlugin({
  387. mode: IS_PRODUCTION ? 'strict' : undefined,
  388. debug: false,
  389. }),
  390. ],
  391. resolve: {
  392. alias: {
  393. sentry: path.join(staticPrefix, 'app'),
  394. 'sentry-images': path.join(staticPrefix, 'images'),
  395. 'sentry-logos': path.join(sentryDjangoAppPath, 'images', 'logos'),
  396. 'sentry-fonts': path.join(staticPrefix, 'fonts'),
  397. // Aliasing this for getsentry's build, otherwise `less/select2` will not be able
  398. // to be resolved
  399. less: path.join(staticPrefix, 'less'),
  400. 'sentry-test': path.join(__dirname, 'tests', 'js', 'sentry-test'),
  401. 'sentry-locale': path.join(__dirname, 'src', 'sentry', 'locale'),
  402. 'ios-device-list': path.join(
  403. __dirname,
  404. 'node_modules',
  405. 'ios-device-list',
  406. 'dist',
  407. 'ios-device-list.min.js'
  408. ),
  409. },
  410. fallback: {
  411. vm: false,
  412. stream: false,
  413. crypto: require.resolve('crypto-browserify'),
  414. // `yarn why` says this is only needed in dev deps
  415. string_decoder: false,
  416. // For framer motion v6, might be able to remove on v11
  417. 'process/browser': require.resolve('process/browser'),
  418. },
  419. modules: ['node_modules'],
  420. extensions: ['.jsx', '.js', '.json', '.ts', '.tsx', '.less'],
  421. symlinks: false,
  422. },
  423. output: {
  424. crossOriginLoading: 'anonymous',
  425. clean: true, // Clean the output directory before emit.
  426. path: distPath,
  427. publicPath: '',
  428. filename: 'entrypoints/[name].js',
  429. chunkFilename: 'chunks/[name].[contenthash].js',
  430. sourceMapFilename: 'sourcemaps/[name].[contenthash].js.map',
  431. assetModuleFilename: 'assets/[name].[contenthash][ext]',
  432. },
  433. optimization: {
  434. chunkIds: 'named',
  435. moduleIds: 'named',
  436. splitChunks: {
  437. // Only affect async chunks, otherwise webpack could potentially split our initial chunks
  438. // Which means the app will not load because we'd need these additional chunks to be loaded in our
  439. // django template.
  440. chunks: 'async',
  441. maxInitialRequests: 10, // (default: 30)
  442. maxAsyncRequests: 10, // (default: 30)
  443. cacheGroups,
  444. },
  445. minimizer: [
  446. new TerserPlugin({
  447. parallel: true,
  448. minify: TerserPlugin.esbuildMinify,
  449. }),
  450. new CssMinimizerPlugin<MinimizerPluginOptions>({
  451. parallel: true,
  452. minify: CssMinimizerPlugin.lightningCssMinify,
  453. minimizerOptions: {
  454. targets: lightningcss.browserslistToTargets(
  455. browserslist(packageJson.browserslist.production)
  456. ),
  457. },
  458. }),
  459. ],
  460. },
  461. devtool: IS_PRODUCTION ? 'source-map' : 'eval-cheap-module-source-map',
  462. };
  463. if (IS_TEST) {
  464. appConfig.resolve!.alias!['sentry-fixture'] = path.join(
  465. __dirname,
  466. 'fixtures',
  467. 'js-stubs'
  468. );
  469. }
  470. if (IS_ACCEPTANCE_TEST) {
  471. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  472. }
  473. // Dev only! Hot module reloading
  474. if (
  475. FORCE_WEBPACK_DEV_SERVER ||
  476. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  477. IS_UI_DEV_ONLY
  478. ) {
  479. if (SHOULD_HOT_MODULE_RELOAD) {
  480. // Hot reload react components on save
  481. // We include the library here as to not break docker/google cloud builds
  482. // since we do not install devDeps there.
  483. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  484. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  485. // TODO: figure out why defining output breaks hot reloading
  486. if (IS_UI_DEV_ONLY) {
  487. appConfig.output = {};
  488. }
  489. }
  490. appConfig.devServer = {
  491. headers: {
  492. 'Document-Policy': 'js-profiling',
  493. },
  494. // Cover the various environments we use (vercel, getsentry-dev, localhost)
  495. allowedHosts: [
  496. '.sentry.dev',
  497. '.dev.getsentry.net',
  498. '.localhost',
  499. '127.0.0.1',
  500. '.docker.internal',
  501. ],
  502. static: {
  503. directory: './src/sentry/static/sentry',
  504. watch: true,
  505. },
  506. host: SENTRY_WEBPACK_PROXY_HOST,
  507. // Don't reload on errors
  508. hot: 'only',
  509. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  510. devMiddleware: {
  511. stats: 'errors-only',
  512. },
  513. client: {
  514. overlay: false,
  515. },
  516. };
  517. if (!IS_UI_DEV_ONLY) {
  518. // This proxies to local backend server
  519. const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
  520. const relayAddress = 'http://127.0.0.1:7899';
  521. // If we're running siloed servers we also need to proxy
  522. // those requests to the right server.
  523. let controlSiloProxy = {};
  524. if (CONTROL_SILO_PORT) {
  525. // TODO(hybridcloud) We also need to use this URL pattern
  526. // list to select control/region when making API requests in non-proxied
  527. // environments (like production). We'll likely need a way to consolidate this
  528. // with the configuration api.Client uses.
  529. const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
  530. controlSiloProxy = {
  531. '/auth/**': controlSiloAddress,
  532. '/account/**': controlSiloAddress,
  533. '/api/0/users/**': controlSiloAddress,
  534. '/api/0/api-tokens/**': controlSiloAddress,
  535. '/api/0/sentry-apps/**': controlSiloAddress,
  536. '/api/0/organizations/*/audit-logs/**': controlSiloAddress,
  537. '/api/0/organizations/*/broadcasts/**': controlSiloAddress,
  538. '/api/0/organizations/*/integrations/**': controlSiloAddress,
  539. '/api/0/organizations/*/config/integrations/**': controlSiloAddress,
  540. '/api/0/organizations/*/sentry-apps/**': controlSiloAddress,
  541. '/api/0/organizations/*/sentry-app-installations/**': controlSiloAddress,
  542. '/api/0/api-authorizations/**': controlSiloAddress,
  543. '/api/0/api-applications/**': controlSiloAddress,
  544. '/api/0/doc-integrations/**': controlSiloAddress,
  545. '/api/0/assistant/**': controlSiloAddress,
  546. };
  547. }
  548. appConfig.devServer = {
  549. ...appConfig.devServer,
  550. static: {
  551. ...(appConfig.devServer.static as object),
  552. publicPath: '/_static/dist/sentry',
  553. },
  554. // syntax for matching is using https://www.npmjs.com/package/micromatch
  555. proxy: {
  556. ...controlSiloProxy,
  557. '/api/store/**': relayAddress,
  558. '/api/{1..9}*({0..9})/**': relayAddress,
  559. '/api/0/relays/outcomes/': relayAddress,
  560. '!/_static/dist/sentry/**': backendAddress,
  561. },
  562. };
  563. appConfig.output!.publicPath = '/_static/dist/sentry/';
  564. }
  565. }
  566. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  567. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  568. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  569. // to a development index.html -- thus, completely separating the frontend
  570. // from serving any pages through the backend.
  571. //
  572. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  573. //
  574. // Various sentry pages still rely on django to serve html views.
  575. if (IS_UI_DEV_ONLY) {
  576. // XXX: If you change this also change its sibiling in:
  577. // - static/index.ejs
  578. // - static/app/utils/extractSlug.tsx
  579. const KNOWN_DOMAINS =
  580. /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
  581. const extractSlug = (hostname: string) => {
  582. const match = hostname.match(KNOWN_DOMAINS);
  583. if (!match) {
  584. return null;
  585. }
  586. const [
  587. matchedExpression, // Expression includes optional leading `.`
  588. ] = match;
  589. const [slug] = hostname.replace(matchedExpression, '').split('.');
  590. return slug;
  591. };
  592. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  593. const certPath = path.join(__dirname, 'config');
  594. const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  595. ? {}
  596. : {
  597. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  598. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  599. };
  600. appConfig.devServer = {
  601. ...appConfig.devServer,
  602. compress: true,
  603. server: {
  604. type: 'https',
  605. options: httpsOptions,
  606. },
  607. headers: {
  608. 'Access-Control-Allow-Origin': '*',
  609. 'Access-Control-Allow-Credentials': 'true',
  610. 'Document-Policy': 'js-profiling',
  611. },
  612. static: {
  613. publicPath: '/_assets/',
  614. },
  615. proxy: [
  616. {
  617. context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
  618. target: 'https://sentry.io',
  619. secure: false,
  620. changeOrigin: true,
  621. headers: {
  622. Referer: 'https://sentry.io/',
  623. 'Document-Policy': 'js-profiling',
  624. origin: 'https://sentry.io',
  625. },
  626. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  627. router: ({hostname}) => {
  628. const orgSlug = extractSlug(hostname);
  629. return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
  630. },
  631. },
  632. {
  633. // Handle dev-ui region silo requests.
  634. // Normally regions act as subdomains, but doing so in dev-ui
  635. // would result in requests bypassing webpack proxy and being sent
  636. // directly to region servers. These requests would fail because of CORS.
  637. // Instead Client prefixes region requests with `/region/$name` which
  638. // we rewrite in the proxy.
  639. context: ['/region/'],
  640. target: 'https://us.sentry.io',
  641. secure: false,
  642. changeOrigin: true,
  643. headers: {
  644. Referer: 'https://sentry.io/',
  645. 'Document-Policy': 'js-profiling',
  646. origin: 'https://sentry.io',
  647. },
  648. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  649. pathRewrite: {
  650. '^/region/[^/]*': '',
  651. },
  652. router: req => {
  653. const regionPathPattern = /^\/region\/([^\/]+)/;
  654. const regionname = req.path.match(regionPathPattern);
  655. if (regionname) {
  656. return `https://${regionname[1]}.sentry.io`;
  657. }
  658. return 'https://sentry.io';
  659. },
  660. },
  661. ],
  662. historyApiFallback: {
  663. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  664. },
  665. };
  666. appConfig.optimization = {
  667. runtimeChunk: 'single',
  668. };
  669. }
  670. if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
  671. appConfig.output!.publicPath = '/_assets/';
  672. /**
  673. * Generate a index.html file used for running the app in pure client mode.
  674. * This is currently used for PR deploy previews, where only the frontend
  675. * is deployed.
  676. */
  677. const HtmlWebpackPlugin = require('html-webpack-plugin');
  678. appConfig.plugins?.push(
  679. new HtmlWebpackPlugin({
  680. // Local dev vs vercel slightly differs...
  681. ...(IS_UI_DEV_ONLY
  682. ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
  683. : {}),
  684. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
  685. template: path.resolve(staticPrefix, 'index.ejs'),
  686. mobile: true,
  687. excludeChunks: ['pipeline'],
  688. title: 'Sentry',
  689. window: {
  690. __SENTRY_DEV_UI: true,
  691. },
  692. })
  693. );
  694. }
  695. const minificationPlugins = [
  696. // This compression-webpack-plugin generates pre-compressed files
  697. // ending in .gz, to be picked up and served by our internal static media
  698. // server as well as nginx when paired with the gzip_static module.
  699. new CompressionPlugin({
  700. algorithm: 'gzip',
  701. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  702. }),
  703. ];
  704. if (IS_PRODUCTION) {
  705. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  706. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  707. }
  708. if (CODECOV_TOKEN && ENABLE_CODECOV_BA) {
  709. const {codecovWebpackPlugin} = require('@codecov/webpack-plugin');
  710. appConfig.plugins?.push(
  711. codecovWebpackPlugin({
  712. enableBundleAnalysis: true,
  713. bundleName: 'app-webpack-bundle',
  714. uploadToken: CODECOV_TOKEN,
  715. debug: true,
  716. })
  717. );
  718. }
  719. // Cache webpack builds
  720. if (env.WEBPACK_CACHE_PATH) {
  721. appConfig.cache = {
  722. type: 'filesystem',
  723. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  724. buildDependencies: {
  725. // This makes all dependencies of this file - build dependencies
  726. config: [__filename],
  727. // By default webpack and loaders are build dependencies
  728. },
  729. };
  730. }
  731. export default appConfig;