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
Tidy module side-effects lint rule (#80734)
Fraser4071663479ff
diff --git a/eslint.config.mjs b/eslint.config.mjsindex 2520d637527..f762cbba74b 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -28,7 +28,10 @@ import {SIDE_EFFECT_PATHS,} from "./frontend/build/shared/rspack/side-effect-free-modules.js";import metabasePlugin from "./frontend/lint/eslint-plugin-metabase/index.js";-import { NO_MODULE_SIDE_EFFECTS_OPTIONS } from "./frontend/lint/no-module-side-effects-options.js";+import {+ NO_MODULE_SIDE_EFFECTS_IGNORES,+ NO_MODULE_SIDE_EFFECTS_OPTIONS,+} from "./frontend/lint/no-module-side-effects-options.js";import {elements as boundaryElements,enforcedRules as boundaryRules,@@ -1211,24 +1214,17 @@ const configs = [// SIDE-EFFECT-FREE MODULES// ============================================{- // Rspack drops any file in these directories whose exports go unused, so an- // import-time effect there is silently lost in production. Declaring a- // directory in SIDE_EFFECT_FREE_PATHS enrols it here.+ // Run the lint on the directories rspack treats as side-effect-freefiles: SIDE_EFFECT_FREE_PATHS.map((dir) => `${path.relative(__dirname, dir)}/**/*.{ts,tsx,js,jsx}`,),ignores: [- // A directory entry (trailing separator) covers every file under it...SIDE_EFFECT_PATHS.map((entry) =>entry.endsWith(path.sep)? `${path.relative(__dirname, entry)}/**`: path.relative(__dirname, entry),),- "**/*.unit.spec.*",- "**/*.stories.*",- "**/tests/**",- "**/__support__/**",- "**/*.d.ts",+ ...NO_MODULE_SIDE_EFFECTS_IGNORES,],rules: {"metabase/no-module-side-effects": [diff --git a/frontend/build/shared/rspack/side-effect-free-modules.js b/frontend/build/shared/rspack/side-effect-free-modules.jsindex d34cf33be78..a3fec9cf4ec 100644--- a/frontend/build/shared/rspack/side-effect-free-modules.js+++ b/frontend/build/shared/rspack/side-effect-free-modules.js@@ -4,73 +4,27 @@ 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- * the `metabase/no-module-side-effects` lint rule is applied to every directory- * listed here (see eslint.config.mjs) and reports the import-time work it can see.- * Third-party imports are assumed self-contained: a package whose import-time work non-importers rely on- * is listed in the registry's `packages` (frontend/lint/side-effect-files.json),- * and a vendor with host-extending plugins gets a facade.- *- * Only applies to production builds, where `optimization.sideEffects` is on.- */+// Sets sideEffects: false for the listed paths, and enrols them in the metabase/no-module-side-effects lint.+// This is unrelated to route splitting (the `import()` calls in metabase/routes.tsx).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,- // The expression language: its barrel re-exports the autocomplete sources and- // the lezer tokenizer, so a picker importing only `getClauseDefinition` from it- // would otherwise pull CodeMirror into the initial bundle.- path.join(REPO_ROOT, "frontend/src/metabase/querying/expressions") + path.sep,- path.join(REPO_ROOT, "frontend/src/metabase/ui") + path.sep,-];+ "frontend/src/metabase/router",+ "frontend/src/metabase/querying/expressions",+ "frontend/src/metabase/ui",+ // Trailing separator: rspack prefix-matches `include`, so a bare directory path would also claim a sibling like `router-utils.ts`.+].map((dir) => path.join(REPO_ROOT, dir) + path.sep);-/**- * Paths inside a side-effect-free directory that do have an import-time effect,- * so keep rspack's default (assume side effects) for them. An entry, and its- * whole import graph, is kept in every bundle that reaches it, so the list- * should stay short and every file entry should be a fix candidate.- *- * A directory entry (trailing separator, like SIDE_EFFECT_FREE_PATHS) covers every file under it.- * List `<module>/api` here when a module is enrolled: those files register their endpoints on the shared Api at import,- * so a bundle has to evaluate them even when it only reaches them by name.- */+// Exceptions to the above rule, which are known to have side effects and must be included in the bundle.const SIDE_EFFECT_PATHS = [- // The pratt parser tables are built by module-scope calls that mutate the exported NODE_TYPE objects.- // Their results are unused, so a PURE annotation would let the minifier delete the setup.- path.join(- REPO_ROOT,- "frontend/src/metabase/querying/expressions/pratt/syntax.ts",- ),- // Installs our wrapped dropdown on Mantine's own Popover object. Mantine's- // Combobox, Menu, ColorInput and HoverCard render `Popover.Dropdown`- // internally, so a bundle that never imports our `Popover` still depends on- // the replacement having run. ThemeProvider bare-imports it.- path.join(- REPO_ROOT,- "frontend/src/metabase/ui/components/overlays/Popover/register-popover-dropdown.ts",- ),-];+ // Module-scope calls fill in the exported NODE_TYPE objects.+ "frontend/src/metabase/querying/expressions/pratt/syntax.ts",+ // Replaces `Popover.Dropdown` on Mantine's own Popover, which Combobox, Menu, ColorInput and HoverCard render internally.+ "frontend/src/metabase/ui/components/overlays/Popover/register-popover-dropdown.ts",+].map((file) => path.join(REPO_ROOT, file));const SIDE_EFFECT_FREE_RULE = {- // Script files only. A CSS module imported for its class names is reachable- // only through the script that imports it, so it is dropped with that script- // and needs no flag of its own; leaving CSS at rspack's default also keeps a- // stray `import "./x.css"` from being shaken should one slip past the lint.+ // Scope to JS/TS files, since we don't want to mark CSS or other assets as side-effect-free.test: /\.[jt]sx?$/,include: SIDE_EFFECT_FREE_PATHS,- // Prefix-matched like `include`, so a directory entry excludes its whole tree.exclude: SIDE_EFFECT_PATHS,sideEffects: false,};diff --git a/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.js b/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.jsindex f24d51778bf..71cf8ea8618 100644--- a/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.js+++ b/frontend/lint/eslint-plugin-metabase/rules/no-module-side-effects.js@@ -1,12 +1,5 @@-/**- * @fileoverview Files declared side-effect free (frontend/build/shared/rspack/side-effect-free-modules.js)- * are dropped from production bundles once their exports go unused, so anything they do at import time is silently lost.- * This reports module-scope code that does work at import.- * A dropped file also takes with it everything only it imports, so it also reports an import- * of a file that frontend/lint/side-effect-files.json classifies as having a global effect,- * or of a third-party package the registry lists as doing global work at import.- * The config decides which files are linted, not the rule.- */+// Reports code that runs at import time in a file rspack treats as side-effect-free.+// Rspack drops such a file from production bundles when nothing uses its exports, so anything it does at import is lost.const fs = require("fs");const path = require("path");@@ -21,17 +14,14 @@ const {const REPO_ROOT = path.resolve(__dirname, "../../../..");-// The tsconfig `*` path roots: `metabase/x` is looked up under each in turn.const DEFAULT_SOURCE_ROOTS = ["frontend/src", "enterprise/frontend/src"];const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];-// Registry path -> parsed registry, so the file is read once per lint run rather than once per file.const registries = new Map();-// Callees known to be pure, so a module-scope call to them needs no annotation.-// A name matches the imported binding or a property called on one (`memo`, `Button.extend`).-// Mantine's `extend` is the identity config helper every *.config.ts calls.+// Calls to these only return a value, so we don't report them at module scope.+// A name matches the imported binding or a property called on it, so `extend` covers `Button.extend`.const DEFAULT_PURE_CALLEES = [{module: "react",@@ -85,33 +75,32 @@ const DEFAULT_PURE_CALLEES = [{ module: "underscore", names: ["compose", "memoize", "once"] },];-// These act on their first argument, so the verdict follows it: fine on a same-file object, a mutation otherwise.-const FIRST_ARGUMENT_MUTATORS = new Set([- "Object.assign",- "Object.defineProperty",- "Object.defineProperties",- "Object.freeze",- "Object.seal",+// `Object.assign` and these others change their first argument, so we report on the argument rather than the call.+const MUTATING_OBJECT_METHODS = new Set([+ "assign",+ "defineProperty",+ "defineProperties",+ "freeze",+ "seal",]);-const CONTROL_FLOW_STATEMENTS = new Set([- "IfStatement",- "ForStatement",- "ForInStatement",- "ForOfStatement",- "WhileStatement",- "DoWhileStatement",- "TryStatement",- "SwitchStatement",- "ThrowStatement",- "LabeledStatement",- "BlockStatement",- "DebuggerStatement",-]);+// A control-flow statement at module scope is reported once as a whole, under the keyword the message names.+const CONTROL_FLOW_KEYWORDS = {+ IfStatement: "if",+ ForStatement: "for",+ ForInStatement: "for",+ ForOfStatement: "for",+ WhileStatement: "while",+ DoWhileStatement: "while",+ TryStatement: "try",+ SwitchStatement: "switch",+ ThrowStatement: "throw",+ DebuggerStatement: "debugger",+ LabeledStatement: "a block",+ BlockStatement: "a block",+};-// An expression under one of these is not judged.-// Function bodies run later, class bodies are not inspected,-// and a control-flow statement is reported once as a whole.+// Anything under one of these is skipped: function bodies run later, class bodies aren't inspected, and a control-flow statement is already reported as a whole.const NOT_MODULE_SCOPE = new Set(["FunctionDeclaration","FunctionExpression",@@ -121,7 +110,7 @@ const NOT_MODULE_SCOPE = new Set(["PropertyDefinition","AccessorProperty","StaticBlock",- ...CONTROL_FLOW_STATEMENTS,+ ...Object.keys(CONTROL_FLOW_KEYWORDS),]);const EXPRESSION_WRAPPERS = new Set([@@ -169,22 +158,21 @@ module.exports = {},sideEffectPaths: {type: "array",- // Absolute paths allowed to have import-time effects: a file, or a- // directory (trailing separator) covering every file under it+ // Absolute file paths, or directories with a trailing separator.items: { type: "string" },},internalModules: {type: "array",- // Import alias roots that resolve inside this repo, e.g. "metabase"+ // Import roots that resolve inside the repo, such as "metabase".items: { type: "string" },},sideEffectRegistry: {- // Path to the registry of effect files, default frontend/lint/side-effect-files.json+ // Defaults to frontend/lint/side-effect-files.json.type: "string",},sourceRoots: {type: "array",- // Repo-relative directories a non-relative import is resolved under, default the tsconfig `*` roots+ // Defaults to the tsconfig `*` roots.items: { type: "string" },},},@@ -193,35 +181,34 @@ module.exports = {],messages: {bareImport:- "Bare import of '{{source}}' runs it for its effect at import time. Move the effect into a registration module listed in SIDE_EFFECT_PATHS, or into an entry.",+ "`import '{{source}}'` is only there for what the file does at import, so move that work into a file in SIDE_EFFECT_PATHS or import it from an app entry.",callOnImport:- "Module-scope call on the imported binding `{{callee}}` runs at import time. If it is pure, annotate it `/* #__PURE__ */` or add it to pureCallees; otherwise move it out of module scope.",+ "`{{callee}}` runs at import time. If it only returns a value, mark it `/* #__PURE__ */` or add it to pureCallees, otherwise move it inside a function.",callAtModuleScope:- "Module-scope call `{{callee}}` runs at import time and its result is unused, so it exists only for its effect. Move it into a registration module listed in SIDE_EFFECT_PATHS, or annotate it `/* #__PURE__ */` if it is pure.",+ "`{{callee}}` runs at import time and its result is thrown away, so move it inside a function or into a file in SIDE_EFFECT_PATHS.",assignToImport:- "Assigning to `{{target}}` mutates an imported object at import time. Move it into a registration module listed in SIDE_EFFECT_PATHS.",+ "`{{target}}` is an import that gets changed at import time, so move the change into a file in SIDE_EFFECT_PATHS.",assignToGlobal:- "Assigning to `{{target}}` writes global state at import time. Move it into a registration module listed in SIDE_EFFECT_PATHS, or into an entry.",+ "`{{target}}` is global state written at import time, so move the write into a file in SIDE_EFFECT_PATHS or an app entry.",topLevelAwait:- "Top-level await runs at import time. Move it into a function that is called from an entry.",+ "Top-level await runs at import time, so move it into a function called from an app entry.",controlFlow:- "`{{kind}}` at module scope means work runs at import time. Move it into a function, or into a registration module listed in SIDE_EFFECT_PATHS.",+ "`{{kind}}` at module scope runs at import time, so move it inside a function or into a file in SIDE_EFFECT_PATHS.",importsGlobalEffect:- "'{{source}}' runs an effect at import that code outside it depends on. A side-effect-free file must not be the reason it loads; import it from an entry (or list it in SIDE_EFFECT_PATHS if this file is a registration module).",+ "'{{source}}' does work at import that code outside it relies on, so import it from an app entry or add this file to SIDE_EFFECT_PATHS.",importsGlobalEffectPackage:- "'{{source}}' does work at import that code outside it depends on (a polyfill, a plugin on a host, global CSS). A side-effect-free file must not be the reason it loads; import it from an entry, or through the vendor's facade.",+ "'{{source}}' does work at import that code outside it relies on, so import it from an app entry or through the vendor's facade.",},},create(context) {- const sourceCode = context.sourceCode || context.getSourceCode();- const filename = context.filename || context.getFilename();+ const { sourceCode, filename } = context;const options = context.options[0] || {};const pureCallees = [...DEFAULT_PURE_CALLEES,...(options.pureCallees || []),];- const sideEffectPaths = normalizeSideEffectPaths(+ const isSideEffectPath = sideEffectPathMatcher(options.sideEffectPaths || [],);const internalModules = new Set(options.internalModules || []);@@ -231,6 +218,8 @@ module.exports = {const sourceRoots = (options.sourceRoots || DEFAULT_SOURCE_ROOTS).map((root) => path.resolve(REPO_ROOT, root),);+ // getScope() on the Program node returns the outer global scope, so ask the scope manager for the module scope itself.+ const moduleScope = sourceCode.scopeManager.acquire(sourceCode.ast, true);function isInternalModule(source) {return (@@ -238,27 +227,31 @@ module.exports = {);}- // Collected over the whole file before any expression is judged, so a function declared below its call site still counts as local.- const localNames = new Set();- // local name -> { module, importedName }- const importBindings = new Map();+ // The import a module-scope name refers to, or null when this file declares the name or it is a global.+ function importOf(name) {+ const def = moduleScope.set+ .get(name)+ ?.defs.find(+ (def) =>+ def.type === "ImportBinding" &&+ def.parent.type === "ImportDeclaration",+ );+ return def == null+ ? null+ : {+ module: def.parent.source.value,+ importedName: importedNameOf(def.node),+ };+ }- function classifyRoot(root) {- if (root == null || root.type !== "Identifier") {- return "local";- }- if (importBindings.has(root.name)) {- return "import";- }- if (localNames.has(root.name)) {- return "local";- }- return "global";+ function isDeclaredHere(name) {+ return moduleScope.set.has(name) && importOf(name) == null;}// The annotation may sit on the call or on a wrapper around it (`/* #__PURE__ */ foo()!`).function isPureAnnotated(node) {- for (const current of wrapperChain(node)) {+ let current = node;+ while (current != null) {const comments = sourceCode.getCommentsBefore(current);if (comments.length > 0 &&@@ -266,16 +259,15 @@ module.exports = {) {return true;}+ current = EXPRESSION_WRAPPERS.has(current.parent.type)+ ? current.parent+ : null;}return false;}- function isAllowlistedCallee(callee) {- const { root, name } = getCalleeInfo(callee);- const binding = root == null ? null : importBindings.get(root.name);- if (binding == null) {- return false;- }+ function isPureCallee(callee, root, binding) {+ const name = calledName(callee);return pureCallees.some((entry) =>entry.module === binding.module &&@@ -292,101 +284,77 @@ module.exports = {: text;}- function reportMutationOf(target, node, targetNode) {- const kind = classifyRoot(getRoot(target));- if (kind === "local") {+ function reportMutationOf(target, node) {+ const root = getRoot(target);+ if (root == null || isDeclaredHere(root.name)) {return;}context.report({node,- messageId: kind === "import" ? "assignToImport" : "assignToGlobal",- data: { target: display(targetNode || target) },+ messageId:+ importOf(root.name) == null ? "assignToGlobal" : "assignToImport",+ data: { target: display(target) },});}- // A call in a statement exists only for its effect, so every call not known pure is reported.- // In an initializer the value is kept, so only calls into packages are reported.- // Our own code (relative or in-repo alias imports) and `new` are trusted there.- function checkCall(node, inStatement) {+ // A call whose result is kept is only reported when it goes into a third-party package, since we trust our own code and `new` to only return a value.+ function checkCall(node) {if (isPureAnnotated(node)) {return;}const callee =node.type === "TaggedTemplateExpression" ? node.tag : node.callee;- const dottedPath = getDottedPath(callee);- if (dottedPath != null && FIRST_ARGUMENT_MUTATORS.has(dottedPath)) {- const [mutated] = node.arguments || [];+ const root = getRoot(callee);+ if (+ root?.name === "Object" &&+ MUTATING_OBJECT_METHODS.has(calledName(callee))+ ) {+ const [mutated] = node.arguments;if (mutated != null) {- reportMutationOf(mutated, node, mutated);+ reportMutationOf(mutated, node);}return;}- if (isAllowlistedCallee(callee)) {- return;- }- const root = getRoot(callee);- const kind = classifyRoot(root);- if (kind === "import") {- const trusted =- !inStatement &&- (node.type === "NewExpression" ||- isInternalModule(importBindings.get(root.name).module));- if (!trusted) {+ const binding = root == null ? null : importOf(root.name);+ if (binding == null) {+ if (isDiscarded(node)) {context.report({node,- messageId: "callOnImport",+ messageId: "callAtModuleScope",data: { callee: display(callee) },});}- } else if (inStatement) {+ return;+ }+ if (isPureCallee(callee, root, binding)) {+ return;+ }+ const returnsValue =+ node.type === "NewExpression" || isInternalModule(binding.module);+ if (isDiscarded(node) || !returnsValue) {context.report({node,- messageId: "callAtModuleScope",+ messageId: "callOnImport",data: { callee: display(callee) },});}}- function checkAssignment(node) {- if (node.left.type === "Identifier") {- if (classifyRoot(node.left) === "global") {- context.report({- node,- messageId: "assignToGlobal",- data: { target: display(node.left) },- });- }- } else if (node.left.type === "MemberExpression") {- reportMutationOf(node.left, node);- }- }-- function checkUpdate(node) {- if (- node.argument.type === "MemberExpression" ||- classifyRoot(node.argument) === "global"- ) {- reportMutationOf(node.argument, node);- }- }-function checkBareImport(node) {const source = node.source.value;const target = source.startsWith(".")? normalizePath(path.resolve(path.dirname(filename), source)): source;- if (sideEffectPaths.allows(target)) {- return;+ if (!isSideEffectPath(target)) {+ context.report({ node, messageId: "bareImport", data: { source } });}- context.report({ node, messageId: "bareImport", data: { source } });}- // An import with bindings keeps its target alive only while this file is kept,- // so a target whose effect others depend on must not be reached this way.+ // A file imported for its bindings is dropped from the bundle along with this file.function checkBindingImport(node) {const source = node.source.value;const target = resolveImport(source, path.dirname(filename), sourceRoots);- if (target == null || sideEffectPaths.allows(target)) {+ if (target == null || isSideEffectPath(target)) {return;}const relative = normalizePath(path.relative(REPO_ROOT, target));@@ -403,8 +371,6 @@ module.exports = {}}- // A listed package is reported the same way whether the import is bare or has bindings,- // unless this file is a registration module, where loading it is the point.function checkImport(node) {const bare = node.specifiers.length === 0;if (!bare && isTypeOnly(node)) {@@ -414,7 +380,7 @@ module.exports = {if (!isInternalModule(source) &&classifyPackage(registry, source) === "global" &&- !sideEffectPaths.allows(normalizePath(filename))+ !isSideEffectPath(normalizePath(filename))) {context.report({node,@@ -428,64 +394,13 @@ module.exports = {}}- function checkTopLevelStatement(node) {- if (node.type === "ImportDeclaration") {- checkImport(node);- } else if (CONTROL_FLOW_STATEMENTS.has(node.type)) {- context.report({- node,- messageId: "controlFlow",- data: { kind: statementKeyword(node) },- });- }- }-- function collectBindings(node) {- switch (node.type) {- case "ImportDeclaration":- for (const specifier of node.specifiers) {- importBindings.set(specifier.local.name, {- module: node.source.value,- importedName: importedNameOf(specifier),- });- }- return;- case "VariableDeclaration":- for (const declarator of node.declarations) {- for (const name of patternNames(declarator.id)) {- localNames.add(name);- }- }- return;- case "FunctionDeclaration":- case "ClassDeclaration":- case "TSEnumDeclaration":- case "TSModuleDeclaration":- case "TSDeclareFunction":- if (node.id && node.id.type === "Identifier") {- localNames.add(node.id.name);- }- return;- case "ExportNamedDeclaration":- if (node.declaration != null) {- collectBindings(node.declaration);- }- return;- case "ExportDefaultDeclaration":- collectBindings(node.declaration);- return;- default:- return;- }- }-- // Runs `check` on the node when it is evaluated at module scope.- // The Program visitor has already collected the bindings by then.function atModuleScope(check) {return (node) => {- const placement = placementOf(node);- if (placement !== "skipped") {- check(node, placement === "statement");+ const ancestors = sourceCode.getAncestors(node);+ if (+ !ancestors.some((ancestor) => NOT_MODULE_SCOPE.has(ancestor.type))+ ) {+ check(node);}};}@@ -493,10 +408,15 @@ module.exports = {return {Program(program) {for (const statement of program.body) {- collectBindings(statement);- }- for (const statement of program.body) {- checkTopLevelStatement(statement);+ if (statement.type === "ImportDeclaration") {+ checkImport(statement);+ } else if (statement.type in CONTROL_FLOW_KEYWORDS) {+ context.report({+ node: statement,+ messageId: "controlFlow",+ data: { kind: CONTROL_FLOW_KEYWORDS[statement.type] },+ });+ }}},CallExpression: atModuleScope(checkCall),@@ -512,8 +432,12 @@ module.exports = {AwaitExpression: atModuleScope((node) => {context.report({ node, messageId: "topLevelAwait" });}),- AssignmentExpression: atModuleScope(checkAssignment),- UpdateExpression: atModuleScope(checkUpdate),+ AssignmentExpression: atModuleScope((node) => {+ reportMutationOf(node.left, node);+ }),+ UpdateExpression: atModuleScope((node) => {+ reportMutationOf(node.argument, node);+ }),UnaryExpression: atModuleScope((node) => {if (node.operator === "delete") {reportMutationOf(node.argument, node);@@ -523,24 +447,17 @@ module.exports = {},};-// Where an expression's value goes: "skipped" under a function, a class body or a control-flow statement,-// "statement" when it is discarded, "value" when it is kept.-function placementOf(node) {- let placement = null;- for (let current = node; current.parent != null; current = current.parent) {- const { parent } = current;- if (NOT_MODULE_SCOPE.has(parent.type)) {- return "skipped";- }- if (placement == null && !discardsValueOf(parent, current)) {- placement = parent.type === "ExpressionStatement" ? "statement" : "value";- }+// Whether the value of `node` is thrown away, looking through the parents that only pass it along.+function isDiscarded(node) {+ let current = node;+ while (forwardsValueOf(current.parent, current)) {+ current = current.parent;}- return placement ?? "value";+ return current.parent.type === "ExpressionStatement";}-// Whether `parent` hands `child`'s value on unused, so an expression statement above still discards it.-function discardsValueOf(parent, child) {+// Whether `parent` passes `child`'s value straight through.+function forwardsValueOf(parent, child) {switch (parent.type) {case "SequenceExpression":return true;@@ -553,30 +470,15 @@ function discardsValueOf(parent, child) {}}-// The node and every TS wrapper or optional chain around it, innermost first.-function wrapperChain(node) {- const chain = [node];- let current = node;- while (- current.parent != null &&- EXPRESSION_WRAPPERS.has(current.parent.type)- ) {- current = current.parent;- chain.push(current);- }- return chain;-}-function unwrap(node) {let current = node;- while (current != null && EXPRESSION_WRAPPERS.has(current.type)) {+ while (EXPRESSION_WRAPPERS.has(current.type)) {current = current.expression;}return current;}// The identifier an expression starts from: `a` for `a.b.c`, `a().b` and `(a as X)!.b?.c`.-// Null when there is none (a literal, `this`, an IIFE).function getRoot(node) {let current = unwrap(node);while (current != null) {@@ -600,47 +502,23 @@ function getRoot(node) {return null;}-// The root binding and the name called: `rem` for `rem(4)`, `extend` for `Button.extend({})`, `t` for `c("ctx").t\`\``.-function getCalleeInfo(callee) {+// The name a callee is called by: `rem` for `rem(4)`, `extend` for `Button.extend({})`, `t` for `c("ctx").t\`\``.+function calledName(callee) {const inner = unwrap(callee);- if (inner == null) {- return { root: null, name: null };- }- if (inner.type === "Identifier") {- return { root: inner, name: inner.name };- }- if (inner.type === "MemberExpression") {- const name =- !inner.computed && inner.property.type === "Identifier"+ switch (inner.type) {+ case "Identifier":+ return inner.name;+ case "MemberExpression":+ return !inner.computed && inner.property.type === "Identifier"? inner.property.name: null;- return { root: getRoot(inner), name };- }- if (- inner.type === "CallExpression" ||- inner.type === "TaggedTemplateExpression"- ) {- return getCalleeInfo(inner.callee || inner.tag);- }- return { root: getRoot(inner), name: null };-}--// The dotted name of a plain member chain (`Object.assign`), null for anything else.-function getDottedPath(node) {- const parts = [];- let current = unwrap(node);- while (current != null && current.type === "MemberExpression") {- if (current.computed || current.property.type !== "Identifier") {+ case "CallExpression":+ return calledName(inner.callee);+ case "TaggedTemplateExpression":+ return calledName(inner.tag);+ default:return null;- }- parts.unshift(current.property.name);- current = unwrap(current.object);}- if (current == null || current.type !== "Identifier") {- return null;- }- parts.unshift(current.name);- return parts.join(".");}function importedNameOf(specifier) {@@ -656,53 +534,6 @@ function importedNameOf(specifier) {}}-function patternNames(pattern) {- switch (pattern.type) {- case "Identifier":- return [pattern.name];- case "ObjectPattern":- return pattern.properties.flatMap((property) =>- property.type === "RestElement"- ? patternNames(property.argument)- : patternNames(property.value),- );- case "ArrayPattern":- return pattern.elements.flatMap((element) =>- element == null ? [] : patternNames(element),- );- case "AssignmentPattern":- return patternNames(pattern.left);- case "RestElement":- return patternNames(pattern.argument);- default:- return [];- }-}--function statementKeyword(node) {- switch (node.type) {- case "IfStatement":- return "if";- case "ForStatement":- case "ForInStatement":- case "ForOfStatement":- return "for";- case "WhileStatement":- case "DoWhileStatement":- return "while";- case "TryStatement":- return "try";- case "SwitchStatement":- return "switch";- case "ThrowStatement":- return "throw";- case "DebuggerStatement":- return "debugger";- default:- return "a block";- }-}-function getRegistry(registryPath) {if (!registries.has(registryPath)) {registries.set(registryPath, loadRegistry(registryPath));@@ -710,7 +541,6 @@ function getRegistry(registryPath) {return registries.get(registryPath);}-// A type-only import is erased, so nothing loads.function isTypeOnly(node) {return (node.importKind === "type" ||@@ -718,8 +548,6 @@ function isTypeOnly(node) {);}-// The absolute file an import source names, or null when it is a package or does not resolve.-// A relative source is resolved from the importing file, any other under each source root in turn.function resolveImport(source, fromDirectory, sourceRoots) {const bases = source.startsWith(".")? [path.resolve(fromDirectory, source)]@@ -733,7 +561,6 @@ function resolveImport(source, fromDirectory, sourceRoots) {return null;}-// `base`, `base.<ext>` or `base/index.<ext>`, whichever exists.function resolveSourceFile(base) {const candidates = [base,@@ -753,7 +580,6 @@ function resolveSourceFile(base) {);}-// `metabase/lib/x` maps to `metabase`, `@scope/pkg/x` to `@scope/pkg`.function packageNameOf(source) {const segments = source.split("/");return source.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];@@ -767,26 +593,14 @@ function stripScriptExtension(file) {return file.replace(/\.[jt]sx?$/, "");}-// A directory entry ends with a separator and covers every file under it.-function normalizeSideEffectPaths(paths) {- const files = new Set();- const directories = [];- for (const entry of paths) {- const absolute = normalizePath(path.resolve(entry));- if (normalizePath(entry).endsWith("/")) {- directories.push(`${absolute}/`);- } else {- files.add(absolute);- files.add(stripScriptExtension(absolute));- }- }- return {- allows(target) {- return (- files.has(target) ||- files.has(stripScriptExtension(target)) ||- directories.some((directory) => target.startsWith(directory))- );- },- };+// A directory entry ends with a separator and covers every file under it, and a file entry matches with or without its extension.+function sideEffectPathMatcher(entries) {+ const paths = entries.map(normalizePath);+ const directories = paths.filter((entry) => entry.endsWith("/"));+ const files = new Set(+ paths.filter((entry) => !entry.endsWith("/")).map(stripScriptExtension),+ );+ return (target) =>+ files.has(stripScriptExtension(target)) ||+ directories.some((directory) => target.startsWith(directory));}diff --git a/frontend/lint/no-module-side-effects-options.js b/frontend/lint/no-module-side-effects-options.jsindex 13f9cffe1a4..29ef10dfe8a 100644--- a/frontend/lint/no-module-side-effects-options.js+++ b/frontend/lint/no-module-side-effects-options.js@@ -2,13 +2,10 @@ const {SIDE_EFFECT_PATHS,} = require("../build/shared/rspack/side-effect-free-modules.js");-// The options `metabase/no-module-side-effects` runs with in eslint.config.mjs.-// The registry scan (scripts/side-effect-files.js) uses the same object, so a file is in-// frontend/lint/side-effect-files.json exactly when the configured rule reports it.+// Options for metabase/no-module-side-effects, shared by eslint.config.mjs and the registry generator.const NO_MODULE_SIDE_EFFECTS_OPTIONS = {sideEffectPaths: SIDE_EFFECT_PATHS,- // Alias roots that resolve inside the repo (the tsconfig `paths` roots),- // so a module-scope call into them counts as our own code+ // Calls into these count as our own code, which we trust to only return a value.internalModules: ["metabase","metabase-lib",@@ -24,4 +21,16 @@ const NO_MODULE_SIDE_EFFECTS_OPTIONS = {],};-module.exports = { NO_MODULE_SIDE_EFFECTS_OPTIONS };+// Files the rule never runs on, in eslint.config.mjs and in the registry generator alike.+const NO_MODULE_SIDE_EFFECTS_IGNORES = [+ "**/*.unit.spec.*",+ "**/*.stories.*",+ "**/tests/**",+ "**/__support__/**",+ "**/*.d.ts",+];++module.exports = {+ NO_MODULE_SIDE_EFFECTS_OPTIONS,+ NO_MODULE_SIDE_EFFECTS_IGNORES,+};diff --git a/frontend/lint/scripts/side-effect-files.js b/frontend/lint/scripts/side-effect-files.jsindex 8dc986912fe..1937ae4166b 100644--- a/frontend/lint/scripts/side-effect-files.js+++ b/frontend/lint/scripts/side-effect-files.js@@ -1,12 +1,5 @@-/**- * @fileoverview Keeps frontend/lint/side-effect-files.json in step with the source tree.- * The registry lists every source file that `metabase/no-module-side-effects` reports under the options- * eslint.config.mjs gives it, so this scans the tree with just that rule and compares.- *- * bun frontend/lint/scripts/side-effect-files.js --check exit 1 on drift, listing it- * bun frontend/lint/scripts/side-effect-files.js --update add new files as unclassified, drop clean ones- * bun frontend/lint/scripts/side-effect-files.js --verbose also print every finding- */+// Generates frontend/lint/side-effect-files.json by linting the whole tree with `metabase/no-module-side-effects`.+// Without a flag it exits 1 when the registry has drifted, `--update` adds new files as unclassified and drops clean ones, and `--verbose` prints every finding.const fs = require("fs");const path = require("path");@@ -17,6 +10,7 @@ const tseslint = require("typescript-eslint");const rule = require("../eslint-plugin-metabase/rules/no-module-side-effects");const {+ NO_MODULE_SIDE_EFFECTS_IGNORES,NO_MODULE_SIDE_EFFECTS_OPTIONS,} = require("../no-module-side-effects-options");const {@@ -30,70 +24,61 @@ const REPO_ROOT = path.resolve(__dirname, "../../..");const SOURCE_ROOTS = ["frontend/src", "enterprise/frontend/src"];const SOURCE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx"]);-// The same files eslint.config.mjs leaves out of the rule.-const IGNORED_PATTERNS = [- "**/*.unit.spec.*",- "**/*.stories.*",- "**/tests/**",- "**/__support__/**",- "**/*.d.ts",-];const RULE_NAME = "metabase/no-module-side-effects";+const LINTER_CONFIG = [+ {+ files: ["**/*.{ts,tsx,js,jsx}"],+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: { ecmaFeatures: { jsx: true } },+ sourceType: "module",+ },+ plugins: { metabase: { rules: { "no-module-side-effects": rule } } },+ rules: { [RULE_NAME]: ["error", NO_MODULE_SIDE_EFFECTS_OPTIONS] },+ },+];++function readSource(file) {+ return fs.readFileSync(path.join(REPO_ROOT, file), "utf8");+}+function listSourceFiles() {- const files = [];- const walk = (dir) => {- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const entryPath = path.join(dir, entry.name);- if (entry.isDirectory()) {- walk(entryPath);- } else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {- files.push(path.relative(REPO_ROOT, entryPath).replaceAll("\\", "/"));- }- }- };- for (const root of SOURCE_ROOTS) {- walk(path.join(REPO_ROOT, root));- }- return files- .filter((file) => !micromatch.isMatch(file, IGNORED_PATTERNS))+ return SOURCE_ROOTS.flatMap((root) =>+ fs+ .readdirSync(path.join(REPO_ROOT, root), {+ recursive: true,+ withFileTypes: true,+ })+ .filter(+ (entry) =>+ entry.isFile() && SOURCE_EXTENSIONS.has(path.extname(entry.name)),+ )+ .map((entry) =>+ path+ .relative(REPO_ROOT, path.join(entry.parentPath, entry.name))+ .replaceAll("\\", "/"),+ ),+ )+ .filter((file) => !micromatch.isMatch(file, NO_MODULE_SIDE_EFFECTS_IGNORES)).sort();}-function createLinter() {+function scanEffectFiles() {const linter = new Linter();- const config = [- {- files: ["**/*.{ts,tsx,js,jsx}"],- languageOptions: {- parser: tseslint.parser,- parserOptions: { ecmaFeatures: { jsx: true } },- sourceType: "module",- },- plugins: { metabase: { rules: { "no-module-side-effects": rule } } },- rules: { [RULE_NAME]: ["error", NO_MODULE_SIDE_EFFECTS_OPTIONS] },- },- ];- return (file) => {- const source = fs.readFileSync(path.join(REPO_ROOT, file), "utf8");- // The registry records what a file does at import, so its imports of other effect files do not count.- return linter- .verify(source, config, { filename: path.join(REPO_ROOT, file) })+ const findings = new Map();+ for (const file of listSourceFiles()) {+ // The registry records what a file itself does at import, so its imports of other listed files don't count.+ const messages = linter+ .verify(readSource(file), LINTER_CONFIG, {+ filename: path.join(REPO_ROOT, file),+ }).filter((message) =>message.ruleId === RULE_NAME &&message.messageId !== "importsGlobalEffect",);- };-}--// Repo-relative path -> messages, for every source file the rule reports.-function scanEffectFiles() {- const lint = createLinter();- const findings = new Map();- for (const file of listSourceFiles()) {- const messages = lint(file);if (messages.length > 0) {findings.set(file, messages);}@@ -101,8 +86,7 @@ function scanEffectFiles() {return findings;}-// Listed packages that no source file imports, so the list cannot keep dead entries.-// A specifier is imported when it appears quoted, alone or with a subpath, anywhere in a source file.+// Listed packages that no source file imports.function unimportedPackages(registry, files) {const unseen = new Map(Object.keys(registry.packages).map((specifier) => [@@ -114,7 +98,7 @@ function unimportedPackages(registry, files) {if (unseen.size === 0) {break;}- const source = fs.readFileSync(path.join(REPO_ROOT, file), "utf8");+ const source = readSource(file);for (const [specifier, pattern] of unseen) {if (pattern.test(source)) {unseen.delete(specifier);@@ -128,7 +112,6 @@ function escapeRegExp(text) {return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}-// { missing: effect files the registry does not list, stale: exact entries whose file is clean }function diffRegistry(registry, effectFiles) {const effectSet = new Set(effectFiles);const missing = effectFiles.filter(@@ -141,9 +124,7 @@ function diffRegistry(registry, effectFiles) {return { missing, stale };}-// The stale entries the registry spec fails on: the rule rejects imports of a file classified-// "global" or "entry", so a stale entry keeps rejecting imports of a file that is now clean,-// while a stale "self" entry affects nothing and can wait for an --update sweep.+// A stale "global" or "entry" entry keeps rejecting imports of a clean file, whereas a stale "self" entry affects nothing.function enforcedStale(registry, stale) {return stale.filter((file) => classify(registry, file) !== "self");}diff --git a/frontend/lint/side-effect-registry.js b/frontend/lint/side-effect-registry.jsindex 3d579ab3af2..b1b70f85de8 100644--- a/frontend/lint/side-effect-registry.js+++ b/frontend/lint/side-effect-registry.js@@ -1,26 +1,5 @@-/**- * @fileoverview Reads frontend/lint/side-effect-files.json, the registry of source files that- * `metabase/no-module-side-effects` reports as doing work at import time.- *- * Every file it reports is listed, classified once by a human:- * "self" the effect only matters to the file's own importers (its own singleton or listener,- * a value it exports), so dropping the file with its importers is correct- * "global" the effect is consumed by code that does not import the file (a polyfill, a vendor patch,- * a registry the app reads, a plugin slot write), so the file must be loaded from an entry- * "entry" a bundle entry or a side-effects list, effectful by design- * `unclassified` files are treated as "global" until someone classifies them.- * `facades` are directory prefixes whose effect is their own exports (`metabase/ui`, `metabase/dayjs`),- * so importing them with bindings is always fine.- * `packages` are bare specifiers of third-party packages whose import-time work is consumed by code- * that does not import them (a polyfill, a plugin on a host like `leaflet-draw` on `L`, global CSS).- * It is hand-maintained: node_modules are not scanned, and a package it does not list is assumed- * self-contained, its import-time work serving only its own exports.- * A key matches its exact specifier and every subpath under it (`leaflet-draw` covers `leaflet-draw/x`).- * A vendor whose plugins extend the host (dayjs) gets a facade, and other rules forbid importing it raw,- * so it needs no entry here.- * Keys are repo-relative paths; a key containing `*` is a micromatch pattern, and an exact key wins over a pattern.- * `scripts/side-effect-files.js --check` keeps the file in step with the tree.- */+// Reads frontend/lint/side-effect-files.json, the registry of source files that run code at import time.+// The file list is generated by `bun frontend/lint/scripts/side-effect-files.js --update`, and `packages` is written by hand.const fs = require("fs");const path = require("path");@@ -29,24 +8,30 @@ const micromatch = require("micromatch");const DEFAULT_REGISTRY_PATH = path.resolve(__dirname, "side-effect-files.json");+// self: only the file itself relies on its side effects+// global: other code relies on its side effects+// entry: the file is a bundle entry point, so its side effects are always includedconst CLASSIFICATIONS = ["self", "global", "entry"];-const PACKAGE_CLASSIFICATIONS = ["global"];-function loadRegistry(registryPath = DEFAULT_REGISTRY_PATH) {const registry = JSON.parse(fs.readFileSync(registryPath, "utf8"));const files = registry.files || {};- const patterns = Object.keys(files).filter((key) => key.includes("*"));return {facades: registry.facades || [],files,packages: registry.packages || {},- patterns,+ patterns: Object.keys(files).filter((key) => key.includes("*")),unclassified: new Set(registry.unclassified || []),};}-// The classification of a repo-relative file, or null when the registry does not list it.+function matchingPatterns(registry, file) {+ return registry.patterns.filter((pattern) =>+ micromatch.isMatch(file, pattern),+ );+}++// An unclassified file counts as "global", and an exact key wins over a pattern.function classify(registry, file) {if (file in registry.files) {return registry.files[file];@@ -54,17 +39,14 @@ function classify(registry, file) {if (registry.unclassified.has(file)) {return "global";}- const matched = registry.patterns.filter((pattern) =>- micromatch.isMatch(file, pattern),- );- return matched.length > 0 ? registry.files[matched[0]] : null;+ const [pattern] = matchingPatterns(registry, file);+ return pattern == null ? null : registry.files[pattern];}function isFacade(registry, file) {return registry.facades.some((prefix) => file.startsWith(prefix));}-// The classification of a package import source, or null when the registry does not list the package.function classifyPackage(registry, source) {const listed = Object.keys(registry.packages).find((specifier) => source === specifier || source.startsWith(`${specifier}/`),@@ -72,7 +54,6 @@ function classifyPackage(registry, source) {return listed == null ? null : registry.packages[listed];}-// Problems a hand-edited registry can have. Empty when it is well formed.function validateRegistry(registry, effectFiles) {const problems = [];for (const [key, value] of Object.entries(registry.files)) {@@ -87,20 +68,17 @@ function validateRegistry(registry, effectFiles) {if (specifier === "" || specifier.startsWith(".")) {problems.push(`packages: "${specifier}" is not a bare specifier`);}- if (!PACKAGE_CLASSIFICATIONS.includes(value)) {+ if (value !== "global") {problems.push(`${specifier}: unknown package classification "${value}"`);}}for (const file of effectFiles) {- if (file in registry.files) {- continue;- }const values = new Set(- registry.patterns- .filter((pattern) => micromatch.isMatch(file, pattern))- .map((pattern) => registry.files[pattern]),+ matchingPatterns(registry, file).map(+ (pattern) => registry.files[pattern],+ ),);- if (values.size > 1) {+ if (!(file in registry.files) && values.size > 1) {problems.push(`${file}: matches patterns with different classifications, add an exact entry`,);