rspack.config.ts 24 KB

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