rspack.config.ts 23 KB

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