The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Make metabase/router side-effect free (#78882)
Romeo Van Snick55ab9b7e38fe
diff --git a/frontend/build/shared/rspack/side-effect-free-modules.js b/frontend/build/shared/rspack/side-effect-free-modules.jsnew file mode 100644index 00000000000..fd12696532e--- /dev/null+++ b/frontend/build/shared/rspack/side-effect-free-modules.js@@ -0,0 +1,36 @@+/* eslint-env node */++const path = require("path");++const REPO_ROOT = path.resolve(__dirname, "../../../..");++/**+ * Source directories that are free of import-time side effects: importing a file+ * from one of them and using none of its exports is guaranteed to be observable+ * only through those exports. Nothing here may contain a bare `import "./x"`, a+ * CSS or asset import, or a top-level call with observable effects. Pure top-level+ * calls are fine, and the module relies on them (`createContext`, `new Set`).+ *+ * Rspack assumes every module may have side effects unless told otherwise, so+ * without this it cannot shake a barrel: a file importing only `useLocation` from+ * `metabase/router` pulls in every module the barrel re-exports.+ *+ * Adding a directory here is a promise the bundler cannot verify. A violation+ * fails silently, in production only, by dropping code that was meant to run, so+ * `frontend/lint/tests/side-effect-free-modules.unit.spec.js` guards the+ * mechanically detectable half of the contract.+ *+ * Only applies to production builds, where `optimization.sideEffects` is on.+ */+const SIDE_EFFECT_FREE_PATHS = [+ // Trailing separator: rspack prefix-matches `include`, so a bare directory path+ // would also claim a sibling like `router-utils.ts` or a future `router-v8/`.+ path.join(REPO_ROOT, "frontend/src/metabase/router") + path.sep,+];++const SIDE_EFFECT_FREE_RULE = {+ include: SIDE_EFFECT_FREE_PATHS,+ sideEffects: false,+};++module.exports = { SIDE_EFFECT_FREE_PATHS, SIDE_EFFECT_FREE_RULE };diff --git a/frontend/lint/tests/side-effect-free-modules.unit.spec.js b/frontend/lint/tests/side-effect-free-modules.unit.spec.jsnew file mode 100644index 00000000000..678004442f3--- /dev/null+++ b/frontend/lint/tests/side-effect-free-modules.unit.spec.js@@ -0,0 +1,50 @@+import fs from "fs";+import path from "path";++import { SIDE_EFFECT_FREE_PATHS } from "../../build/shared/rspack/side-effect-free-modules";++// A directory in SIDE_EFFECT_FREE_PATHS promises rspack that importing any file+// in it, and using none of its exports, has no observable effect. Rspack cannot+// verify that. When the promise breaks, production silently drops code that was+// meant to run, while dev and jest keep working, and no size budget catches it+// because dropping more is never a size failure.+//+// The half of the contract that is mechanically detectable is import-time effects,+// which is what this covers. Whether a top-level call is pure still needs a human.++const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];++function sourceFilesIn(dir) {+ return fs+ .readdirSync(dir, { withFileTypes: true })+ .flatMap((entry) => {+ const entryPath = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ return sourceFilesIn(entryPath);+ }+ return SOURCE_EXTENSIONS.includes(path.extname(entry.name))+ ? [entryPath]+ : [];+ })+ .filter((file) => !file.includes(".unit.spec."));+}++// `import "./x"` and `require("./x")`, which exist only for their side effects.+const BARE_IMPORT =+ /^\s*(?:import\s+["'][^"']+["']|require\(["'][^"']+["']\))/m;+// Assets pulled in for their effect on the page rather than for a binding.+const ASSET_IMPORT = /^\s*import\s+[^;]*["'][^"']+\.(?:css|svg|png|jpe?g)["']/m;++describe.each(SIDE_EFFECT_FREE_PATHS)("side-effect-free %s", (dir) => {+ const files = sourceFilesIn(dir);++ it("has source files to check", () => {+ expect(files.length).toBeGreaterThan(0);+ });++ it.each(files)("%s has no import-time side effects", (file) => {+ const source = fs.readFileSync(file, "utf8");+ expect(BARE_IMPORT.test(source)).toBe(false);+ expect(ASSET_IMPORT.test(source)).toBe(false);+ });+});diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.jsindex 0d68f04539a..b824b6d9777 100644--- a/frontend/src/metabase/app.js+++ b/frontend/src/metabase/app.js@@ -37,8 +37,7 @@ import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-eimport { MetabotProvider } from "metabase/metabot/context";import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";import { MetabaseReduxProvider } from "metabase/redux";-import { LOCATION_CHANGE } from "metabase/router";-import { createV7Navigator } from "metabase/router/v7/navigator";+import { LOCATION_CHANGE, createV7Navigator } from "metabase/router";import { getUserId } from "metabase/selectors/user";import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";import { PortalContainer } from "metabase/ui";diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsxindex 24575c0ea0a..0c08250d706 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx@@ -9,8 +9,7 @@ import {setupTableEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { Route } from "metabase/router";-import { RouterProviderV7Memory } from "metabase/router/v7/RouterProviderV7";+import { Route, RouterProviderV7Memory } from "metabase/router";import {createMockCard,createMockCollection,diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex 68d5fc6395e..dea47803529 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -15,8 +15,17 @@ export * from "./use-router";export * from "./use-search-params";export * from "./with-route-props";export { getRawBrowserHistory } from "./v7/blocking-history";-export { queryToSearch, searchToQuery } from "./v7/location";+export { queryToSearch, searchToQuery, toV3Location } from "./v7/location";export {createLocationMirror,type LocationMirror,} from "./v7/location-mirror";+export { createV7Navigator, toNavigateArgs } from "./v7/navigator";+// The memory-history engine is test-only. It reaches the barrel rather than a+// deep import because `sideEffects: false` lets rspack drop it from the app+// bundles, where nothing references it.+export {+ createMemoryTestHistory,+ type MemoryTestHistory,+ RouterProviderV7Memory,+} from "./v7/RouterProviderV7";diff --git a/frontend/src/metabase/visualizations/lib/open-url.ts b/frontend/src/metabase/visualizations/lib/open-url.tsindex 9999bad42c7..61242831031 100644--- a/frontend/src/metabase/visualizations/lib/open-url.ts+++ b/frontend/src/metabase/visualizations/lib/open-url.ts@@ -1,14 +1,11 @@import { handleLinkSdkPlugin } from "embedding-sdk-shared/lib/sdk-global-plugins";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";-import type {- LocationDescriptor,- LocationDescriptorObject,+import {+ type LocationDescriptor,+ type LocationDescriptorObject,+ queryToSearch,+ searchToQuery,} from "metabase/router";-// Imported from the module rather than the `metabase/router` barrel on purpose.-// This file is reachable from the static-viz entry, which runs inside GraalVM,-// and the barrel pulls react-router and the redux router middleware in with it:-// ~1MB on a bundle with a 3.5MB budget. `v7/location` has only type imports.-import { queryToSearch, searchToQuery } from "metabase/router/v7/location";import {clickLink,getPathnameWithoutSubPath,diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex dbaa503f064..7087385bf46 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -45,20 +45,16 @@ import {type Action,type History,type LocationDescriptor,- Route,- createLocationMirror,- routerMiddleware,-} from "metabase/router";-import {type MemoryTestHistory,+ Route,RouterProviderV7Memory,+ createLocationMirror,createMemoryTestHistory,-} from "metabase/router/v7/RouterProviderV7";-import { toV3Location } from "metabase/router/v7/location";-import {createV7Navigator,+ routerMiddleware,toNavigateArgs,-} from "metabase/router/v7/navigator";+ toV3Location,+} from "metabase/router";import { getMetabaseCssVariables } from "metabase/styled-components/theme/css-variables";import type { MantineThemeOverride } from "metabase/ui";import { PortalContainer, ThemeProvider, useMantineTheme } from "metabase/ui";diff --git a/rspack.embedding-sdk-bundle.config.js b/rspack.embedding-sdk-bundle.config.jsindex 148401edef0..954abd6e513 100644--- a/rspack.embedding-sdk-bundle.config.js+++ b/rspack.embedding-sdk-bundle.config.js@@ -25,6 +25,9 @@ const {} = require("./frontend/build/embedding-sdk/rspack/shared");const { BABEL_CONFIG } = require("./frontend/build/shared/rspack/babel-config");const { CSS_CONFIG } = require("./frontend/build/shared/rspack/css-config");+const {+ SIDE_EFFECT_FREE_RULE,+} = require("./frontend/build/shared/rspack/side-effect-free-modules");const {EXTERNAL_DEPENDENCIES,} = require("./frontend/build/embedding-sdk/constants/external-dependencies");@@ -111,6 +114,7 @@ const config = {module: {rules: [+ SIDE_EFFECT_FREE_RULE,{test: /\.(tsx?|jsx?)$/,exclude: /node_modules|cljs/,diff --git a/rspack.main.config.js b/rspack.main.config.jsindex dd254afb2ab..f08787c009b 100644--- a/rspack.main.config.js+++ b/rspack.main.config.js@@ -30,6 +30,9 @@ const {const {RESOLVE_ALIASES,} = require("./frontend/build/shared/rspack/resolve-aliases");+const {+ SIDE_EFFECT_FREE_RULE,+} = require("./frontend/build/shared/rspack/side-effect-free-modules");const { SVGO_CONFIG } = require("./frontend/build/shared/rspack/svgo-config");const SRC_PATH = __dirname + "/frontend/src/metabase";@@ -156,6 +159,7 @@ const config = {module: {rules: [+ SIDE_EFFECT_FREE_RULE,{// swc breaks styles for the whole app if we process this filetest: /css\/core\/fonts\.styled\.ts$/,diff --git a/rspack.static-viz.config.js b/rspack.static-viz.config.jsindex 13c2de5cdf6..6ed0b6f7724 100644--- a/rspack.static-viz.config.js+++ b/rspack.static-viz.config.js@@ -3,6 +3,9 @@ const YAML = require("json-to-pretty-yaml");const { StatsWriterPlugin } = require("webpack-stats-plugin");const { WEBPACK_BUNDLE } = require("./frontend/build/shared/constants");+const {+ SIDE_EFFECT_FREE_RULE,+} = require("./frontend/build/shared/rspack/side-effect-free-modules");const { SVGO_CONFIG } = require("./frontend/build/shared/rspack/svgo-config");const ASSETS_PATH = __dirname + "/resources/frontend_client/app/assets";@@ -55,6 +58,7 @@ module.exports = (env) => {module: {rules: [+ SIDE_EFFECT_FREE_RULE,{test: /\.css$/i,use: "null-loader",