webpack.config.ts 26 KB

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