webpack.config.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. // Environment variables that are used by other tooling and should
  61. // not be user configurable.
  62. //
  63. // Ports used by webpack dev server to proxy to backend and webpack
  64. const SENTRY_BACKEND_PORT = env.SENTRY_BACKEND_PORT;
  65. const SENTRY_WEBPACK_PROXY_HOST = env.SENTRY_WEBPACK_PROXY_HOST;
  66. const SENTRY_WEBPACK_PROXY_PORT = env.SENTRY_WEBPACK_PROXY_PORT;
  67. const SENTRY_RELEASE_VERSION = env.SENTRY_RELEASE_VERSION;
  68. // Used by sentry devserver runner to force using webpack-dev-server
  69. const FORCE_WEBPACK_DEV_SERVER = !!env.FORCE_WEBPACK_DEV_SERVER;
  70. const HAS_WEBPACK_DEV_SERVER_CONFIG =
  71. !!SENTRY_BACKEND_PORT && !!SENTRY_WEBPACK_PROXY_PORT;
  72. // User/tooling configurable environment variables
  73. const NO_DEV_SERVER = !!env.NO_DEV_SERVER; // Do not run webpack dev server
  74. const SHOULD_FORK_TS = DEV_MODE && !env.NO_TS_FORK; // Do not run fork-ts plugin (or if not dev env)
  75. const SHOULD_HOT_MODULE_RELOAD = DEV_MODE && !!env.SENTRY_UI_HOT_RELOAD;
  76. const SHOULD_ADD_RSDOCTOR = Boolean(env.RSDOCTOR);
  77. // Deploy previews are built using vercel. We can check if we're in vercel's
  78. // build process by checking the existence of the PULL_REQUEST env var.
  79. const DEPLOY_PREVIEW_CONFIG = IS_DEPLOY_PREVIEW && {
  80. branch: env.NOW_GITHUB_COMMIT_REF,
  81. commitSha: env.NOW_GITHUB_COMMIT_SHA,
  82. githubOrg: env.NOW_GITHUB_COMMIT_ORG,
  83. githubRepo: env.NOW_GITHUB_COMMIT_REPO,
  84. };
  85. // When deploy previews are enabled always enable experimental SPA mode --
  86. // deploy previews are served standalone. Otherwise fallback to the environment
  87. // configuration.
  88. const SENTRY_EXPERIMENTAL_SPA =
  89. !DEPLOY_PREVIEW_CONFIG && !IS_UI_DEV_ONLY ? !!env.SENTRY_EXPERIMENTAL_SPA : true;
  90. // We should only read from the SENTRY_SPA_DSN env variable if SENTRY_EXPERIMENTAL_SPA
  91. // is true. This is to make sure we can validate that the experimental SPA mode is
  92. // working properly.
  93. const SENTRY_SPA_DSN = SENTRY_EXPERIMENTAL_SPA ? env.SENTRY_SPA_DSN : undefined;
  94. const CODECOV_TOKEN = env.CODECOV_TOKEN;
  95. // value should come back as either 'true' or 'false' or undefined
  96. const ENABLE_CODECOV_BA = env.CODECOV_ENABLE_BA === 'true' ?? false;
  97. // this is the path to the django "sentry" app, we output the webpack build here to `dist`
  98. // so that `django collectstatic` and so that we can serve the post-webpack bundles
  99. const sentryDjangoAppPath = path.join(__dirname, 'src/sentry/static/sentry');
  100. const distPath = path.join(sentryDjangoAppPath, 'dist');
  101. const staticPrefix = path.join(__dirname, 'static');
  102. // Locale file extraction build step
  103. if (env.SENTRY_EXTRACT_TRANSLATIONS === '1') {
  104. babelConfig.plugins?.push([
  105. 'module:babel-gettext-extractor',
  106. {
  107. fileName: 'build/javascript.po',
  108. baseDirectory: path.join(__dirname),
  109. functionNames: {
  110. gettext: ['msgid'],
  111. ngettext: ['msgid', 'msgid_plural', 'count'],
  112. gettextComponentTemplate: ['msgid'],
  113. t: ['msgid'],
  114. tn: ['msgid', 'msgid_plural', 'count'],
  115. tct: ['msgid'],
  116. },
  117. },
  118. ]);
  119. }
  120. // Locale compilation and optimizations.
  121. //
  122. // Locales are code-split from the app and vendor chunk into separate chunks
  123. // that will be loaded by layout.html depending on the users configured locale.
  124. //
  125. // Code splitting happens using the splitChunks plugin, configured under the
  126. // `optimization` key of the webpack module. We create chunk (cache) groups for
  127. // each of our supported locales and extract the PO files and moment.js locale
  128. // files into each chunk.
  129. //
  130. // A plugin is used to remove the locale chunks from the app entry's chunk
  131. // dependency list, so that our compiled bundle does not expect that *all*
  132. // locale chunks must be loaded
  133. const localeCatalogPath = path.join(
  134. __dirname,
  135. 'src',
  136. 'sentry',
  137. 'locale',
  138. 'catalogs.json'
  139. );
  140. type LocaleCatalog = {
  141. supported_locales: string[];
  142. };
  143. const localeCatalog: LocaleCatalog = JSON.parse(
  144. fs.readFileSync(localeCatalogPath, 'utf8')
  145. );
  146. // Translates a locale name to a language code.
  147. //
  148. // * po files are kept in a directory represented by the locale name [0]
  149. // * moment.js locales are stored as language code files
  150. //
  151. // [0] https://docs.djangoproject.com/en/2.1/topics/i18n/#term-locale-name
  152. const localeToLanguage = (locale: string) => locale.toLowerCase().replace('_', '-');
  153. const supportedLocales = localeCatalog.supported_locales;
  154. const supportedLanguages = supportedLocales.map(localeToLanguage);
  155. type CacheGroups = Exclude<
  156. NonNullable<Configuration['optimization']>['splitChunks'],
  157. false | undefined
  158. >['cacheGroups'];
  159. type CacheGroupTest = (
  160. module: webpack.Module,
  161. context: Parameters<webpack.optimize.SplitChunksPlugin['options']['getCacheGroups']>[1]
  162. ) => boolean;
  163. // A mapping of chunk groups used for locale code splitting
  164. const cacheGroups: CacheGroups = {};
  165. supportedLocales
  166. // No need to split the english locale out as it will be completely empty and
  167. // is not included in the django layout.html.
  168. .filter(l => l !== 'en')
  169. .forEach(locale => {
  170. const language = localeToLanguage(locale);
  171. const group = `locale/${language}`;
  172. // List of module path tests to group into locale chunks
  173. const localeGroupTests = [
  174. new RegExp(`locale\\/${locale}\\/.*\\.po$`),
  175. new RegExp(`moment\\/locale\\/${language}\\.js$`),
  176. ];
  177. // module test taken from [0] and modified to support testing against
  178. // multiple expressions.
  179. //
  180. // [0] https://github.com/webpack/webpack/blob/7a6a71f1e9349f86833de12a673805621f0fc6f6/lib/optimize/SplitChunksPlugin.js#L309-L320
  181. const groupTest: CacheGroupTest = (module, {chunkGraph}) =>
  182. localeGroupTests.some(pattern =>
  183. pattern.test(module?.nameForCondition?.() ?? '')
  184. ? true
  185. : chunkGraph.getModuleChunks(module).some(c => c.name && pattern.test(c.name))
  186. );
  187. // We are defining a chunk that combines the django language files with
  188. // moment's locales as if you want one, you will want the other.
  189. //
  190. // In the application code you will still need to import via their module
  191. // paths and not the chunk name
  192. cacheGroups[group] = {
  193. chunks: 'async',
  194. name: group,
  195. test: groupTest,
  196. enforce: true,
  197. };
  198. });
  199. const babelOptions = {...babelConfig, cacheDirectory: true};
  200. const babelLoaderConfig = {
  201. loader: 'babel-loader',
  202. options: babelOptions,
  203. };
  204. /**
  205. * Main Webpack config for Sentry React SPA.
  206. */
  207. const appConfig: Configuration = {
  208. mode: WEBPACK_MODE,
  209. entry: {
  210. /**
  211. * Main Sentry SPA
  212. *
  213. * The order here matters for `getsentry`
  214. */
  215. app: ['sentry/utils/statics-setup', 'sentry'],
  216. /**
  217. * Pipeline View for integrations
  218. */
  219. pipeline: ['sentry/utils/statics-setup', 'sentry/views/integrationPipeline'],
  220. /**
  221. * Legacy CSS Webpack appConfig for Django-powered views.
  222. * This generates a single "sentry.css" file that imports ALL component styles
  223. * for use on Django-powered pages.
  224. */
  225. sentry: 'less/sentry.less',
  226. },
  227. context: staticPrefix,
  228. module: {
  229. /**
  230. * XXX: Modifying the order/contents of these rules may break `getsentry`
  231. * Please remember to test it.
  232. */
  233. rules: [
  234. {
  235. test: /\.[tj]sx?$/,
  236. include: [staticPrefix],
  237. exclude: /(vendor|node_modules|dist)/,
  238. use: babelLoaderConfig,
  239. },
  240. {
  241. test: /\.po$/,
  242. use: {
  243. loader: 'po-catalog-loader',
  244. options: {
  245. referenceExtensions: ['.js', '.tsx'],
  246. domain: 'sentry',
  247. },
  248. },
  249. },
  250. {
  251. test: /\.pegjs/,
  252. use: {loader: 'pegjs-loader'},
  253. },
  254. {
  255. test: /\.css/,
  256. use: ['style-loader', 'css-loader'],
  257. },
  258. {
  259. test: /\.less$/,
  260. include: [staticPrefix],
  261. use: [
  262. {
  263. loader: MiniCssExtractPlugin.loader,
  264. options: {
  265. publicPath: 'auto',
  266. },
  267. },
  268. 'css-loader',
  269. 'less-loader',
  270. ],
  271. },
  272. {
  273. test: /\.(woff|woff2|ttf|eot|svg|png|gif|ico|jpg|mp4)($|\?)/,
  274. type: 'asset',
  275. },
  276. ],
  277. noParse: [
  278. // don't parse known, pre-built javascript files (improves webpack perf)
  279. /jed\/jed\.js/,
  280. /marked\/lib\/marked\.js/,
  281. /terser\/dist\/bundle\.min\.js/,
  282. ],
  283. },
  284. plugins: [
  285. /**
  286. * Adds build time measurement instrumentation, which will be reported back
  287. * to sentry
  288. */
  289. new SentryInstrumentation(),
  290. // Do not bundle moment's locale files as we will lazy load them using
  291. // dynamic imports in the application code
  292. new webpack.IgnorePlugin({
  293. contextRegExp: /moment$/,
  294. resourceRegExp: /^\.\/locale$/,
  295. }),
  296. /**
  297. * TODO(epurkhiser): Figure out if we still need these
  298. */
  299. new webpack.ProvidePlugin({
  300. process: 'process/browser',
  301. Buffer: ['buffer', 'Buffer'],
  302. }),
  303. /**
  304. * Extract CSS into separate files.
  305. */
  306. new MiniCssExtractPlugin({
  307. // We want the sentry css file to be unversioned for frontend-only deploys
  308. // We will cache using `Cache-Control` headers
  309. filename: 'entrypoints/[name].css',
  310. }),
  311. /**
  312. * Defines environment specific flags.
  313. */
  314. new webpack.DefinePlugin({
  315. 'process.env': {
  316. NODE_ENV: JSON.stringify(env.NODE_ENV),
  317. IS_ACCEPTANCE_TEST: JSON.stringify(IS_ACCEPTANCE_TEST),
  318. DEPLOY_PREVIEW_CONFIG: JSON.stringify(DEPLOY_PREVIEW_CONFIG),
  319. EXPERIMENTAL_SPA: JSON.stringify(SENTRY_EXPERIMENTAL_SPA),
  320. SPA_DSN: JSON.stringify(SENTRY_SPA_DSN),
  321. SENTRY_RELEASE_VERSION: JSON.stringify(SENTRY_RELEASE_VERSION),
  322. USE_REACT_QUERY_DEVTOOL: JSON.stringify(USE_REACT_QUERY_DEVTOOL),
  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. // Node crypto is imported in @sentry-internal/global-search but not used here
  414. crypto: false,
  415. // `yarn why` says this is only needed in dev deps
  416. string_decoder: false,
  417. // For framer motion v6, might be able to remove on v11
  418. 'process/browser': require.resolve('process/browser'),
  419. },
  420. // Might be an issue if changing file extensions during development
  421. cache: true,
  422. // Prefers local modules over node_modules
  423. preferAbsolute: true,
  424. modules: ['node_modules'],
  425. extensions: ['.js', '.tsx', '.ts', '.json', '.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. 'tests',
  472. 'js',
  473. 'fixtures'
  474. );
  475. }
  476. if (IS_ACCEPTANCE_TEST) {
  477. appConfig.plugins?.push(new LastBuiltPlugin({basePath: __dirname}));
  478. }
  479. // Dev only! Hot module reloading
  480. if (
  481. FORCE_WEBPACK_DEV_SERVER ||
  482. (HAS_WEBPACK_DEV_SERVER_CONFIG && !NO_DEV_SERVER) ||
  483. IS_UI_DEV_ONLY
  484. ) {
  485. if (SHOULD_HOT_MODULE_RELOAD) {
  486. // Hot reload react components on save
  487. // We include the library here as to not break docker/google cloud builds
  488. // since we do not install devDeps there.
  489. const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
  490. appConfig.plugins?.push(new ReactRefreshWebpackPlugin());
  491. // TODO: figure out why defining output breaks hot reloading
  492. if (IS_UI_DEV_ONLY) {
  493. appConfig.output = {};
  494. }
  495. }
  496. appConfig.devServer = {
  497. headers: {
  498. 'Document-Policy': 'js-profiling',
  499. },
  500. // Cover the various environments we use (vercel, getsentry-dev, localhost)
  501. allowedHosts: [
  502. '.sentry.dev',
  503. '.dev.getsentry.net',
  504. '.localhost',
  505. '127.0.0.1',
  506. '.docker.internal',
  507. ],
  508. static: {
  509. directory: './src/sentry/static/sentry',
  510. watch: true,
  511. },
  512. host: SENTRY_WEBPACK_PROXY_HOST,
  513. // Don't reload on errors
  514. hot: 'only',
  515. port: Number(SENTRY_WEBPACK_PROXY_PORT),
  516. devMiddleware: {
  517. stats: 'errors-only',
  518. },
  519. client: {
  520. overlay: false,
  521. },
  522. };
  523. if (!IS_UI_DEV_ONLY) {
  524. // This proxies to local backend server
  525. const backendAddress = `http://127.0.0.1:${SENTRY_BACKEND_PORT}/`;
  526. const relayAddress = 'http://127.0.0.1:7899';
  527. // If we're running siloed servers we also need to proxy
  528. // those requests to the right server.
  529. let controlSiloProxy: ProxyConfigArray = [];
  530. if (CONTROL_SILO_PORT) {
  531. // TODO(hybridcloud) We also need to use this URL pattern
  532. // list to select control/region when making API requests in non-proxied
  533. // environments (like production). We'll likely need a way to consolidate this
  534. // with the configuration api.Client uses.
  535. const controlSiloAddress = `http://127.0.0.1:${CONTROL_SILO_PORT}`;
  536. controlSiloProxy = [
  537. {
  538. context: [
  539. '/auth/**',
  540. '/account/**',
  541. '/api/0/users/**',
  542. '/api/0/api-tokens/**',
  543. '/api/0/sentry-apps/**',
  544. '/api/0/organizations/*/audit-logs/**',
  545. '/api/0/organizations/*/broadcasts/**',
  546. '/api/0/organizations/*/integrations/**',
  547. '/api/0/organizations/*/config/integrations/**',
  548. '/api/0/organizations/*/sentry-apps/**',
  549. '/api/0/organizations/*/sentry-app-installations/**',
  550. '/api/0/api-authorizations/**',
  551. '/api/0/api-applications/**',
  552. '/api/0/doc-integrations/**',
  553. '/api/0/assistant/**',
  554. ],
  555. target: controlSiloAddress,
  556. },
  557. ];
  558. }
  559. appConfig.devServer = {
  560. ...appConfig.devServer,
  561. static: {
  562. ...(appConfig.devServer.static as Static),
  563. publicPath: '/_static/dist/sentry',
  564. },
  565. // syntax for matching is using https://www.npmjs.com/package/micromatch
  566. proxy: [
  567. ...controlSiloProxy,
  568. {
  569. context: [
  570. '/api/store/**',
  571. '/api/{1..9}*({0..9})/**',
  572. '/api/0/relays/outcomes/**',
  573. ],
  574. target: relayAddress,
  575. },
  576. {
  577. context: ['!/_static/dist/sentry/**'],
  578. target: backendAddress,
  579. },
  580. ],
  581. };
  582. appConfig.output!.publicPath = '/_static/dist/sentry/';
  583. }
  584. }
  585. // XXX(epurkhiser): Sentry (development) can be run in an experimental
  586. // pure-SPA mode, where ONLY /api* requests are proxied directly to the API
  587. // backend (in this case, sentry.io), otherwise ALL requests are rewritten
  588. // to a development index.html -- thus, completely separating the frontend
  589. // from serving any pages through the backend.
  590. //
  591. // THIS IS EXPERIMENTAL and has limitations (e.g. you can't use SSO)
  592. //
  593. // Various sentry pages still rely on django to serve html views.
  594. if (IS_UI_DEV_ONLY) {
  595. // XXX: If you change this also change its sibiling in:
  596. // - static/index.ejs
  597. // - static/app/utils/extractSlug.tsx
  598. const KNOWN_DOMAINS =
  599. /(?:\.?)((?:localhost|dev\.getsentry\.net|sentry\.dev)(?:\:\d*)?)$/;
  600. const extractSlug = (hostname: string) => {
  601. const match = hostname.match(KNOWN_DOMAINS);
  602. if (!match) {
  603. return null;
  604. }
  605. const [
  606. matchedExpression, // Expression includes optional leading `.`
  607. ] = match;
  608. const [slug] = hostname.replace(matchedExpression, '').split('.');
  609. return slug;
  610. };
  611. // Try and load certificates from mkcert if available. Use $ yarn mkcert-localhost
  612. const certPath = path.join(__dirname, 'config');
  613. const httpsOptions = !fs.existsSync(path.join(certPath, 'localhost.pem'))
  614. ? {}
  615. : {
  616. key: fs.readFileSync(path.join(certPath, 'localhost-key.pem')),
  617. cert: fs.readFileSync(path.join(certPath, 'localhost.pem')),
  618. };
  619. appConfig.devServer = {
  620. ...appConfig.devServer,
  621. compress: true,
  622. server: {
  623. type: 'https',
  624. options: httpsOptions,
  625. },
  626. headers: {
  627. 'Access-Control-Allow-Origin': '*',
  628. 'Access-Control-Allow-Credentials': 'true',
  629. 'Document-Policy': 'js-profiling',
  630. },
  631. static: {
  632. publicPath: '/_assets/',
  633. },
  634. proxy: [
  635. {
  636. context: ['/api/', '/avatar/', '/organization-avatar/', '/extensions/'],
  637. target: 'https://sentry.io',
  638. secure: false,
  639. changeOrigin: true,
  640. headers: {
  641. Referer: 'https://sentry.io/',
  642. 'Document-Policy': 'js-profiling',
  643. origin: 'https://sentry.io',
  644. },
  645. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  646. router: ({hostname}) => {
  647. const orgSlug = extractSlug(hostname);
  648. return orgSlug ? `https://${orgSlug}.sentry.io` : 'https://sentry.io';
  649. },
  650. },
  651. {
  652. // Handle dev-ui region silo requests.
  653. // Normally regions act as subdomains, but doing so in dev-ui
  654. // would result in requests bypassing webpack proxy and being sent
  655. // directly to region servers. These requests would fail because of CORS.
  656. // Instead Client prefixes region requests with `/region/$name` which
  657. // we rewrite in the proxy.
  658. context: ['/region/'],
  659. target: 'https://us.sentry.io',
  660. secure: false,
  661. changeOrigin: true,
  662. headers: {
  663. Referer: 'https://sentry.io/',
  664. 'Document-Policy': 'js-profiling',
  665. origin: 'https://sentry.io',
  666. },
  667. cookieDomainRewrite: {'.sentry.io': 'localhost'},
  668. pathRewrite: {
  669. '^/region/[^/]*': '',
  670. },
  671. router: req => {
  672. const regionPathPattern = /^\/region\/([^\/]+)/;
  673. const regionname = req.path.match(regionPathPattern);
  674. if (regionname) {
  675. return `https://${regionname[1]}.sentry.io`;
  676. }
  677. return 'https://sentry.io';
  678. },
  679. },
  680. ],
  681. historyApiFallback: {
  682. rewrites: [{from: /^\/.*$/, to: '/_assets/index.html'}],
  683. },
  684. };
  685. appConfig.optimization = {
  686. runtimeChunk: 'single',
  687. };
  688. }
  689. if (IS_UI_DEV_ONLY || SENTRY_EXPERIMENTAL_SPA) {
  690. appConfig.output!.publicPath = '/_assets/';
  691. /**
  692. * Generate a index.html file used for running the app in pure client mode.
  693. * This is currently used for PR deploy previews, where only the frontend
  694. * is deployed.
  695. */
  696. const HtmlWebpackPlugin = require('html-webpack-plugin');
  697. appConfig.plugins?.push(
  698. new HtmlWebpackPlugin({
  699. // Local dev vs vercel slightly differs...
  700. ...(IS_UI_DEV_ONLY
  701. ? {devServer: `https://127.0.0.1:${SENTRY_WEBPACK_PROXY_PORT}`}
  702. : {}),
  703. favicon: path.resolve(sentryDjangoAppPath, 'images', 'favicon_dev.png'),
  704. template: path.resolve(staticPrefix, 'index.ejs'),
  705. mobile: true,
  706. excludeChunks: ['pipeline'],
  707. title: 'Sentry',
  708. window: {
  709. __SENTRY_DEV_UI: true,
  710. },
  711. })
  712. );
  713. }
  714. const minificationPlugins = [
  715. // This compression-webpack-plugin generates pre-compressed files
  716. // ending in .gz, to be picked up and served by our internal static media
  717. // server as well as nginx when paired with the gzip_static module.
  718. new CompressionPlugin({
  719. algorithm: 'gzip',
  720. test: /\.(js|map|css|svg|html|txt|ico|eot|ttf)$/,
  721. }),
  722. ];
  723. if (IS_PRODUCTION) {
  724. // NOTE: can't do plugins.push(Array) because webpack/webpack#2217
  725. minificationPlugins.forEach(plugin => appConfig.plugins?.push(plugin));
  726. }
  727. if (CODECOV_TOKEN && ENABLE_CODECOV_BA) {
  728. const {codecovWebpackPlugin} = require('@codecov/webpack-plugin');
  729. // defaulting to an empty string which in turn will fallback to env var or
  730. // determine merge commit sha from git
  731. const GH_COMMIT_SHA = env.GH_COMMIT_SHA ?? '';
  732. appConfig.plugins?.push(
  733. codecovWebpackPlugin({
  734. enableBundleAnalysis: true,
  735. bundleName: 'app-webpack-bundle',
  736. uploadToken: CODECOV_TOKEN,
  737. debug: true,
  738. uploadOverrides: {
  739. sha: GH_COMMIT_SHA,
  740. },
  741. })
  742. );
  743. }
  744. // Cache webpack builds
  745. if (env.WEBPACK_CACHE_PATH) {
  746. appConfig.cache = {
  747. type: 'filesystem',
  748. cacheLocation: path.resolve(__dirname, env.WEBPACK_CACHE_PATH),
  749. buildDependencies: {
  750. // This makes all dependencies of this file - build dependencies
  751. config: [__filename],
  752. // By default webpack and loaders are build dependencies
  753. },
  754. };
  755. }
  756. export default appConfig;