rspack.config.ts 23 KB

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