webpack.config.ts 27 KB

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