webpack.config.ts 26 KB

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