webpack.config.ts 27 KB

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