webpack.config.ts 25 KB

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