webpack.config.ts 26 KB

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