Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(sdk): Convert plugin system to deferred initialization (#65142)

Sébastiend514efc3c35a
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
index b05d466cc93..d0e4e0a7b7f 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx
@@ -15,11 +15,12 @@ import type { SdkStore } from "embedding-sdk-bundle/store/types";
import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-provider";
import { EnsureSingleInstance } from "embedding-sdk-shared/components/EnsureSingleInstance/EnsureSingleInstance";
import { useInstanceLocale } from "metabase/common/hooks/use-instance-locale";
-import { MetabaseReduxProvider } from "metabase/lib/redux";
+import { MetabaseReduxProvider, useSelector } from "metabase/lib/redux";
import { LocaleProvider } from "metabase/public/LocaleProvider";
import { setOptions } from "metabase/redux/embed";
import { EmotionCacheProvider } from "metabase/styled-components/components/EmotionCacheProvider";
import { MetabotProvider } from "metabase-enterprise/metabot/context";
+import { initializePlugins } from "sdk-ee-plugins";
import { SCOPED_CSS_RESET } from "../../private/PublicComponentStylesWrapper";
import { SdkFontsGlobalStyles } from "../../private/SdkGlobalFontsStyles";
@@ -31,6 +32,24 @@ type ComponentProviderInternalProps = ComponentProviderProps & {
isLocalHost?: boolean;
};
+let hasInitializedPlugins = false;
+
+function useInitPlugins() {
+ const tokenFeatures = useSelector(
+ (state) => state.settings.values["token-features"],
+ );
+
+ useEffect(() => {
+ if (hasInitializedPlugins || !tokenFeatures) {
+ return;
+ }
+
+ hasInitializedPlugins = true;
+
+ initializePlugins();
+ }, [tokenFeatures]);
+}
+
export const ComponentProviderInternal = ({
children,
authConfig,
@@ -52,6 +71,8 @@ export const ComponentProviderInternal = ({
// - Unit tests
useInitDataInternal({ reduxStore, authConfig, isLocalHost });
+ useInitPlugins();
+
useEffect(() => {
if (fontFamily) {
reduxStore.dispatch(setOptions({ font: fontFamily }));
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/index.ts b/enterprise/frontend/src/embedding-sdk-bundle/index.ts
index e5a817fe54d..4572080e9e8 100644
--- a/enterprise/frontend/src/embedding-sdk-bundle/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-bundle/index.ts
@@ -10,7 +10,9 @@ EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
import "metabase/embedding-sdk/vendors-side-effects";
// Import the EE plugins required by the embedding sdk.
-import "sdk-ee-plugins";
+import { initializePlugins } from "sdk-ee-plugins";
+
+initializePlugins();
// Imports which are only applicable to the embedding sdk, and not the new iframe embedding.
import "sdk-specific-imports";
diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
index 62df22b3910..cab3d9bbd54 100644
--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/index.js
@@ -44,109 +44,120 @@ const BLOCK_PERMISSION_OPTION = {
iconColor: "danger",
};
-if (hasPremiumFeature("advanced_permissions")) {
- const addSelectedAdvancedPermission = (options, value) => {
- if (value === IMPERSONATED_PERMISSION_OPTION.value) {
- return [...options, IMPERSONATED_PERMISSION_OPTION];
- }
-
- return options;
- };
-
- PLUGIN_ADMIN_PERMISSIONS_TABLE_OPTIONS.push(BLOCK_PERMISSION_OPTION);
- PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_OPTIONS.push(BLOCK_PERMISSION_OPTION);
-
- PLUGIN_ADVANCED_PERMISSIONS.addTablePermissionOptions =
- addSelectedAdvancedPermission;
- PLUGIN_ADVANCED_PERMISSIONS.addSchemaPermissionOptions =
- addSelectedAdvancedPermission;
- PLUGIN_ADVANCED_PERMISSIONS.addDatabasePermissionOptions = (
- options,
- database,
- ) => [
- ...options,
- ...(database.hasFeature("connection-impersonation")
- ? [IMPERSONATED_PERMISSION_OPTION]
- : []),
- BLOCK_PERMISSION_OPTION,
- ];
-
- PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES.push(
- <ModalRoute
- key="impersonated/group/:groupId"
- path="impersonated/group/:groupId"
- modal={ImpersonationModal}
- />,
- );
-
- PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES.push(
- <ModalRoute
- key="impersonated/database/:impersonatedDatabaseId"
- path="impersonated/database/:impersonatedDatabaseId"
- modal={ImpersonationModal}
- />,
- );
-
- PLUGIN_ADVANCED_PERMISSIONS.isBlockPermission = (value) =>
- value === BLOCK_PERMISSION_OPTION.value;
-
- PLUGIN_ADVANCED_PERMISSIONS.getDatabaseLimitedAccessPermission = (value) => {
- if (value === IMPERSONATED_PERMISSION_OPTION.value) {
- return DataPermissionValue.UNRESTRICTED;
- }
-
- return null;
- };
- PLUGIN_ADVANCED_PERMISSIONS.isAccessPermissionDisabled = (value, subject) => {
- if (subject === "tables" || subject === "fields") {
- return value === DataPermissionValue.IMPERSONATED;
- } else {
- return false;
- }
- };
-
- PLUGIN_ADVANCED_PERMISSIONS.isRestrictivePermission = (value) => {
- return value === DataPermissionValue.BLOCKED;
- };
-
- PLUGIN_ADVANCED_PERMISSIONS.shouldShowViewDataColumn = true;
-
- PLUGIN_ADVANCED_PERMISSIONS.defaultViewDataPermission =
- DataPermissionValue.BLOCKED;
-
- PLUGIN_ADMIN_PERMISSIONS_DATABASE_POST_ACTIONS[
- DataPermissionValue.IMPERSONATED
- ] = getImpersonatedPostAction;
-
- PLUGIN_REDUCERS.advancedPermissionsPlugin = advancedPermissionsSlice.reducer;
-
- PLUGIN_DATA_PERMISSIONS.permissionsPayloadExtraSelectors.push(
- (state, data) => {
- const impersonations = getImpersonations(state);
- const impersonationGroupIds = impersonations.map((i) => `${i.group_id}`);
- return [{ impersonations }, impersonationGroupIds];
- },
- );
-
- PLUGIN_DATA_PERMISSIONS.hasChanges.push(
- (state) => getImpersonations(state).length > 0,
- );
-
- PLUGIN_ADMIN_PERMISSIONS_DATABASE_ACTIONS[
- DataPermissionValue.IMPERSONATED
- ].push({
- label: t`Edit Impersonated`,
- iconColor: "warning",
- icon: "database",
- actionCreator: (entityId, groupId, view) =>
- push(getEditImpersonationUrl(entityId, groupId, view)),
- });
-
- PLUGIN_DATA_PERMISSIONS.upgradeViewPermissionsIfNeeded =
- upgradeViewPermissionsIfNeeded;
-
- PLUGIN_DATA_PERMISSIONS.shouldRestrictNativeQueryPermissions =
- shouldRestrictNativeQueryPermissions;
+/**
+ * Initialize advanced permissions plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("advanced_permissions")) {
+ const addSelectedAdvancedPermission = (options, value) => {
+ if (value === IMPERSONATED_PERMISSION_OPTION.value) {
+ return [...options, IMPERSONATED_PERMISSION_OPTION];
+ }
+
+ return options;
+ };
+
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_OPTIONS.push(BLOCK_PERMISSION_OPTION);
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_OPTIONS.push(BLOCK_PERMISSION_OPTION);
+
+ PLUGIN_ADVANCED_PERMISSIONS.addTablePermissionOptions =
+ addSelectedAdvancedPermission;
+ PLUGIN_ADVANCED_PERMISSIONS.addSchemaPermissionOptions =
+ addSelectedAdvancedPermission;
+ PLUGIN_ADVANCED_PERMISSIONS.addDatabasePermissionOptions = (
+ options,
+ database,
+ ) => [
+ ...options,
+ ...(database.hasFeature("connection-impersonation")
+ ? [IMPERSONATED_PERMISSION_OPTION]
+ : []),
+ BLOCK_PERMISSION_OPTION,
+ ];
+
+ PLUGIN_ADMIN_PERMISSIONS_DATABASE_ROUTES.push(
+ <ModalRoute
+ key="impersonated/group/:groupId"
+ path="impersonated/group/:groupId"
+ modal={ImpersonationModal}
+ />,
+ );
+
+ PLUGIN_ADMIN_PERMISSIONS_DATABASE_GROUP_ROUTES.push(
+ <ModalRoute
+ key="impersonated/database/:impersonatedDatabaseId"
+ path="impersonated/database/:impersonatedDatabaseId"
+ modal={ImpersonationModal}
+ />,
+ );
+
+ PLUGIN_ADVANCED_PERMISSIONS.isBlockPermission = (value) =>
+ value === BLOCK_PERMISSION_OPTION.value;
+
+ PLUGIN_ADVANCED_PERMISSIONS.getDatabaseLimitedAccessPermission = (
+ value,
+ ) => {
+ if (value === IMPERSONATED_PERMISSION_OPTION.value) {
+ return DataPermissionValue.UNRESTRICTED;
+ }
+ return null;
+ };
+
+ PLUGIN_ADVANCED_PERMISSIONS.isAccessPermissionDisabled = (
+ value,
+ subject,
+ ) => {
+ if (subject === "tables" || subject === "fields") {
+ return value === DataPermissionValue.IMPERSONATED;
+ } else {
+ return false;
+ }
+ };
+
+ PLUGIN_ADVANCED_PERMISSIONS.isRestrictivePermission = (value) => {
+ return value === DataPermissionValue.BLOCKED;
+ };
+
+ PLUGIN_ADVANCED_PERMISSIONS.shouldShowViewDataColumn = true;
+ PLUGIN_ADVANCED_PERMISSIONS.defaultViewDataPermission =
+ DataPermissionValue.BLOCKED;
+
+ PLUGIN_ADMIN_PERMISSIONS_DATABASE_POST_ACTIONS[
+ DataPermissionValue.IMPERSONATED
+ ] = getImpersonatedPostAction;
+
+ PLUGIN_REDUCERS.advancedPermissionsPlugin =
+ advancedPermissionsSlice.reducer;
+
+ PLUGIN_DATA_PERMISSIONS.permissionsPayloadExtraSelectors.push(
+ (state, data) => {
+ const impersonations = getImpersonations(state);
+ const impersonationGroupIds = impersonations.map(
+ (i) => `${i.group_id}`,
+ );
+ return [{ impersonations }, impersonationGroupIds];
+ },
+ );
+
+ PLUGIN_DATA_PERMISSIONS.hasChanges.push(
+ (state) => getImpersonations(state).length > 0,
+ );
+
+ PLUGIN_ADMIN_PERMISSIONS_DATABASE_ACTIONS[
+ DataPermissionValue.IMPERSONATED
+ ].push({
+ label: t`Edit Impersonated`,
+ iconColor: "warning",
+ icon: "database",
+ actionCreator: (entityId, groupId, view) =>
+ push(getEditImpersonationUrl(entityId, groupId, view)),
+ });
+
+ PLUGIN_DATA_PERMISSIONS.upgradeViewPermissionsIfNeeded =
+ upgradeViewPermissionsIfNeeded;
+ PLUGIN_DATA_PERMISSIONS.shouldRestrictNativeQueryPermissions =
+ shouldRestrictNativeQueryPermissions;
+ }
}
const getDatabaseViewImpersonationModalUrl = (entityId, groupId) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/index.ts
index 3096262f748..7d7e41ccefd 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/ai-entity-analysis/index.ts
@@ -13,39 +13,45 @@ import { AIQuestionAnalysisButton } from "./components/AIQuestionAnalysisButton"
import { AIQuestionAnalysisSidebar } from "./components/AIQuestionAnalysisSidebar";
import { CHART_ANALYSIS_RENDER_FORMATS, canAnalyzeQuestion } from "./utils";
-if (hasPremiumFeature("ai_entity_analysis")) {
- PLUGIN_AI_ENTITY_ANALYSIS.AIQuestionAnalysisButton = AIQuestionAnalysisButton;
- PLUGIN_AI_ENTITY_ANALYSIS.AIQuestionAnalysisSidebar =
- AIQuestionAnalysisSidebar;
- PLUGIN_AI_ENTITY_ANALYSIS.AIDashboardAnalysisSidebar =
- AIDashboardAnalysisSidebar;
-
- PLUGIN_AI_ENTITY_ANALYSIS.canAnalyzeQuestion = (question: Question) => {
- return canAnalyzeQuestion(question.card().display);
- };
-
- PLUGIN_AI_ENTITY_ANALYSIS.chartAnalysisRenderFormats =
- CHART_ANALYSIS_RENDER_FORMATS;
-
- PLUGIN_DASHCARD_MENU.dashcardMenuItemGetters.push(
- (question, dashcardId, dispatch) => {
- if (!PLUGIN_AI_ENTITY_ANALYSIS.canAnalyzeQuestion(question)) {
- return null;
- }
-
- return {
- key: "MB_ANALYZE_CHART",
- iconName: "metabot",
- label: t`Analyze chart`,
- onClick: () => {
- if (dashcardId != null) {
- dispatch(showDashCardAnalysisSidebar(dashcardId));
- }
- },
- };
- },
- );
-}
-
export { AIQuestionAnalysisButton };
export { AIQuestionAnalysisSidebar };
+
+/**
+ * Initialize ai-entity-analysis plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("ai_entity_analysis")) {
+ PLUGIN_AI_ENTITY_ANALYSIS.AIQuestionAnalysisButton =
+ AIQuestionAnalysisButton;
+ PLUGIN_AI_ENTITY_ANALYSIS.AIQuestionAnalysisSidebar =
+ AIQuestionAnalysisSidebar;
+ PLUGIN_AI_ENTITY_ANALYSIS.AIDashboardAnalysisSidebar =
+ AIDashboardAnalysisSidebar;
+
+ PLUGIN_AI_ENTITY_ANALYSIS.canAnalyzeQuestion = (question: Question) => {
+ return canAnalyzeQuestion(question.card().display);
+ };
+
+ PLUGIN_AI_ENTITY_ANALYSIS.chartAnalysisRenderFormats =
+ CHART_ANALYSIS_RENDER_FORMATS;
+
+ PLUGIN_DASHCARD_MENU.dashcardMenuItemGetters.push(
+ (question, dashcardId, dispatch) => {
+ if (!PLUGIN_AI_ENTITY_ANALYSIS.canAnalyzeQuestion(question)) {
+ return null;
+ }
+
+ return {
+ key: "MB_ANALYZE_CHART",
+ iconName: "metabot",
+ label: t`Analyze chart`,
+ onClick: () => {
+ if (dashcardId != null) {
+ dispatch(showDashCardAnalysisSidebar(dashcardId));
+ }
+ },
+ };
+ },
+ );
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/index.ts
index c7c687e2394..1d561593c01 100644
--- a/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/ai-sql-fixer/index.ts
@@ -3,6 +3,11 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { FixSqlQueryButton } from "./components/FixSqlQueryButton";
-if (hasPremiumFeature("ai_sql_fixer")) {
- PLUGIN_AI_SQL_FIXER.FixSqlQueryButton = FixSqlQueryButton;
+/**
+ * Initialize ai-sql-fixer plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("ai_sql_fixer")) {
+ PLUGIN_AI_SQL_FIXER.FixSqlQueryButton = FixSqlQueryButton;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
index a9b39aefa5e..ac7b61bd216 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/index.ts
@@ -15,18 +15,26 @@ import {
settingsPermissionAllowedPathGetter,
} from "./utils";
-if (hasPremiumFeature("advanced_permissions")) {
- PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(monitoringPermissionAllowedPathGetter);
- PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(settingsPermissionAllowedPathGetter);
+/**
+ * Initialize application permissions plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("advanced_permissions")) {
+ PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(
+ monitoringPermissionAllowedPathGetter,
+ );
+ PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(settingsPermissionAllowedPathGetter);
- PLUGIN_APPLICATION_PERMISSIONS.getRoutes = getRoutes;
- PLUGIN_APPLICATION_PERMISSIONS.tabs = [
- { name: t`Application`, value: `application` },
- ];
+ PLUGIN_APPLICATION_PERMISSIONS.getRoutes = getRoutes;
+ PLUGIN_APPLICATION_PERMISSIONS.tabs = [
+ { name: t`Application`, value: `application` },
+ ];
- PLUGIN_APPLICATION_PERMISSIONS.selectors = {
- canAccessSettings,
- canManageSubscriptions,
- };
- PLUGIN_REDUCERS.applicationPermissionsPlugin = applicationPermissionsReducer;
+ PLUGIN_APPLICATION_PERMISSIONS.selectors = {
+ canAccessSettings,
+ canManageSubscriptions,
+ };
+ PLUGIN_REDUCERS.applicationPermissionsPlugin =
+ applicationPermissionsReducer;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js b/enterprise/frontend/src/metabase-enterprise/audit_app/index.js
index 73f0e91421f..b785f74927c 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/index.js
@@ -13,20 +13,25 @@ import { InsightsLink } from "./components/InsightsLink";
import { getUserMenuRotes } from "./routes";
import { isAuditDb } from "./utils";
-if (hasPremiumFeature("audit_app")) {
- PLUGIN_ADMIN_USER_MENU_ITEMS.push((user) => [
- <Menu.Item
- component={ForwardRefLink}
- to={`/admin/people/${user.id}/unsubscribe`}
- key="unsubscribe"
- >
- {t`Unsubscribe from all subscriptions / alerts`}
- </Menu.Item>,
- ]);
+/**
+ * Initialize audit app plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("audit_app")) {
+ // Add new menu item function
+ const menuItemFunction = (user) => [
+ <Menu.Item
+ component={ForwardRefLink}
+ to={`/admin/people/${user.id}/unsubscribe`}
+ key="unsubscribe"
+ >
+ {t`Unsubscribe from all subscriptions / alerts`}
+ </Menu.Item>,
+ ];
- PLUGIN_ADMIN_USER_MENU_ROUTES.push(getUserMenuRotes);
-
- PLUGIN_AUDIT.isAuditDb = isAuditDb;
-
- PLUGIN_AUDIT.InsightsLink = InsightsLink;
+ PLUGIN_ADMIN_USER_MENU_ITEMS.push(menuItemFunction);
+ PLUGIN_ADMIN_USER_MENU_ROUTES.push(getUserMenuRotes);
+ PLUGIN_AUDIT.isAuditDb = isAuditDb;
+ PLUGIN_AUDIT.InsightsLink = InsightsLink;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/index.ts b/enterprise/frontend/src/metabase-enterprise/auth/index.ts
index b45ee860f8c..44e4b702dd3 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/auth/index.ts
@@ -6,7 +6,9 @@ import {
PLUGIN_LDAP_FORM_FIELDS,
PLUGIN_REDUX_MIDDLEWARES,
} from "metabase/plugins";
+import type { AuthProvider } from "metabase/plugins/types";
import { hasPremiumFeature } from "metabase-enterprise/settings";
+import type { User } from "metabase-types/api";
import { createSessionMiddleware } from "../auth/middleware/session-middleware";
@@ -24,50 +26,62 @@ const SSO_PROVIDER = {
Button: SsoButton,
};
-if (hasPremiumFeature("sso_saml")) {
- PLUGIN_AUTH_PROVIDERS.SettingsSAMLForm = SettingsSAMLForm;
-}
-
-if (hasPremiumFeature("sso_jwt")) {
- PLUGIN_AUTH_PROVIDERS.SettingsJWTForm = SettingsJWTForm;
-}
-
+// Always set AuthSettingsPage - this doesn't depend on premium features
PLUGIN_AUTH_PROVIDERS.AuthSettingsPage = AuthSettingsPage;
-PLUGIN_AUTH_PROVIDERS.providers.push((providers) => {
- if (
- (hasPremiumFeature("sso_jwt") || hasPremiumFeature("sso_saml")) &&
- MetabaseSettings.get("other-sso-enabled?")
- ) {
- providers = [SSO_PROVIDER, ...providers];
+/**
+ * Initialize auth plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("sso_saml")) {
+ PLUGIN_AUTH_PROVIDERS.SettingsSAMLForm = SettingsSAMLForm;
}
- if (
- hasPremiumFeature("disable_password_login") &&
- !MetabaseSettings.isPasswordLoginEnabled() &&
- !MetabaseSettings.isLdapEnabled()
- ) {
- providers = providers.filter((p) => p.name !== "password");
+
+ if (hasPremiumFeature("sso_jwt")) {
+ PLUGIN_AUTH_PROVIDERS.SettingsJWTForm = SettingsJWTForm;
}
- return providers;
-});
-if (hasPremiumFeature("disable_password_login")) {
- PLUGIN_IS_PASSWORD_USER.push((user) =>
- Boolean(
- user.sso_source !== "google" &&
- user.sso_source !== "ldap" &&
- MetabaseSettings.isPasswordLoginEnabled(),
- ),
- );
-}
+ // Add provider function that handles SSO and password login
+ const enhancedProviderFunction = (providers: AuthProvider[]) => {
+ if (
+ (hasPremiumFeature("sso_jwt") || hasPremiumFeature("sso_saml")) &&
+ MetabaseSettings.get("other-sso-enabled?")
+ ) {
+ providers = [SSO_PROVIDER, ...providers];
+ }
+ if (
+ hasPremiumFeature("disable_password_login") &&
+ !MetabaseSettings.isPasswordLoginEnabled() &&
+ !MetabaseSettings.isLdapEnabled()
+ ) {
+ providers = providers.filter((p) => p.name !== "password");
+ }
+ return providers;
+ };
-if (hasPremiumFeature("sso_ldap")) {
- Object.assign(PLUGIN_LDAP_FORM_FIELDS, {
- LdapGroupMembershipFilter,
- LdapUserProvisioning,
- });
-}
+ PLUGIN_AUTH_PROVIDERS.providers.push(enhancedProviderFunction);
-if (hasPremiumFeature("session_timeout_config")) {
- PLUGIN_REDUX_MIDDLEWARES.push(createSessionMiddleware([LOGIN, LOGIN_GOOGLE]));
+ if (hasPremiumFeature("disable_password_login")) {
+ const passwordUserFunction = (user: User) =>
+ Boolean(
+ user.sso_source !== "google" &&
+ user.sso_source !== "ldap" &&
+ MetabaseSettings.isPasswordLoginEnabled(),
+ );
+
+ PLUGIN_IS_PASSWORD_USER.push(passwordUserFunction);
+ }
+
+ if (hasPremiumFeature("sso_ldap")) {
+ Object.assign(PLUGIN_LDAP_FORM_FIELDS, {
+ LdapGroupMembershipFilter,
+ LdapUserProvisioning,
+ });
+ }
+
+ if (hasPremiumFeature("session_timeout_config")) {
+ PLUGIN_REDUX_MIDDLEWARES.push(
+ createSessionMiddleware([LOGIN, LOGIN_GOOGLE]),
+ );
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx b/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
index 9d5be3a1814..d31912aa2f2 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
@@ -15,29 +15,34 @@ import {
} from "./constants";
import { hasQuestionCacheSection } from "./utils";
-if (hasPremiumFeature("cache_granular_controls")) {
- PLUGIN_CACHING.isGranularCachingEnabled = () => true;
- PLUGIN_CACHING.StrategyFormLauncherPanel = StrategyFormLauncherPanel;
- PLUGIN_CACHING.hasQuestionCacheSection = hasQuestionCacheSection;
- PLUGIN_CACHING.canOverrideRootStrategy = true;
- PLUGIN_CACHING.GranularControlsExplanation = GranularControlsExplanation;
- PLUGIN_CACHING.InvalidateNowButton = InvalidateNowButton;
- PLUGIN_CACHING.SidebarCacheSection = SidebarCacheSection;
- PLUGIN_CACHING.SidebarCacheForm = SidebarCacheForm;
- PLUGIN_CACHING.strategies = {
- inherit: PLUGIN_CACHING.strategies.inherit,
- duration: enterpriseOnlyCachingStrategies.duration,
- schedule: enterpriseOnlyCachingStrategies.schedule,
- ttl: PLUGIN_CACHING.strategies.ttl,
- nocache: PLUGIN_CACHING.strategies.nocache,
- };
- PLUGIN_CACHING.DashboardAndQuestionCachingTab =
- DashboardAndQuestionCachingTab;
- PLUGIN_CACHING.StrategyEditorForQuestionsAndDashboards =
- StrategyEditorForQuestionsAndDashboards;
- PLUGIN_CACHING.getTabMetadata = getEnterprisePerformanceTabMetadata;
-}
+/**
+ * Initialize caching plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("cache_granular_controls")) {
+ PLUGIN_CACHING.isGranularCachingEnabled = () => true;
+ PLUGIN_CACHING.StrategyFormLauncherPanel = StrategyFormLauncherPanel;
+ PLUGIN_CACHING.hasQuestionCacheSection = hasQuestionCacheSection;
+ PLUGIN_CACHING.canOverrideRootStrategy = true;
+ PLUGIN_CACHING.GranularControlsExplanation = GranularControlsExplanation;
+ PLUGIN_CACHING.InvalidateNowButton = InvalidateNowButton;
+ PLUGIN_CACHING.SidebarCacheSection = SidebarCacheSection;
+ PLUGIN_CACHING.SidebarCacheForm = SidebarCacheForm;
+ PLUGIN_CACHING.strategies = {
+ inherit: PLUGIN_CACHING.strategies.inherit,
+ duration: enterpriseOnlyCachingStrategies.duration,
+ schedule: enterpriseOnlyCachingStrategies.schedule,
+ ttl: PLUGIN_CACHING.strategies.ttl,
+ nocache: PLUGIN_CACHING.strategies.nocache,
+ };
+ PLUGIN_CACHING.DashboardAndQuestionCachingTab =
+ DashboardAndQuestionCachingTab;
+ PLUGIN_CACHING.StrategyEditorForQuestionsAndDashboards =
+ StrategyEditorForQuestionsAndDashboards;
+ PLUGIN_CACHING.getTabMetadata = getEnterprisePerformanceTabMetadata;
+ }
-if (hasPremiumFeature("cache_preemptive")) {
- PLUGIN_CACHING.PreemptiveCachingSwitch = PreemptiveCachingSwitch;
+ if (hasPremiumFeature("cache_preemptive")) {
+ PLUGIN_CACHING.PreemptiveCachingSwitch = PreemptiveCachingSwitch;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx b/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
index 407b829bd76..df8906f4bee 100644
--- a/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/clean_up/index.tsx
@@ -14,66 +14,71 @@ import { CleanupCollectionModal } from "./CleanupCollectionModal";
import { getDateFilterValue } from "./CleanupCollectionModal/utils";
import { canCleanUp } from "./utils";
-if (hasPremiumFeature("collection_cleanup")) {
- PLUGIN_COLLECTIONS.canCleanUp = canCleanUp;
+/**
+ * Initialize clean_up plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("collection_cleanup")) {
+ PLUGIN_COLLECTIONS.canCleanUp = canCleanUp;
- PLUGIN_COLLECTIONS.useGetCleanUpMenuItems = (collection) => {
- const canCleanupCollection = canCleanUp(collection);
+ PLUGIN_COLLECTIONS.useGetCleanUpMenuItems = (collection) => {
+ const canCleanupCollection = canCleanUp(collection);
- const { currentData: collectionItems } = useListCollectionItemsQuery(
- canCleanupCollection
- ? {
- id: collection.id,
- limit: 0, // only fetch pagination info
- }
- : skipToken,
- );
+ const { currentData: collectionItems } = useListCollectionItemsQuery(
+ canCleanupCollection
+ ? {
+ id: collection.id,
+ limit: 0, // only fetch pagination info
+ }
+ : skipToken,
+ );
- const hasCollectionItems = (collectionItems?.total ?? 0) > 0;
+ const hasCollectionItems = (collectionItems?.total ?? 0) > 0;
- const { currentData: staleItems } = useListStaleCollectionItemsQuery(
- canCleanupCollection && hasCollectionItems
- ? {
- id: collection.id,
- limit: 0, // only fetch pagination info
- before_date: getDateFilterValue("three-months"), // set to 3 months ago
- }
- : skipToken,
- );
+ const { currentData: staleItems } = useListStaleCollectionItemsQuery(
+ canCleanupCollection && hasCollectionItems
+ ? {
+ id: collection.id,
+ limit: 0, // only fetch pagination info
+ before_date: getDateFilterValue("three-months"), // set to 3 months ago
+ }
+ : skipToken,
+ );
+
+ const hasStaleItems = (staleItems?.total ?? 0) > 0;
- const hasStaleItems = (staleItems?.total ?? 0) > 0;
+ if (!canCleanupCollection || !hasCollectionItems) {
+ return {
+ menuItems: [],
+ };
+ }
- if (!canCleanupCollection || !hasCollectionItems) {
return {
- menuItems: [],
+ menuItems: [
+ <UserHasSeen
+ key="collections-cleanup"
+ id="clean-stale-items"
+ withContext={hasStaleItems}
+ >
+ {() => (
+ <Menu.Item
+ leftSection={<Icon name="archive" />}
+ component={ForwardRefLink}
+ to={`${Urls.collection(collection)}/cleanup`}
+ rightSection={
+ hasStaleItems ? <Badge>{t`Recommended`}</Badge> : null
+ }
+ >
+ {t`Clear out unused items`}
+ </Menu.Item>
+ )}
+ </UserHasSeen>,
+ ],
};
- }
-
- return {
- menuItems: [
- <UserHasSeen
- key="collections-cleanup"
- id="clean-stale-items"
- withContext={hasStaleItems}
- >
- {() => (
- <Menu.Item
- leftSection={<Icon name="archive" />}
- component={ForwardRefLink}
- to={`${Urls.collection(collection)}/cleanup`}
- rightSection={
- hasStaleItems ? <Badge>{t`Recommended`}</Badge> : null
- }
- >
- {t`Clear out unused items`}
- </Menu.Item>
- )}
- </UserHasSeen>,
- ],
};
- };
- PLUGIN_COLLECTIONS.cleanUpRoute = (
- <ModalRoute path="cleanup" modal={CleanupCollectionModal} />
- );
+ PLUGIN_COLLECTIONS.cleanUpRoute = (
+ <ModalRoute path="cleanup" modal={CleanupCollectionModal} />
+ );
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/collections/index.tsx b/enterprise/frontend/src/metabase-enterprise/collections/index.tsx
index dee1a36c3bc..0c05b276159 100644
--- a/enterprise/frontend/src/metabase-enterprise/collections/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/collections/index.tsx
@@ -27,71 +27,68 @@ import {
isSyncedCollection,
} from "./utils";
-if (hasPremiumFeature("remote_sync")) {
- PLUGIN_COLLECTIONS.isSyncedCollection = isSyncedCollection;
-}
-
-if (hasPremiumFeature("official_collections")) {
- PLUGIN_COLLECTIONS.isRegularCollection = isRegularCollection;
-
- PLUGIN_COLLECTIONS.REGULAR_COLLECTION = REGULAR_COLLECTION;
-
- PLUGIN_COLLECTIONS.AUTHORITY_LEVEL = AUTHORITY_LEVELS;
-
- PLUGIN_COLLECTIONS.getIcon = getIcon;
+/**
+ * Initialize collections plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("remote_sync")) {
+ PLUGIN_COLLECTIONS.isSyncedCollection = isSyncedCollection;
+ }
- PLUGIN_COLLECTIONS.getAuthorityLevelMenuItems = (
- collection: Collection,
- onUpdate: (collection: Collection, values: Partial<Collection>) => void,
- ) => {
- if (isRegularCollection(collection)) {
- return [
- <Menu.Item
- key="collection-make-official"
- leftSection={<Icon name={OFFICIAL_COLLECTION.icon} />}
- onClick={() =>
- onUpdate(collection, {
- authority_level: OFFICIAL_COLLECTION.type,
- })
- }
- >{t`Make collection official`}</Menu.Item>,
- ];
- } else {
- return [
- <Menu.Item
- key="collection-remove-official"
- leftSection={<Icon name="close" />}
- onClick={() =>
- onUpdate(collection, {
- authority_level: REGULAR_COLLECTION.type,
- })
- }
- >{t`Remove Official badge`}</Menu.Item>,
- ];
- }
- };
-
- PLUGIN_COLLECTIONS.filterOutItemsFromInstanceAnalytics =
- filterOutItemsFromInstanceAnalytics;
-
- PLUGIN_COLLECTION_COMPONENTS.FormCollectionAuthorityLevelPicker =
- FormCollectionAuthorityLevel;
-
- PLUGIN_COLLECTION_COMPONENTS.CollectionAuthorityLevelIcon =
- CollectionAuthorityLevelIcon;
-
- PLUGIN_COLLECTION_COMPONENTS.CollectionAuthorityLevelDisplay =
- CollectionAuthorityLevelDisplay;
-}
+ if (hasPremiumFeature("official_collections")) {
+ PLUGIN_COLLECTIONS.isRegularCollection = isRegularCollection;
+ PLUGIN_COLLECTIONS.REGULAR_COLLECTION = REGULAR_COLLECTION;
+ PLUGIN_COLLECTIONS.AUTHORITY_LEVEL = AUTHORITY_LEVELS;
+ PLUGIN_COLLECTIONS.getIcon = getIcon;
-if (hasPremiumFeature("audit_app")) {
- PLUGIN_COLLECTION_COMPONENTS.CollectionInstanceAnalyticsIcon =
- CollectionInstanceAnalyticsIcon;
+ PLUGIN_COLLECTIONS.getAuthorityLevelMenuItems = (
+ collection: Collection,
+ onUpdate: (collection: Collection, values: Partial<Collection>) => void,
+ ) => {
+ if (isRegularCollection(collection)) {
+ return [
+ <Menu.Item
+ key="collection-make-official"
+ leftSection={<Icon name={OFFICIAL_COLLECTION.icon} />}
+ onClick={() =>
+ onUpdate(collection, {
+ authority_level: OFFICIAL_COLLECTION.type,
+ })
+ }
+ >{t`Make collection official`}</Menu.Item>,
+ ];
+ } else {
+ return [
+ <Menu.Item
+ key="collection-remove-official"
+ leftSection={<Icon name="close" />}
+ onClick={() =>
+ onUpdate(collection, {
+ authority_level: REGULAR_COLLECTION.type,
+ })
+ }
+ >{t`Remove Official badge`}</Menu.Item>,
+ ];
+ }
+ };
- PLUGIN_COLLECTIONS.getCollectionType = getCollectionType;
- PLUGIN_COLLECTIONS.useGetDefaultCollectionId = useGetDefaultCollectionId;
- PLUGIN_COLLECTIONS.CUSTOM_INSTANCE_ANALYTICS_COLLECTION_ENTITY_ID =
- CUSTOM_INSTANCE_ANALYTICS_COLLECTION_ENTITY_ID;
+ PLUGIN_COLLECTIONS.filterOutItemsFromInstanceAnalytics =
+ filterOutItemsFromInstanceAnalytics;
+ PLUGIN_COLLECTION_COMPONENTS.FormCollectionAuthorityLevelPicker =
+ FormCollectionAuthorityLevel;
+ PLUGIN_COLLECTION_COMPONENTS.CollectionAuthorityLevelIcon =
+ CollectionAuthorityLevelIcon;
+ PLUGIN_COLLECTION_COMPONENTS.CollectionAuthorityLevelDisplay =
+ CollectionAuthorityLevelDisplay;
+ }
- PLUGIN_COLLECTIONS.INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE = t`This instance analytics collection is read-only for admin users`;
+ if (hasPremiumFeature("audit_app")) {
+ PLUGIN_COLLECTION_COMPONENTS.CollectionInstanceAnalyticsIcon =
+ CollectionInstanceAnalyticsIcon;
+ PLUGIN_COLLECTIONS.getCollectionType = getCollectionType;
+ PLUGIN_COLLECTIONS.useGetDefaultCollectionId = useGetDefaultCollectionId;
+ PLUGIN_COLLECTIONS.CUSTOM_INSTANCE_ANALYTICS_COLLECTION_ENTITY_ID =
+ CUSTOM_INSTANCE_ANALYTICS_COLLECTION_ENTITY_ID;
+ PLUGIN_COLLECTIONS.INSTANCE_ANALYTICS_ADMIN_READONLY_MESSAGE = t`This instance analytics collection is read-only for admin users`;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts b/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts
index c5fa57a4f77..5fcb9b88957 100644
--- a/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/content_translation/index.ts
@@ -11,17 +11,22 @@ import {
useTranslateSeries,
} from "./utils";
-if (hasPremiumFeature("content_translation")) {
- Object.assign(PLUGIN_CONTENT_TRANSLATION, {
- isEnabled: true,
- useSortByContentTranslation,
- useTranslateContent,
- useTranslateFieldValuesInHoveredObject,
- useTranslateSeries,
- setEndpointsForStaticEmbedding: (encodedToken: string) => {
- contentTranslationEndpoints.getDictionary = `/api/ee/content-translation/dictionary/${encodedToken}`;
- },
- translateDisplayNames,
- ContentTranslationConfiguration,
- });
+/**
+ * Initialize content translation plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("content_translation")) {
+ Object.assign(PLUGIN_CONTENT_TRANSLATION, {
+ isEnabled: true,
+ useSortByContentTranslation,
+ useTranslateContent,
+ useTranslateFieldValuesInHoveredObject,
+ useTranslateSeries,
+ setEndpointsForStaticEmbedding: (encodedToken: string) => {
+ contentTranslationEndpoints.getDictionary = `/api/ee/content-translation/dictionary/${encodedToken}`;
+ },
+ translateDisplayNames,
+ ContentTranslationConfiguration,
+ });
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/content_verification/index.ts b/enterprise/frontend/src/metabase-enterprise/content_verification/index.ts
index 1e318383b25..f77e4966e63 100644
--- a/enterprise/frontend/src/metabase-enterprise/content_verification/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/content_verification/index.ts
@@ -5,15 +5,18 @@ import { VerifiedFilter } from "./VerifiedFilter";
import { MetricFilterControls, getDefaultMetricFilters } from "./metrics";
import { ModelFilterControls, getDefaultModelFilters } from "./models";
-if (hasPremiumFeature("content_verification")) {
- Object.assign(PLUGIN_CONTENT_VERIFICATION, {
- contentVerificationEnabled: true,
- VerifiedFilter,
-
- ModelFilterControls,
- getDefaultModelFilters,
-
- getDefaultMetricFilters,
- MetricFilterControls,
- });
+/**
+ * Initialize content verification plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("content_verification")) {
+ Object.assign(PLUGIN_CONTENT_VERIFICATION, {
+ contentVerificationEnabled: true,
+ VerifiedFilter,
+ ModelFilterControls,
+ getDefaultModelFilters,
+ getDefaultMetricFilters,
+ MetricFilterControls,
+ });
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/database_replication/index.tsx b/enterprise/frontend/src/metabase-enterprise/database_replication/index.tsx
index 7776f894192..9ecee6d2417 100644
--- a/enterprise/frontend/src/metabase-enterprise/database_replication/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/database_replication/index.tsx
@@ -3,12 +3,17 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { DatabaseReplicationSection } from "./DatabaseReplicationSection";
-if (
- hasPremiumFeature("hosting") &&
- hasPremiumFeature("attached_dwh") &&
- hasPremiumFeature("etl_connections") &&
- hasPremiumFeature("etl_connections_pg")
-) {
- PLUGIN_DATABASE_REPLICATION.DatabaseReplicationSection =
- DatabaseReplicationSection;
+/**
+ * Initialize database replication plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (
+ hasPremiumFeature("hosting") &&
+ hasPremiumFeature("attached_dwh") &&
+ hasPremiumFeature("etl_connections") &&
+ hasPremiumFeature("etl_connections_pg")
+ ) {
+ PLUGIN_DATABASE_REPLICATION.DatabaseReplicationSection =
+ DatabaseReplicationSection;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/database_routing/index.tsx b/enterprise/frontend/src/metabase-enterprise/database_routing/index.tsx
index 3a7ac6b81c9..b61dd7f09e5 100644
--- a/enterprise/frontend/src/metabase-enterprise/database_routing/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/database_routing/index.tsx
@@ -10,40 +10,45 @@ import { DestinationDatabasesModal } from "./DestinationDatabasesModal";
import { RemoveDestinationDatabaseModal } from "./RemoveDestinationDatabaseModal";
import { useRedirectDestinationDatabase } from "./hooks";
-if (hasPremiumFeature("database_routing")) {
- PLUGIN_DB_ROUTING.DatabaseRoutingSection = DatabaseRoutingSection;
-
- PLUGIN_DB_ROUTING.getDatabaseNameFieldProps = (isSlug) => {
- if (!isSlug) {
- return {};
- }
-
- return {
- label: t`Slug`,
- // eslint-disable-next-line no-literal-metabase-strings -- Admin settings
- description: t`Metabase will route queries to this database when the user attribute value matches this slug.`, // Metabase will use this value to map to the user attribute you specify to swap queries at run time`,
- placeholder: t`For example, pro-users`,
+/**
+ * Initialize database_routing plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("database_routing")) {
+ PLUGIN_DB_ROUTING.DatabaseRoutingSection = DatabaseRoutingSection;
+
+ PLUGIN_DB_ROUTING.getDatabaseNameFieldProps = (isSlug) => {
+ if (!isSlug) {
+ return {};
+ }
+
+ return {
+ label: t`Slug`,
+ // eslint-disable-next-line no-literal-metabase-strings -- Admin settings
+ description: t`Metabase will route queries to this database when the user attribute value matches this slug.`, // Metabase will use this value to map to the user attribute you specify to swap queries at run time`,
+ placeholder: t`For example, pro-users`,
+ };
};
- };
- PLUGIN_DB_ROUTING.getPrimaryDBEngineFieldState = (db) =>
- db.router_user_attribute ? "disabled" : "default";
+ PLUGIN_DB_ROUTING.getPrimaryDBEngineFieldState = (db) =>
+ db.router_user_attribute ? "disabled" : "default";
- PLUGIN_DB_ROUTING.useRedirectDestinationDatabase =
- useRedirectDestinationDatabase;
+ PLUGIN_DB_ROUTING.useRedirectDestinationDatabase =
+ useRedirectDestinationDatabase;
- PLUGIN_DB_ROUTING.getDestinationDatabaseRoutes = (IsAdmin: any) => (
- <Route path="destination-databases">
- <IndexRoute component={DestinationDatabasesModal} />
- <Route component={IsAdmin}>
- <Route path="create" component={DestinationDatabaseConnectionModal} />
- </Route>
- <Route path=":destinationDatabaseId">
- <IndexRoute component={DestinationDatabaseConnectionModal} />
+ PLUGIN_DB_ROUTING.getDestinationDatabaseRoutes = (IsAdmin: any) => (
+ <Route path="destination-databases">
+ <IndexRoute component={DestinationDatabasesModal} />
<Route component={IsAdmin}>
- <Route path="remove" component={RemoveDestinationDatabaseModal} />
+ <Route path="create" component={DestinationDatabaseConnectionModal} />
+ </Route>
+ <Route path=":destinationDatabaseId">
+ <IndexRoute component={DestinationDatabaseConnectionModal} />
+ <Route component={IsAdmin}>
+ <Route path="remove" component={RemoveDestinationDatabaseModal} />
+ </Route>
</Route>
</Route>
- </Route>
- );
+ );
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/index.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/index.ts
index 39e00eb354b..c687d30fa5b 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/index.ts
@@ -9,14 +9,20 @@ import { useCheckSnippetDependencies } from "./hooks/use-check-snippet-dependenc
import { useCheckTransformDependencies } from "./hooks/use-check-transform-dependencies";
import { DependencyGraphPage } from "./pages/DependencyGraphPage";
-if (hasPremiumFeature("dependencies")) {
- PLUGIN_DEPENDENCIES.isEnabled = true;
- PLUGIN_DEPENDENCIES.DependencyGraphPage = DependencyGraphPage;
- PLUGIN_DEPENDENCIES.CheckDependenciesForm = CheckDependenciesForm;
- PLUGIN_DEPENDENCIES.CheckDependenciesModal = CheckDependenciesModal;
- PLUGIN_DEPENDENCIES.CheckDependenciesTitle = CheckDependenciesTitle;
- PLUGIN_DEPENDENCIES.useCheckCardDependencies = useCheckCardDependencies;
- PLUGIN_DEPENDENCIES.useCheckSnippetDependencies = useCheckSnippetDependencies;
- PLUGIN_DEPENDENCIES.useCheckTransformDependencies =
- useCheckTransformDependencies;
+/**
+ * Initialize dependencies plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("dependencies")) {
+ PLUGIN_DEPENDENCIES.isEnabled = true;
+ PLUGIN_DEPENDENCIES.DependencyGraphPage = DependencyGraphPage;
+ PLUGIN_DEPENDENCIES.CheckDependenciesForm = CheckDependenciesForm;
+ PLUGIN_DEPENDENCIES.CheckDependenciesModal = CheckDependenciesModal;
+ PLUGIN_DEPENDENCIES.CheckDependenciesTitle = CheckDependenciesTitle;
+ PLUGIN_DEPENDENCIES.useCheckCardDependencies = useCheckCardDependencies;
+ PLUGIN_DEPENDENCIES.useCheckSnippetDependencies =
+ useCheckSnippetDependencies;
+ PLUGIN_DEPENDENCIES.useCheckTransformDependencies =
+ useCheckTransformDependencies;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/documents/index.ts b/enterprise/frontend/src/metabase-enterprise/documents/index.ts
index 82be98a4ca6..6fb7e1eea0c 100644
--- a/enterprise/frontend/src/metabase-enterprise/documents/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/documents/index.ts
@@ -15,15 +15,20 @@ import {
getSidebarOpen,
} from "./selectors";
-if (hasPremiumFeature("documents")) {
- PLUGIN_DOCUMENTS.getRoutes = getRoutes;
- PLUGIN_DOCUMENTS.shouldShowDocumentInNewItemMenu = () => true;
- PLUGIN_DOCUMENTS.getCurrentDocument = getCurrentDocument;
- PLUGIN_DOCUMENTS.getSidebarOpen = getSidebarOpen;
- PLUGIN_DOCUMENTS.getCommentSidebarOpen = getCommentSidebarOpen;
- PLUGIN_DOCUMENTS.DocumentCopyForm = DocumentCopyForm;
+/**
+ * Initialize documents plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("documents")) {
+ PLUGIN_DOCUMENTS.getRoutes = getRoutes;
+ PLUGIN_DOCUMENTS.shouldShowDocumentInNewItemMenu = () => true;
+ PLUGIN_DOCUMENTS.getCurrentDocument = getCurrentDocument;
+ PLUGIN_DOCUMENTS.getSidebarOpen = getSidebarOpen;
+ PLUGIN_DOCUMENTS.getCommentSidebarOpen = getCommentSidebarOpen;
+ PLUGIN_DOCUMENTS.DocumentCopyForm = DocumentCopyForm;
- PLUGIN_REDUCERS.documents = documentsReducer;
+ PLUGIN_REDUCERS.documents = documentsReducer;
- PLUGIN_ENTITIES.entities["documents"] = Documents;
+ PLUGIN_ENTITIES.entities["documents"] = Documents;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding-sdk/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding-sdk/index.ts
index 25382cec7e0..32e8e80c320 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding-sdk/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding-sdk/index.ts
@@ -1,6 +1,11 @@
import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-if (hasPremiumFeature("embedding_sdk")) {
- PLUGIN_EMBEDDING_SDK.isEnabled = () => true;
+/**
+ * Initialize embedding SDK plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("embedding_sdk")) {
+ PLUGIN_EMBEDDING_SDK.isEnabled = () => true;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding/index.ts
index 13c6084499f..fe53d4c783d 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding/index.ts
@@ -6,18 +6,22 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { InteractiveEmbeddingSettings } from "./components/InteractiveEmbeddingSettings";
-if (hasPremiumFeature("embedding")) {
- PLUGIN_EMBEDDING.isEnabled = () => true;
- PLUGIN_EMBEDDING.isInteractiveEmbeddingEnabled =
- isInteractiveEmbeddingEnabled;
-
- PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettings =
- InteractiveEmbeddingSettings;
-}
-
/**
* We can't gate this component behind a feature flag, because SDK users could
* use the SDK without a valid license and doesn't contain any feature flags.
*/
PLUGIN_EMBEDDING.SimpleDataPicker = SimpleDataPicker;
PLUGIN_EMBEDDING.DataSourceSelector = DataSourceSelector;
+
+/**
+ * Initialize embedding plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("embedding")) {
+ PLUGIN_EMBEDDING.isEnabled = () => true;
+ PLUGIN_EMBEDDING.isInteractiveEmbeddingEnabled =
+ isInteractiveEmbeddingEnabled;
+ PLUGIN_ADMIN_SETTINGS.InteractiveEmbeddingSettings =
+ InteractiveEmbeddingSettings;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
index a88d615e1be..828c56b2382 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup/index.ts
@@ -3,11 +3,16 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { SdkIframeEmbedSetupModal } from "./components/SdkIframeEmbedSetupModal";
-// Feature gate the embed setup for gradual rollouts.
-// In the future, we may drop this to enable users to try out new iframe embedding.
-if (hasPremiumFeature("embedding_simple")) {
- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = () => true;
- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.shouldShowEmbedInNewItemMenu = () => true;
- PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetupModal =
- SdkIframeEmbedSetupModal;
+/**
+ * Initialize embedding iframe SDK setup plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ // Feature gate the embed setup for gradual rollouts.
+ // In the future, we may drop this to enable users to try out new iframe embedding.
+ if (hasPremiumFeature("embedding_simple")) {
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.isFeatureEnabled = () => true;
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.shouldShowEmbedInNewItemMenu = () => true;
+ PLUGIN_EMBEDDING_IFRAME_SDK_SETUP.SdkIframeEmbedSetupModal =
+ SdkIframeEmbedSetupModal;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/index.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/index.ts
index 4e59f613bff..55f5c2ed94d 100644
--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/index.ts
@@ -15,25 +15,31 @@ import {
getDataColumns,
} from "./utils";
-if (hasPremiumFeature("advanced_permissions")) {
- PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(dataModelPermissionAllowedPathGetter);
- PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(
- databaseManagementPermissionAllowedPathGetter,
- );
+/**
+ * Initialize feature level permissions plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("advanced_permissions")) {
+ PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(
+ dataModelPermissionAllowedPathGetter,
+ );
+ PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(
+ databaseManagementPermissionAllowedPathGetter,
+ );
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.getFeatureLevelDataPermissions =
- getFeatureLevelDataPermissions;
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.getFeatureLevelDataPermissions =
+ getFeatureLevelDataPermissions;
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDataColumns = getDataColumns;
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDownloadWidgetMessageOverride =
+ getDownloadWidgetMessageOverride;
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.canDownloadResults = canDownloadResults;
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDataColumns = getDataColumns;
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.getDownloadWidgetMessageOverride =
- getDownloadWidgetMessageOverride;
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.canDownloadResults = canDownloadResults;
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps = {
+ include_editable_data_model: true,
+ };
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps = {
- include_editable_data_model: true,
- };
-
- PLUGIN_FEATURE_LEVEL_PERMISSIONS.databaseDetailsQueryProps = {
- exclude_uneditable_details: true,
- };
+ PLUGIN_FEATURE_LEVEL_PERMISSIONS.databaseDetailsQueryProps = {
+ exclude_uneditable_details: true,
+ };
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/group_managers/index.ts b/enterprise/frontend/src/metabase-enterprise/group_managers/index.ts
index a1a02965381..8bcd9c9f297 100644
--- a/enterprise/frontend/src/metabase-enterprise/group_managers/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/group_managers/index.ts
@@ -17,18 +17,25 @@ import {
groupManagerAllowedPathGetter,
} from "./utils";
-if (hasPremiumFeature("advanced_permissions")) {
- PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(groupManagerAllowedPathGetter);
+/**
+ * Initialize group_managers plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("advanced_permissions")) {
+ PLUGIN_ADMIN_ALLOWED_PATH_GETTERS.push(groupManagerAllowedPathGetter);
- PLUGIN_GROUP_MANAGERS.UserTypeCell = UserTypeCell;
- PLUGIN_GROUP_MANAGERS.UserTypeToggle = UserTypeToggle;
+ PLUGIN_GROUP_MANAGERS.UserTypeCell = UserTypeCell;
+ PLUGIN_GROUP_MANAGERS.UserTypeToggle = UserTypeToggle;
- PLUGIN_GROUP_MANAGERS.getRemoveMembershipConfirmation =
- getRemoveMembershipConfirmation;
- PLUGIN_GROUP_MANAGERS.getChangeMembershipConfirmation =
- getChangeMembershipConfirmation;
+ PLUGIN_GROUP_MANAGERS.getRemoveMembershipConfirmation =
+ getRemoveMembershipConfirmation;
+ PLUGIN_GROUP_MANAGERS.getChangeMembershipConfirmation =
+ getChangeMembershipConfirmation;
- PLUGIN_GROUP_MANAGERS.deleteGroup = deleteGroup;
- PLUGIN_GROUP_MANAGERS.confirmDeleteMembershipAction = confirmDeleteMembership;
- PLUGIN_GROUP_MANAGERS.confirmUpdateMembershipAction = confirmUpdateMembership;
+ PLUGIN_GROUP_MANAGERS.deleteGroup = deleteGroup;
+ PLUGIN_GROUP_MANAGERS.confirmDeleteMembershipAction =
+ confirmDeleteMembership;
+ PLUGIN_GROUP_MANAGERS.confirmUpdateMembershipAction =
+ confirmUpdateMembership;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index c090a3bd035..55ea246f7ae 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -17,59 +17,6 @@ import { MetabotToggleButton } from "./components/MetabotToggleButton";
import { MetabotContext, MetabotProvider, defaultContext } from "./context";
import { getMetabotVisible, metabotReducer } from "./state";
-if (hasPremiumFeature("metabot_v3")) {
- PLUGIN_METABOT.isEnabled = () => true;
- PLUGIN_METABOT.Metabot = Metabot;
-
- PLUGIN_METABOT.getMetabotRoutes = getMetabotQuickLinks;
-
- PLUGIN_METABOT.getAdminPaths = () => [
- {
- name: t`AI`,
- path: "/admin/metabot",
- key: "metabot",
- },
- ];
- PLUGIN_METABOT.getAdminRoutes = () => (
- <Route
- key="metabot"
- path="metabot"
- component={createAdminRouteGuard("metabot")}
- >
- <IndexRoute component={MetabotAdminPage} />
- <Route path=":metabotId" component={MetabotAdminPage} />
- </Route>
- );
-
- PLUGIN_METABOT.defaultMetabotContextValue = defaultContext;
- PLUGIN_METABOT.MetabotContext = MetabotContext;
- PLUGIN_METABOT.getMetabotProvider = () => MetabotProvider;
- // TODO: make enterprise store + fix type
- PLUGIN_METABOT.getMetabotVisible =
- getMetabotVisible as unknown as typeof PLUGIN_METABOT.getMetabotVisible;
-
- PLUGIN_METABOT.MetabotToggleButton = MetabotToggleButton;
- PLUGIN_METABOT.MetabotAppBarButton = MetabotAppBarButton;
- PLUGIN_METABOT.MetabotAdminAppBarButton = MetabotAdminAppBarButton;
-
- PLUGIN_REDUCERS.metabotPlugin = metabotReducer;
-} else if (hasPremiumFeature("offer_metabase_ai")) {
- PLUGIN_METABOT.getAdminPaths = () => [
- {
- name: t`AI`,
- path: "/admin/metabot",
- key: "metabot",
- },
- ];
- PLUGIN_METABOT.getAdminRoutes = () => (
- <Route path="metabot" component={createAdminRouteGuard("metabot")}>
- <Route title={t`AI`} component={AdminSettingsLayout}>
- <IndexRoute component={MetabotPurchasePage} />
- </Route>
- </Route>
- );
-}
-
/**
* This is for Metabot in embedding
*
@@ -82,3 +29,55 @@ PLUGIN_METABOT.defaultMetabotContextValue = defaultContext;
PLUGIN_METABOT.MetabotContext = MetabotContext;
PLUGIN_REDUCERS.metabotPlugin = metabotReducer;
+
+/**
+ * Initialize metabot plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("metabot_v3")) {
+ PLUGIN_METABOT.isEnabled = () => true;
+ PLUGIN_METABOT.Metabot = Metabot;
+ PLUGIN_METABOT.getMetabotRoutes = getMetabotQuickLinks;
+
+ PLUGIN_METABOT.getAdminPaths = () => [
+ {
+ name: t`AI`,
+ path: "/admin/metabot",
+ key: "metabot",
+ },
+ ];
+ PLUGIN_METABOT.getAdminRoutes = () => (
+ <Route
+ key="metabot"
+ path="metabot"
+ component={createAdminRouteGuard("metabot")}
+ >
+ <IndexRoute component={MetabotAdminPage} />
+ <Route path=":metabotId" component={MetabotAdminPage} />
+ </Route>
+ );
+
+ // TODO: make enterprise store + fix type
+ PLUGIN_METABOT.getMetabotVisible =
+ getMetabotVisible as unknown as typeof PLUGIN_METABOT.getMetabotVisible;
+
+ PLUGIN_METABOT.MetabotToggleButton = MetabotToggleButton;
+ PLUGIN_METABOT.MetabotAppBarButton = MetabotAppBarButton;
+ PLUGIN_METABOT.MetabotAdminAppBarButton = MetabotAdminAppBarButton;
+ } else if (hasPremiumFeature("offer_metabase_ai")) {
+ PLUGIN_METABOT.getAdminPaths = () => [
+ {
+ name: t`AI`,
+ path: "/admin/metabot",
+ key: "metabot",
+ },
+ ];
+ PLUGIN_METABOT.getAdminRoutes = () => (
+ <Route path="metabot" component={createAdminRouteGuard("metabot")}>
+ <Route title={t`AI`} component={AdminSettingsLayout}>
+ <IndexRoute component={MetabotPurchasePage} />
+ </Route>
+ </Route>
+ );
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/model_persistence/index.ts b/enterprise/frontend/src/metabase-enterprise/model_persistence/index.ts
index 5527b3b956b..b498d65b6bb 100644
--- a/enterprise/frontend/src/metabase-enterprise/model_persistence/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/model_persistence/index.ts
@@ -3,7 +3,12 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { ModelCacheToggle } from "./components/ModelCacheControl";
-if (hasPremiumFeature("cache_granular_controls")) {
- PLUGIN_MODEL_PERSISTENCE.isModelLevelPersistenceEnabled = () => true;
- PLUGIN_MODEL_PERSISTENCE.ModelCacheToggle = ModelCacheToggle;
+/**
+ * Initialize model persistence plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("cache_granular_controls")) {
+ PLUGIN_MODEL_PERSISTENCE.isModelLevelPersistenceEnabled = () => true;
+ PLUGIN_MODEL_PERSISTENCE.ModelCacheToggle = ModelCacheToggle;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/moderation/index.ts b/enterprise/frontend/src/metabase-enterprise/moderation/index.ts
index 34dea6e7440..c72c9a86df2 100644
--- a/enterprise/frontend/src/metabase-enterprise/moderation/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/moderation/index.ts
@@ -19,19 +19,24 @@ import {
getStatusIcon,
} from "./service";
-if (hasPremiumFeature("content_verification")) {
- Object.assign(PLUGIN_MODERATION, {
- isEnabled: () => true,
- EntityModerationIcon,
- QuestionModerationSection,
- ModerationReviewBanner,
- ModerationReviewTextForQuestion,
- ModerationReviewTextForDashboard,
- ModerationStatusIcon,
- getStatusIcon,
- getQuestionIcon,
- getModerationTimelineEvents,
- useQuestionMenuItems,
- useDashboardMenuItems,
- });
+/**
+ * Initialize moderation plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("content_verification")) {
+ Object.assign(PLUGIN_MODERATION, {
+ isEnabled: () => true,
+ EntityModerationIcon,
+ QuestionModerationSection,
+ ModerationReviewBanner,
+ ModerationReviewTextForQuestion,
+ ModerationReviewTextForDashboard,
+ ModerationStatusIcon,
+ getStatusIcon,
+ getQuestionIcon,
+ getModerationTimelineEvents,
+ useQuestionMenuItems,
+ useDashboardMenuItems,
+ });
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.js
index 7853b40f21f..9a9c17b686f 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js
@@ -5,44 +5,90 @@ PLUGIN_IS_EE_BUILD.isEEBuild = () => true;
import "./shared";
-// PLUGINS:
-
-import "./tools";
-import "./sandboxes";
-import "./auth";
-import "./caching";
-import "./collections";
-import "./content_translation";
-import "./content_verification";
-import "./database_routing";
-import "./remote_sync";
-import "./whitelabel";
-import "./embedding";
-import "./embedding-sdk";
-import "./embedding_iframe_sdk_setup";
-import "./snippets";
-import "./smtp-override";
-import "./sharing";
-import "./moderation";
-import "./advanced_permissions";
-import "./ai-sql-fixer";
-import "./ai-entity-analysis";
-import "./audit_app";
+// PLUGINS THAT DON'T USE hasPremiumFeature (imported immediately):
import "./license";
-import "./model_persistence";
-import "./feature_level_permissions";
-import "./application_permissions";
-import "./group_managers";
-import "./upload_management";
-import "./resource_downloads";
-import "./user_provisioning";
-import "./clean_up";
-import "./metabot";
-import "./database_replication";
-import "./table-editing";
-import "./dependencies";
-import "./documents";
-import "./semantic_search";
-import "./transforms";
-import "./transforms-python";
-import "./public-sharing";
+
+// PLUGINS THAT USE hasPremiumFeature (import initialization functions):
+import { initializePlugin as initializeAdvancedPermissions } from "./advanced_permissions";
+import { initializePlugin as initializeAiEntityAnalysis } from "./ai-entity-analysis";
+import { initializePlugin as initializeAiSqlFixer } from "./ai-sql-fixer";
+import { initializePlugin as initializeApplicationPermissions } from "./application_permissions";
+import { initializePlugin as initializeAuditApp } from "./audit_app";
+import { initializePlugin as initializeAuth } from "./auth";
+import { initializePlugin as initializeCaching } from "./caching";
+import { initializePlugin as initializeCleanUp } from "./clean_up";
+import { initializePlugin as initializeCollections } from "./collections";
+import { initializePlugin as initializeContentTranslation } from "./content_translation";
+import { initializePlugin as initializeContentVerification } from "./content_verification";
+import { initializePlugin as initializeDatabaseReplication } from "./database_replication";
+import { initializePlugin as initializeDatabaseRouting } from "./database_routing";
+import { initializePlugin as initializeDependencies } from "./dependencies";
+import { initializePlugin as initializeDocuments } from "./documents";
+import { initializePlugin as initializeEmbedding } from "./embedding";
+import { initializePlugin as initializeEmbeddingSdk } from "./embedding-sdk";
+import { initializePlugin as initializeEmbeddingIframeSdkSetup } from "./embedding_iframe_sdk_setup";
+import { initializePlugin as initializeFeatureLevelPermissions } from "./feature_level_permissions";
+import { initializePlugin as initializeGroupManagers } from "./group_managers";
+import { initializePlugin as initializeMetabot } from "./metabot";
+import { initializePlugin as initializeModelPersistence } from "./model_persistence";
+import { initializePlugin as initializeModeration } from "./moderation";
+import { initializePlugin as initializePublicSharing } from "./public-sharing";
+import { initializePlugin as initializeRemoteSync } from "./remote_sync";
+import { initializePlugin as initializeResourceDownloads } from "./resource_downloads";
+import { initializePlugin as initializeSandboxes } from "./sandboxes";
+import { initializePlugin as initializeSemanticSearch } from "./semantic_search";
+import { initializePlugin as initializeSharing } from "./sharing";
+import { initializePlugin as initializeSmtpOverride } from "./smtp-override";
+import { initializePlugin as initializeSnippets } from "./snippets";
+import { initializePlugin as initializeTableEditing } from "./table-editing";
+import { initializePlugin as initializeTools } from "./tools";
+import { initializePlugin as initializeTransforms } from "./transforms";
+import { initializePlugin as initializeTransformsPython } from "./transforms-python";
+import { initializePlugin as initializeUploadManagement } from "./upload_management";
+import { initializePlugin as initializeUserProvisioning } from "./user_provisioning";
+import { initializePlugin as initializeWhitelabel } from "./whitelabel";
+
+/**
+ * Initialize all enterprise plugins that use hasPremiumFeature.
+ * Must be called after token features are available.
+ */
+export function initializePlugins() {
+ initializeTools?.();
+ initializeSandboxes?.();
+ initializeAuth?.();
+ initializeCaching?.();
+ initializeCollections?.();
+ initializeContentTranslation?.();
+ initializeContentVerification?.();
+ initializeDatabaseRouting?.();
+ initializeRemoteSync?.();
+ initializeWhitelabel?.();
+ initializeEmbedding?.();
+ initializeEmbeddingSdk?.();
+ initializeEmbeddingIframeSdkSetup?.();
+ initializeSnippets?.();
+ initializeSmtpOverride?.();
+ initializeSharing?.();
+ initializeModeration?.();
+ initializeAdvancedPermissions?.();
+ initializeAiSqlFixer?.();
+ initializeAiEntityAnalysis?.();
+ initializeAuditApp?.();
+ initializeModelPersistence?.();
+ initializeFeatureLevelPermissions?.();
+ initializeApplicationPermissions?.();
+ initializeGroupManagers?.();
+ initializeUploadManagement?.();
+ initializeResourceDownloads?.();
+ initializeUserProvisioning?.();
+ initializeCleanUp?.();
+ initializeMetabot?.();
+ initializeDatabaseReplication?.();
+ initializeTableEditing?.();
+ initializeDependencies?.();
+ initializeDocuments?.();
+ initializeSemanticSearch?.();
+ initializeTransforms?.();
+ initializeTransformsPython?.();
+ initializePublicSharing?.();
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts b/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts
index 4a1d6081f88..9559ca2b56a 100644
--- a/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/public-sharing/index.ts
@@ -3,5 +3,10 @@ import { PLUGIN_PUBLIC_SHARING } from "metabase/plugins";
import { PublicLinksDocumentListing } from "../admin/settings/components/widgets/PublicLinksListing/PublicDocumentResources";
import { PublicDocument } from "../public/containers/PublicDocument";
-PLUGIN_PUBLIC_SHARING.PublicDocumentRoute = PublicDocument;
-PLUGIN_PUBLIC_SHARING.PublicLinksDocumentListing = PublicLinksDocumentListing;
+/**
+ * Initialize sharing plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ PLUGIN_PUBLIC_SHARING.PublicDocumentRoute = PublicDocument;
+ PLUGIN_PUBLIC_SHARING.PublicLinksDocumentListing = PublicLinksDocumentListing;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
index bfec8136812..0d20e3305f5 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
@@ -13,15 +13,20 @@ import { useSyncStatus } from "./hooks/use-sync-status";
import { remoteSyncListenerMiddleware } from "./middleware/remote-sync-listener-middleware";
import { remoteSyncReducer } from "./sync-task-slice";
-if (hasPremiumFeature("remote_sync")) {
- PLUGIN_REMOTE_SYNC.RemoteSyncSettings = RemoteSyncAdminSettings;
- PLUGIN_REMOTE_SYNC.LibraryNav = LibraryNav;
- PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection =
- SyncedCollectionsSidebarSection;
- PLUGIN_REMOTE_SYNC.REMOTE_SYNC_INVALIDATION_TAGS =
- REMOTE_SYNC_INVALIDATION_TAGS;
- PLUGIN_REMOTE_SYNC.useSyncStatus = useSyncStatus;
+/**
+ * Initialize remote sync plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("remote_sync")) {
+ PLUGIN_REMOTE_SYNC.RemoteSyncSettings = RemoteSyncAdminSettings;
+ PLUGIN_REMOTE_SYNC.LibraryNav = LibraryNav;
+ PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection =
+ SyncedCollectionsSidebarSection;
+ PLUGIN_REMOTE_SYNC.REMOTE_SYNC_INVALIDATION_TAGS =
+ REMOTE_SYNC_INVALIDATION_TAGS;
+ PLUGIN_REMOTE_SYNC.useSyncStatus = useSyncStatus;
- PLUGIN_REDUX_MIDDLEWARES.push(remoteSyncListenerMiddleware.middleware);
- PLUGIN_REDUCERS.remoteSyncPlugin = remoteSyncReducer;
+ PLUGIN_REDUX_MIDDLEWARES.push(remoteSyncListenerMiddleware.middleware);
+ PLUGIN_REDUCERS.remoteSyncPlugin = remoteSyncReducer;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/resource_downloads/index.ts b/enterprise/frontend/src/metabase-enterprise/resource_downloads/index.ts
index e7c8324a50b..233720226fc 100644
--- a/enterprise/frontend/src/metabase-enterprise/resource_downloads/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/resource_downloads/index.ts
@@ -1 +1,8 @@
-import "./resource_downloads_plugin";
+import { initializeResourceDownloadsPlugin } from "./resource_downloads_plugin";
+
+/**
+ * Initialize resource downloads plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ initializeResourceDownloadsPlugin();
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/resource_downloads/resource_downloads_plugin.ts b/enterprise/frontend/src/metabase-enterprise/resource_downloads/resource_downloads_plugin.ts
index 98ac209e3a4..78296bd68fa 100644
--- a/enterprise/frontend/src/metabase-enterprise/resource_downloads/resource_downloads_plugin.ts
+++ b/enterprise/frontend/src/metabase-enterprise/resource_downloads/resource_downloads_plugin.ts
@@ -4,35 +4,37 @@ import { PLUGIN_RESOURCE_DOWNLOADS } from "metabase/plugins";
import type { EmbedResourceDownloadOptions } from "metabase/public/lib/types";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-if (hasPremiumFeature("whitelabel")) {
- /**
- * Returns if 'download results' on cards and pdf exports are enabled in public and embedded contexts.
- */
- PLUGIN_RESOURCE_DOWNLOADS.areDownloadsEnabled = ({
- downloads,
- }: {
- downloads?: string | boolean | null;
- }): EmbedResourceDownloadOptions => {
- return (
- match({ downloads })
- .with({ downloads: true }, () => ({ pdf: true, results: true }))
- .with({ downloads: false }, () => ({ pdf: false, results: false }))
- // supports `downloads=pdf`, `downloads=results` and `downloads=pdf,results`
- .with(
- { downloads: P.string },
- ({ downloads }: { downloads: string }) => {
- const downloadTypes = downloads
- .split(",")
- .map((type: string) => type.trim());
+/**
+ * Initialize resource downloads plugin features that depend on hasPremiumFeature.
+ */
+export function initializeResourceDownloadsPlugin() {
+ if (hasPremiumFeature("whitelabel")) {
+ PLUGIN_RESOURCE_DOWNLOADS.areDownloadsEnabled = ({
+ downloads,
+ }: {
+ downloads?: string | boolean | null;
+ }): EmbedResourceDownloadOptions => {
+ return (
+ match({ downloads })
+ .with({ downloads: true }, () => ({ pdf: true, results: true }))
+ .with({ downloads: false }, () => ({ pdf: false, results: false }))
+ // supports `downloads=pdf`, `downloads=results` and `downloads=pdf,results`
+ .with(
+ { downloads: P.string },
+ ({ downloads }: { downloads: string }) => {
+ const downloadTypes = downloads
+ .split(",")
+ .map((type: string) => type.trim());
- return {
- pdf: downloadTypes.includes("pdf"),
- results: downloadTypes.includes("results"),
- };
- },
- )
- // by default downloads are enabled
- .otherwise(() => ({ pdf: true, results: true }))
- );
- };
+ return {
+ pdf: downloadTypes.includes("pdf"),
+ results: downloadTypes.includes("results"),
+ };
+ },
+ )
+ // by default downloads are enabled
+ .otherwise(() => ({ pdf: true, results: true }))
+ );
+ };
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js b/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
index 5d3c1ce00b9..40c8739c630 100644
--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/index.js
@@ -56,44 +56,49 @@ const getEditSegementedAccessUrl = (entityId, groupId, view) =>
const getEditSegmentedAccessPostAction = (entityId, groupId, view) =>
push(getEditSegementedAccessUrl(entityId, groupId, view));
-if (hasPremiumFeature("sandboxes")) {
- PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes = LoginAttributesWidget;
+/**
+ * Initialize sandboxes plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("sandboxes")) {
+ PLUGIN_ADMIN_USER_FORM_FIELDS.FormLoginAttributes = LoginAttributesWidget;
- PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES.push(
- <ModalRoute
- key=":tableId/segmented"
- path=":tableId/segmented"
- modal={EditSandboxingModal}
- />,
- );
- PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES.push(
- <ModalRoute
- key="segmented/group/:groupId"
- path="segmented/group/:groupId"
- modal={EditSandboxingModal}
- />,
- );
- PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_OPTIONS.push(OPTION_SEGMENTED);
- PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_ACTIONS[OPTION_SEGMENTED.value].push({
- label: t`Edit row and column security`,
- iconColor: "brand",
- icon: "pencil",
- actionCreator: (entityId, groupId, view) =>
- push(getEditSegementedAccessUrl(entityId, groupId, view)),
- });
- PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_CONFIRMATIONS.push(
- (permissions, groupId, entityId, newValue) =>
- getSandboxedTableWarningModal(permissions, groupId, entityId, newValue),
- );
- PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_POST_ACTION[OPTION_SEGMENTED.value] =
- getEditSegmentedAccessPostAction;
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES.push(
+ <ModalRoute
+ key=":tableId/segmented"
+ path=":tableId/segmented"
+ modal={EditSandboxingModal}
+ />,
+ );
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES.push(
+ <ModalRoute
+ key="segmented/group/:groupId"
+ path="segmented/group/:groupId"
+ modal={EditSandboxingModal}
+ />,
+ );
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_OPTIONS.push(OPTION_SEGMENTED);
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_ACTIONS[OPTION_SEGMENTED.value].push({
+ label: t`Edit row and column security`,
+ iconColor: "brand",
+ icon: "pencil",
+ actionCreator: (entityId, groupId, view) =>
+ push(getEditSegementedAccessUrl(entityId, groupId, view)),
+ });
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_CONFIRMATIONS.push(
+ (permissions, groupId, entityId, newValue) =>
+ getSandboxedTableWarningModal(permissions, groupId, entityId, newValue),
+ );
+ PLUGIN_ADMIN_PERMISSIONS_TABLE_FIELDS_POST_ACTION[OPTION_SEGMENTED.value] =
+ getEditSegmentedAccessPostAction;
- PLUGIN_DATA_PERMISSIONS.permissionsPayloadExtraSelectors.push((state) => {
- const sandboxes = getDraftPolicies(state);
- const modifiedGroupIds = _.uniq(sandboxes.map((sb) => sb.group_id));
- return [{ sandboxes }, modifiedGroupIds];
- });
+ PLUGIN_DATA_PERMISSIONS.permissionsPayloadExtraSelectors.push((state) => {
+ const sandboxes = getDraftPolicies(state);
+ const modifiedGroupIds = _.uniq(sandboxes.map((sb) => sb.group_id));
+ return [{ sandboxes }, modifiedGroupIds];
+ });
- PLUGIN_DATA_PERMISSIONS.hasChanges.push(hasPolicyChanges);
- PLUGIN_REDUCERS.sandboxingPlugin = sandboxingReducer;
+ PLUGIN_DATA_PERMISSIONS.hasChanges.push(hasPolicyChanges);
+ PLUGIN_REDUCERS.sandboxingPlugin = sandboxingReducer;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-plugins.js b/enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-plugins.js
index e6fb04cf223..8c97e17544d 100644
--- a/enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/sdk-iframe-embedding-plugins.js
@@ -1,5 +1,6 @@
-// Import the EE plugins required by the embedding sdk.
-import "sdk-ee-plugins";
+import { initializePlugins } from "sdk-ee-plugins";
// Plugins that are only applicable to the new iframe embedding.
import "./embedding_iframe_sdk";
+
+initializePlugins();
diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.js b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.js
deleted file mode 100644
index 761dceb017b..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import { PLUGIN_IS_EE_BUILD } from "metabase/plugins";
-
-import { initializeSdkPlugins } from "./whitelabel/sdk-overrides";
-
-// SETTINGS OVERRIDES:
-PLUGIN_IS_EE_BUILD.isEEBuild = () => true;
-
-import "./shared";
-
-// SDK PLUGINS:
-
-import "./embedding";
-import "./embedding-sdk";
-import "./metabot";
-
-initializeSdkPlugins();
diff --git a/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts
new file mode 100644
index 00000000000..9dd0b86b72f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/sdk-plugins.ts
@@ -0,0 +1,25 @@
+import { PLUGIN_IS_EE_BUILD } from "metabase/plugins";
+
+// SETTINGS OVERRIDES:
+PLUGIN_IS_EE_BUILD.isEEBuild = () => true;
+
+import "./shared";
+
+// SDK PLUGINS THAT USE hasPremiumFeature (import initialization functions):
+import { initializePlugin as initializeEmbedding } from "./embedding";
+import { initializePlugin as initializeEmbeddingSdk } from "./embedding-sdk";
+import { initializePlugin as initializeMetabot } from "./metabot";
+import { initializePlugin as initializeWhitelabelPlugin } from "./whitelabel";
+import { initializePlugin as initializeWhitelabelOverridePlugin } from "./whitelabel/sdk-overrides";
+
+/**
+ * Initialize all SDK enterprise plugins that use hasPremiumFeature.
+ * Must be called after token features are available.
+ */
+export function initializePlugins() {
+ initializeEmbedding?.();
+ initializeEmbeddingSdk?.();
+ initializeMetabot?.();
+ initializeWhitelabelPlugin?.();
+ initializeWhitelabelOverridePlugin?.();
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx b/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx
index 610115d163f..c189829c0e8 100644
--- a/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/semantic_search/index.tsx
@@ -3,6 +3,11 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { SearchSettingsWidget } from "./SearchSettingsWidget";
-if (hasPremiumFeature("semantic_search")) {
- PLUGIN_SEMANTIC_SEARCH.SearchSettingsWidget = SearchSettingsWidget;
+/**
+ * Initialize semantic_search plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("semantic_search")) {
+ PLUGIN_SEMANTIC_SEARCH.SearchSettingsWidget = SearchSettingsWidget;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/sharing/index.ts b/enterprise/frontend/src/metabase-enterprise/sharing/index.ts
index 63d459be061..283b8b01b19 100644
--- a/enterprise/frontend/src/metabase-enterprise/sharing/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/sharing/index.ts
@@ -2,7 +2,12 @@ import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metab
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { MutableParametersSection } from "metabase-enterprise/sharing/components/MutableParametersSection";
-if (hasPremiumFeature("dashboard_subscription_filters")) {
- PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE.Component =
- MutableParametersSection;
+/**
+ * Initialize sharing plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("dashboard_subscription_filters")) {
+ PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE.Component =
+ MutableParametersSection;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/smtp-override/index.ts b/enterprise/frontend/src/metabase-enterprise/smtp-override/index.ts
index 1035b8daa1a..0efd2755dc7 100644
--- a/enterprise/frontend/src/metabase-enterprise/smtp-override/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/smtp-override/index.ts
@@ -6,7 +6,13 @@ import {
SMTPOverrideConnectionForm,
} from "./components";
-if (hasPremiumFeature("cloud_custom_smtp")) {
- PLUGIN_SMTP_OVERRIDE.CloudSMTPConnectionCard = CloudSMTPConnectionCard;
- PLUGIN_SMTP_OVERRIDE.SMTPOverrideConnectionForm = SMTPOverrideConnectionForm;
+/**
+ * Initialize SMTP override plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("cloud_custom_smtp")) {
+ PLUGIN_SMTP_OVERRIDE.CloudSMTPConnectionCard = CloudSMTPConnectionCard;
+ PLUGIN_SMTP_OVERRIDE.SMTPOverrideConnectionForm =
+ SMTPOverrideConnectionForm;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/index.js b/enterprise/frontend/src/metabase-enterprise/snippets/index.js
index 6de5f4e3131..bc3e1910154 100644
--- a/enterprise/frontend/src/metabase-enterprise/snippets/index.js
+++ b/enterprise/frontend/src/metabase-enterprise/snippets/index.js
@@ -15,70 +15,91 @@ import CollectionOptionsButton from "./components/CollectionOptionsButton";
import CollectionRow from "./components/CollectionRow";
import SnippetCollectionFormModal from "./components/SnippetCollectionFormModal";
-if (hasPremiumFeature("snippet_collections")) {
- PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS.push((snippetSidebar) => ({
- icon: "folder",
- name: t`New folder`,
- onClick: () =>
- snippetSidebar.setState({
- modalSnippetCollection: {
- parent_id: canonicalCollectionId(
- snippetSidebar.props.snippetCollection.id,
- ),
- },
- }),
- }));
+/**
+ * Initialize snippets plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("snippet_collections")) {
+ // Add new menu option
+ PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS.push((snippetSidebar) => ({
+ icon: "folder",
+ name: t`New folder`,
+ onClick: () =>
+ snippetSidebar.setState({
+ modalSnippetCollection: {
+ parent_id: canonicalCollectionId(
+ snippetSidebar.props.snippetCollection.id,
+ ),
+ },
+ }),
+ }));
- PLUGIN_SNIPPET_SIDEBAR_MODALS.push(
- (snippetSidebar) =>
- snippetSidebar.state.modalSnippetCollection && (
- <Modal
- onClose={() =>
- snippetSidebar.setState({ modalSnippetCollection: null })
- }
- >
- <SnippetCollectionFormModal
- collection={snippetSidebar.state.modalSnippetCollection}
+ // Add modals
+ PLUGIN_SNIPPET_SIDEBAR_MODALS.push(
+ (snippetSidebar) =>
+ snippetSidebar.state.modalSnippetCollection && (
+ <Modal
onClose={() =>
snippetSidebar.setState({ modalSnippetCollection: null })
}
- onSaved={() => {
- snippetSidebar.setState({ modalSnippetCollection: null });
- }}
- />
- </Modal>
- ),
- (snippetSidebar) =>
- snippetSidebar.state.permissionsModalCollectionId != null && (
- <Modal
- onClose={() =>
- snippetSidebar.setState({ permissionsModalCollectionId: null })
- }
- >
- <CollectionPermissionsModal
- params={{
- slug: snippetSidebar.state.permissionsModalCollectionId,
- }}
+ >
+ <SnippetCollectionFormModal
+ collection={snippetSidebar.state.modalSnippetCollection}
+ onClose={() =>
+ snippetSidebar.setState({ modalSnippetCollection: null })
+ }
+ onSaved={() => {
+ snippetSidebar.setState({ modalSnippetCollection: null });
+ }}
+ />
+ </Modal>
+ ),
+ (snippetSidebar) =>
+ snippetSidebar.state.permissionsModalCollectionId != null && (
+ <Modal
onClose={() =>
snippetSidebar.setState({ permissionsModalCollectionId: null })
}
- namespace="snippets"
- />
- </Modal>
- ),
- );
+ >
+ <CollectionPermissionsModal
+ params={{
+ slug: snippetSidebar.state.permissionsModalCollectionId,
+ }}
+ onClose={() =>
+ snippetSidebar.setState({ permissionsModalCollectionId: null })
+ }
+ namespace="snippets"
+ />
+ </Modal>
+ ),
+ );
- PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS.collection = CollectionRow;
+ // Set collection row renderer
+ PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS.collection = CollectionRow;
- PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push((snippetSidebar, props) => {
- const collection = snippetSidebar.props.snippetCollection;
- return (
- <CollectionOptionsButton
- {...snippetSidebar.props}
- {...props}
- setSidebarState={snippetSidebar.setState.bind(snippetSidebar)}
- collection={collection}
- />
- );
- });
+ // Add header button
+ PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.push((snippetSidebar, props) => {
+ const collection = snippetSidebar.props.snippetCollection;
+ return (
+ <CollectionOptionsButton
+ {...snippetSidebar.props}
+ {...props}
+ setSidebarState={snippetSidebar.setState.bind(snippetSidebar)}
+ collection={collection}
+ />
+ );
+ });
+ }
+}
+
+/**
+ * Reset snippets plugin features.
+ *
+ * @internal for testing purposes only
+ */
+export function resetPlugin() {
+ PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS.length = 0;
+ PLUGIN_SNIPPET_SIDEBAR_MODALS.length = 0;
+ PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS.collection = null;
+ PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS.length = 0;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/index.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/index.tsx
index 9e5fdc4bacb..207734f73a4 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/index.tsx
@@ -6,12 +6,17 @@ import { getRoutes } from "./routes";
import { isDatabaseTableEditingEnabled } from "./settings";
import { getTableEditUrl } from "./urls";
-if (hasPremiumFeature("table_data_editing")) {
- PLUGIN_TABLE_EDITING.isEnabled = () => true;
- PLUGIN_TABLE_EDITING.isDatabaseTableEditingEnabled =
- isDatabaseTableEditingEnabled;
- PLUGIN_TABLE_EDITING.getRoutes = getRoutes;
- PLUGIN_TABLE_EDITING.getTableEditUrl = getTableEditUrl;
- PLUGIN_TABLE_EDITING.AdminDatabaseTableEditingSection =
- AdminDatabaseTableEditingSection;
+/**
+ * Initialize table-editing plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("table_data_editing")) {
+ PLUGIN_TABLE_EDITING.isEnabled = () => true;
+ PLUGIN_TABLE_EDITING.isDatabaseTableEditingEnabled =
+ isDatabaseTableEditingEnabled;
+ PLUGIN_TABLE_EDITING.getRoutes = getRoutes;
+ PLUGIN_TABLE_EDITING.getTableEditUrl = getTableEditUrl;
+ PLUGIN_TABLE_EDITING.AdminDatabaseTableEditingSection =
+ AdminDatabaseTableEditingSection;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/tools/index.ts b/enterprise/frontend/src/metabase-enterprise/tools/index.ts
index 4b85db72cec..958f288024c 100644
--- a/enterprise/frontend/src/metabase-enterprise/tools/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/tools/index.ts
@@ -3,6 +3,11 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import ErrorOverview from "./ErrorOverview";
-if (hasPremiumFeature("audit_app")) {
- PLUGIN_ADMIN_TOOLS.COMPONENT = ErrorOverview;
+/**
+ * Initialize tools plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("audit_app")) {
+ PLUGIN_ADMIN_TOOLS.COMPONENT = ErrorOverview;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
index 9ab4794a5b2..adf9cc09b14 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/index.tsx
@@ -13,23 +13,29 @@ import { SHARED_LIB_IMPORT_PATH } from "./constants";
import { PythonLibraryEditorPage } from "./pages/PythonLibraryEditorPage";
import { PythonRunnerSettingsPage } from "./pages/PythonRunnerSettingsPage";
-if (hasPremiumFeature("transforms-python")) {
- PLUGIN_TRANSFORMS_PYTHON.isEnabled = true;
- PLUGIN_TRANSFORMS_PYTHON.PythonRunnerSettingsPage = PythonRunnerSettingsPage;
- PLUGIN_TRANSFORMS_PYTHON.TransformEditor = PythonTransformEditor;
- PLUGIN_TRANSFORMS_PYTHON.SourceSection = SourceSection;
+/**
+ * Initialize transforms-python plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("transforms-python")) {
+ PLUGIN_TRANSFORMS_PYTHON.isEnabled = true;
+ PLUGIN_TRANSFORMS_PYTHON.PythonRunnerSettingsPage =
+ PythonRunnerSettingsPage;
+ PLUGIN_TRANSFORMS_PYTHON.TransformEditor = PythonTransformEditor;
+ PLUGIN_TRANSFORMS_PYTHON.SourceSection = SourceSection;
- PLUGIN_TRANSFORMS_PYTHON.getAdminRoutes = () => (
- <Route component={FullWidthTransformPageLayout}>
- <Route path="library/:path" component={PythonLibraryEditorPage} />
- </Route>
- );
+ PLUGIN_TRANSFORMS_PYTHON.getAdminRoutes = () => (
+ <Route component={FullWidthTransformPageLayout}>
+ <Route path="library/:path" component={PythonLibraryEditorPage} />
+ </Route>
+ );
- PLUGIN_TRANSFORMS_PYTHON.getTransformsNavLinks = () => (
- <AdminNavItem
- label={t`Python library`}
- path={Urls.transformPythonLibrary({ path: SHARED_LIB_IMPORT_PATH })}
- icon="code_block"
- />
- );
+ PLUGIN_TRANSFORMS_PYTHON.getTransformsNavLinks = () => (
+ <AdminNavItem
+ label={t`Python library`}
+ path={Urls.transformPythonLibrary({ path: SHARED_LIB_IMPORT_PATH })}
+ icon="code_block"
+ />
+ );
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
index a0a723ab4de..3ab55d5862f 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms/index.tsx
@@ -27,36 +27,41 @@ import { TransformPage } from "./pages/TransformPage";
import { DetailsPageLayout, ListPageLayout } from "./pages/TransformPageLayout";
import { TransformQueryPage } from "./pages/TransformQueryPage";
-if (hasPremiumFeature("transforms")) {
- PLUGIN_ENTITIES.entities["transforms"] = Transforms;
- PLUGIN_TRANSFORMS.TransformPicker = TransformPicker;
+/**
+ * Initialize transforms plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("transforms")) {
+ PLUGIN_ENTITIES.entities["transforms"] = Transforms;
+ PLUGIN_TRANSFORMS.TransformPicker = TransformPicker;
- PLUGIN_TRANSFORMS.getAdminPaths = () => [
- { key: "transforms", name: t`Transforms`, path: "/admin/transforms" },
- ];
+ PLUGIN_TRANSFORMS.getAdminPaths = () => [
+ { key: "transforms", name: t`Transforms`, path: "/admin/transforms" },
+ ];
- PLUGIN_TRANSFORMS.getAdminRoutes = () => (
- <Route path="transforms" component={createAdminRouteGuard("transforms")}>
- <Route title={t`Transforms`}>
- <Route component={ListPageLayout}>
- <IndexRoute component={TransformListPage} />
- <Route path="jobs" component={JobListPage} />
- <Route path="runs" component={RunListPage} />
+ PLUGIN_TRANSFORMS.getAdminRoutes = () => (
+ <Route path="transforms" component={createAdminRouteGuard("transforms")}>
+ <Route title={t`Transforms`}>
+ <Route component={ListPageLayout}>
+ <IndexRoute component={TransformListPage} />
+ <Route path="jobs" component={JobListPage} />
+ <Route path="runs" component={RunListPage} />
+ </Route>
+ <Route component={DetailsPageLayout}>
+ <Route path="jobs/new" component={NewJobPage} />
+ <Route path="jobs/:jobId" component={JobPage} />
+ <Route path=":transformId" component={TransformPage} />
+ </Route>
+ {PLUGIN_TRANSFORMS_PYTHON.getAdminRoutes()}
+ <Route path="new/query" component={NewQueryTransformPage} />
+ <Route path="new/native" component={NewNativeTransformPage} />
+ <Route path="new/card/:cardId" component={NewCardTransformPage} />
+ {PLUGIN_TRANSFORMS_PYTHON.isEnabled && (
+ <Route path="new/python" component={NewPythonTransformPage} />
+ )}
+ <Route path=":transformId/query" component={TransformQueryPage} />
</Route>
- <Route component={DetailsPageLayout}>
- <Route path="jobs/new" component={NewJobPage} />
- <Route path="jobs/:jobId" component={JobPage} />
- <Route path=":transformId" component={TransformPage} />
- </Route>
- {PLUGIN_TRANSFORMS_PYTHON.getAdminRoutes()}
- <Route path="new/query" component={NewQueryTransformPage} />
- <Route path="new/native" component={NewNativeTransformPage} />
- <Route path="new/card/:cardId" component={NewCardTransformPage} />
- {PLUGIN_TRANSFORMS_PYTHON.isEnabled && (
- <Route path="new/python" component={NewPythonTransformPage} />
- )}
- <Route path=":transformId/query" component={TransformQueryPage} />
</Route>
- </Route>
- );
+ );
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts b/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
index 5bc8684b792..51fd7c91bba 100644
--- a/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
@@ -11,19 +11,24 @@ import {
import { UploadManagementTable } from "./UploadManagementTable";
-if (hasPremiumFeature("upload_management")) {
- PLUGIN_UPLOAD_MANAGEMENT.UploadManagementTable = UploadManagementTable;
-}
+/**
+ * Initialize upload_management plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("upload_management")) {
+ PLUGIN_UPLOAD_MANAGEMENT.UploadManagementTable = UploadManagementTable;
+ }
-if (hasPremiumFeature("hosting")) {
- // The reason we're showing this panel even to instances without the dwh
- // is because we want to show them the storage upsell.
- PLUGIN_UPLOAD_MANAGEMENT.GdriveAddDataPanel = GdriveAddDataPanel;
-}
+ if (hasPremiumFeature("hosting")) {
+ // The reason we're showing this panel even to instances without the dwh
+ // is because we want to show them the storage upsell.
+ PLUGIN_UPLOAD_MANAGEMENT.GdriveAddDataPanel = GdriveAddDataPanel;
+ }
-if (hasPremiumFeature("hosting") && hasPremiumFeature("attached_dwh")) {
- PLUGIN_UPLOAD_MANAGEMENT.FileUploadErrorModal = FileUploadErrorModal;
- PLUGIN_UPLOAD_MANAGEMENT.GdriveConnectionModal = GdriveConnectionModal;
- PLUGIN_UPLOAD_MANAGEMENT.GdriveSyncStatus = GdriveSyncStatus;
- PLUGIN_UPLOAD_MANAGEMENT.GdriveDbMenu = GdriveDbMenu;
+ if (hasPremiumFeature("hosting") && hasPremiumFeature("attached_dwh")) {
+ PLUGIN_UPLOAD_MANAGEMENT.FileUploadErrorModal = FileUploadErrorModal;
+ PLUGIN_UPLOAD_MANAGEMENT.GdriveConnectionModal = GdriveConnectionModal;
+ PLUGIN_UPLOAD_MANAGEMENT.GdriveSyncStatus = GdriveSyncStatus;
+ PLUGIN_UPLOAD_MANAGEMENT.GdriveDbMenu = GdriveDbMenu;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/index.ts b/enterprise/frontend/src/metabase-enterprise/user_provisioning/index.ts
index 7f53257fae7..78c9238f45b 100644
--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/index.ts
@@ -3,6 +3,11 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { UserProvisioning } from "./components/UserProvisioning";
-if (hasPremiumFeature("scim")) {
- PLUGIN_AUTH_PROVIDERS.UserProvisioningSettings = UserProvisioning;
+/**
+ * Initialize user provisioning plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("scim")) {
+ PLUGIN_AUTH_PROVIDERS.UserProvisioningSettings = UserProvisioning;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
index 1e72915e3c8..69e578bc214 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
@@ -25,31 +25,36 @@ import { WhiteLabelBrandingSettingsPage } from "./components/WhiteLabelBrandingS
import { WhiteLabelConcealSettingsPage } from "./components/WhiteLabelConcealSettingsPage";
import { updateColors } from "./lib/whitelabel";
-if (hasPremiumFeature("whitelabel")) {
- PLUGIN_LANDING_PAGE.getLandingPage = () =>
- // TODO: MetabaseSettings doesn't have EnterpriseSetting keys, so the type and mapping don't work
- MetabaseSettings.get("landing-page" as SettingKey) as string;
- PLUGIN_LANDING_PAGE.LandingPageWidget = LandingPageWidget;
+/**
+ * Initialize whitelabel plugin features that depend on hasPremiumFeature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("whitelabel")) {
+ PLUGIN_LANDING_PAGE.getLandingPage = () =>
+ // TODO: MetabaseSettings doesn't have EnterpriseSetting keys, so the type and mapping don't work
+ MetabaseSettings.get("landing-page" as SettingKey) as string;
+ PLUGIN_LANDING_PAGE.LandingPageWidget = LandingPageWidget;
- PLUGIN_WHITELABEL.WhiteLabelBrandingSettingsPage =
- WhiteLabelBrandingSettingsPage;
- PLUGIN_WHITELABEL.WhiteLabelConcealSettingsPage =
- WhiteLabelConcealSettingsPage;
+ PLUGIN_WHITELABEL.WhiteLabelBrandingSettingsPage =
+ WhiteLabelBrandingSettingsPage;
+ PLUGIN_WHITELABEL.WhiteLabelConcealSettingsPage =
+ WhiteLabelConcealSettingsPage;
- PLUGIN_APP_INIT_FUNCTIONS.push(() => {
- updateColors();
- });
+ PLUGIN_APP_INIT_FUNCTIONS.push(() => {
+ updateColors();
+ });
- PLUGIN_LOGO_ICON_COMPONENTS.push(LogoIcon);
- PLUGIN_SELECTORS.canWhitelabel = () => true;
+ PLUGIN_LOGO_ICON_COMPONENTS.push(LogoIcon);
+ PLUGIN_SELECTORS.canWhitelabel = () => true;
- // these selectors control whitelabeling UI
- PLUGIN_SELECTORS.getLoadingMessageFactory = getLoadingMessage;
- PLUGIN_SELECTORS.getIsWhiteLabeling = getIsWhiteLabeling;
- PLUGIN_SELECTORS.getApplicationName = getApplicationName;
- PLUGIN_SELECTORS.getShowMetabaseLinks = getShowMetabaseLinks;
- PLUGIN_SELECTORS.getLoginPageIllustration = getLoginPageIllustration;
- PLUGIN_SELECTORS.getLandingPageIllustration = getLandingPageIllustration;
- PLUGIN_SELECTORS.getNoDataIllustration = getNoDataIllustration;
- PLUGIN_SELECTORS.getNoObjectIllustration = getNoObjectIllustration;
+ // these selectors control whitelabeling UI
+ PLUGIN_SELECTORS.getLoadingMessageFactory = getLoadingMessage;
+ PLUGIN_SELECTORS.getIsWhiteLabeling = getIsWhiteLabeling;
+ PLUGIN_SELECTORS.getApplicationName = getApplicationName;
+ PLUGIN_SELECTORS.getShowMetabaseLinks = getShowMetabaseLinks;
+ PLUGIN_SELECTORS.getLoginPageIllustration = getLoginPageIllustration;
+ PLUGIN_SELECTORS.getLandingPageIllustration = getLandingPageIllustration;
+ PLUGIN_SELECTORS.getNoDataIllustration = getNoDataIllustration;
+ PLUGIN_SELECTORS.getNoObjectIllustration = getNoObjectIllustration;
+ }
}
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.ts
index e06f710a27c..049f3035f3b 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.ts
@@ -1,25 +1,34 @@
import type { SdkStoreState } from "embedding-sdk-bundle/store/types";
import type { MetabaseGlobalPluginsConfig } from "embedding-sdk-package";
import { PLUGIN_SELECTORS } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
import type { State } from "metabase-types/store";
-// Store the original selector functions to preserve Enterprise/OSS behavior
-const originalGetNoDataIllustration = PLUGIN_SELECTORS.getNoDataIllustration;
-const originalGetNoObjectIllustration =
- PLUGIN_SELECTORS.getNoObjectIllustration;
-
// Flag to ensure initialization happens only once
let isInitialized = false;
+// For testing purposes - allows resetting initialization state
+export const resetInitialization = () => {
+ isInitialized = false;
+};
+
/**
* Initialize SDK plugins by overriding core plugin selectors to be SDK-aware.
* This allows the SDK to provide custom implementations while maintaining
* backward compatibility with Enterprise and OSS versions.
*/
-export const initializeSdkPlugins = () => {
+export const initializePlugin = () => {
+ if (!hasPremiumFeature("whitelabel")) {
+ return;
+ }
+
if (isInitialized) {
return;
}
+ // Store the original selector functions to preserve Enterprise/OSS behavior
+ const originalGetNoDataIllustration = PLUGIN_SELECTORS.getNoDataIllustration;
+ const originalGetNoObjectIllustration =
+ PLUGIN_SELECTORS.getNoObjectIllustration;
isInitialized = true;
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.unit.spec.ts
index eeabf55ab87..730142f679b 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/sdk-overrides.unit.spec.ts
@@ -1,6 +1,24 @@
import { PLUGIN_SELECTORS } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
-import { initializeSdkPlugins } from "./sdk-overrides";
+import { initializePlugin, resetInitialization } from "./sdk-overrides";
+
+jest.mock("metabase-enterprise/settings", () => ({
+ hasPremiumFeature: jest.fn(),
+}));
+
+const mockHasPremiumFeature = hasPremiumFeature as jest.MockedFunction<
+ typeof hasPremiumFeature
+>;
+
+const mockWhitelabelEnabled = (enabled: boolean) => {
+ mockHasPremiumFeature.mockImplementation((feature) => {
+ if (feature === "whitelabel") {
+ return enabled;
+ }
+ return true; // Mock other features as enabled by default
+ });
+};
describe("SDK Plugin Initialization", () => {
let originalGetNoDataIllustration: typeof PLUGIN_SELECTORS.getNoDataIllustration;
@@ -10,18 +28,43 @@ describe("SDK Plugin Initialization", () => {
// Store original selectors before all tests
originalGetNoDataIllustration = PLUGIN_SELECTORS.getNoDataIllustration;
originalGetNoObjectIllustration = PLUGIN_SELECTORS.getNoObjectIllustration;
-
- // Initialize SDK plugins once for all tests
- initializeSdkPlugins();
});
- afterAll(() => {
- // Restore original selectors after all tests
+ afterEach(() => {
+ // Reset mocks after each test
+ jest.clearAllMocks();
+
+ // Reset initialization state for next test
+ resetInitialization();
+
+ // Restore original selectors after each test
PLUGIN_SELECTORS.getNoDataIllustration = originalGetNoDataIllustration;
PLUGIN_SELECTORS.getNoObjectIllustration = originalGetNoObjectIllustration;
});
- describe("initializeSdkPlugins", () => {
+ describe("when whitelabel feature is disabled", () => {
+ beforeEach(() => {
+ mockWhitelabelEnabled(false);
+ initializePlugin();
+ });
+
+ it("should not initialize SDK plugins when whitelabel is disabled", () => {
+ // Selectors should remain unchanged
+ expect(PLUGIN_SELECTORS.getNoDataIllustration).toBe(
+ originalGetNoDataIllustration,
+ );
+ expect(PLUGIN_SELECTORS.getNoObjectIllustration).toBe(
+ originalGetNoObjectIllustration,
+ );
+ });
+ });
+
+ describe("when whitelabel feature is enabled", () => {
+ beforeEach(() => {
+ mockWhitelabelEnabled(true);
+ initializePlugin();
+ });
+
it("should initialize SDK plugins and make selectors SDK-aware", () => {
// Selectors should be different after initialization
expect(PLUGIN_SELECTORS.getNoDataIllustration).not.toBe(
@@ -120,6 +163,8 @@ describe("SDK Plugin Initialization", () => {
});
it("should return SDK plugin result for getNoObjectIllustration when SDK plugins are available", () => {
+ initializePlugin();
+
const mockSdkIllustration = "custom-sdk-no-object-illustration.svg";
const mockSdkPlugins = {
getNoObjectIllustration: jest.fn().mockReturnValue(mockSdkIllustration),
@@ -217,5 +262,17 @@ describe("SDK Plugin Initialization", () => {
consoleSpy.mockRestore();
});
+
+ it("should not initialize twice when called multiple times", () => {
+ // First call is in beforeEach, get the selector reference
+ const firstSelector = PLUGIN_SELECTORS.getNoDataIllustration;
+
+ // Call initialize again
+ initializePlugin();
+ const secondSelector = PLUGIN_SELECTORS.getNoDataIllustration;
+
+ // Should be the same selector instance (not re-wrapped)
+ expect(firstSelector).toBe(secondSelector);
+ });
});
});
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index 4ec8ca7692f..dfdbc341f3e 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -24,7 +24,6 @@ import "metabase/plugins/builtin";
// This is conditionally aliased in the webpack config.
// If EE isn't enabled, it loads an empty file.
-import "ee-plugins";
// Set nonce for mantine v6 deps
import "metabase/lib/csp";
@@ -35,6 +34,7 @@ import { createRoot } from "react-dom/client";
import { Router, useRouterHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
+import { initializePlugins } from "ee-plugins";
import { ModifiedBackend } from "metabase/common/components/dnd/ModifiedBackend";
import { createTracker } from "metabase/lib/analytics";
import api from "metabase/lib/api";
@@ -61,6 +61,7 @@ const browserHistory = useRouterHistory(createHistory)({
basename: BASENAME,
});
+initializePlugins();
function _init(reducers, getRoutes, callback) {
const store = getStore(reducers, browserHistory);
const routes = getRoutes(store);
diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
index ed19549133d..cd2cbe17220 100644
--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
@@ -17,7 +17,11 @@ import {
waitForLoaderToBeRemoved,
within,
} from "__support__/ui";
-import type { CollectionId, CollectionItem } from "metabase-types/api";
+import type {
+ CollectionId,
+ CollectionItem,
+ TokenFeatures,
+} from "metabase-types/api";
import {
createMockCard,
createMockCollection,
@@ -243,6 +247,7 @@ interface SetupOpts {
onChange?: (item: QuestionPickerItem) => void;
models?: [QuestionPickerValueModel, ...QuestionPickerValueModel[]];
options?: typeof defaultOptions;
+ tokenFeatures?: Partial<TokenFeatures>;
}
const commonSetup = () => {
@@ -278,18 +283,19 @@ const commonSetup = () => {
const setupPicker = async ({
initialValue = { id: "root", model: "collection" },
onChange = jest.fn<void, [QuestionPickerItem]>(),
+ tokenFeatures = {},
}: SetupOpts = {}) => {
commonSetup();
- const tokenFeatures = createMockTokenFeatures({
- content_verification: true,
- official_collections: true,
- });
const settings = createMockSettings();
const settingValuesWithToken = {
...settings,
- "token-features": tokenFeatures,
+ "token-features": createMockTokenFeatures({
+ content_verification: true,
+ official_collections: true,
+ ...tokenFeatures,
+ }),
};
const state = createMockState({
@@ -329,9 +335,16 @@ const setupModal = async ({
models = ["card", "dataset"],
onChange = jest.fn<void, [QuestionPickerItem]>(),
options = defaultOptions,
+ tokenFeatures = {},
}: SetupOpts = {}) => {
commonSetup();
+ const state = createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ }),
+ });
+
renderWithProviders(
<QuestionPickerModal
onChange={onChange}
@@ -340,6 +353,9 @@ const setupModal = async ({
models={models}
options={options}
/>,
+ {
+ storeInitialState: state,
+ },
);
await waitForLoaderToBeRemoved();
@@ -650,7 +666,10 @@ describe("QuestionPickerModal", () => {
it("should be able to search for metrics", async () => {
setupSearchEndpoints([nestedQuestion, myModel, myMetric]);
- await setupModal({ models: ["card", "dataset", "metric"] });
+ await setupModal({
+ tokenFeatures: { snippet_collections: true },
+ models: ["card", "dataset", "metric"],
+ });
const searchInput = await screen.findByPlaceholderText(/search/i);
await userEvent.type(searchInput, myMetric.name);
await userEvent.click(screen.getByText("Everywhere"));
diff --git a/frontend/src/metabase/entities/collections/utils.unit.spec.ts b/frontend/src/metabase/entities/collections/utils.unit.spec.ts
index 2ea371b4fd1..29c4a50f607 100644
--- a/frontend/src/metabase/entities/collections/utils.unit.spec.ts
+++ b/frontend/src/metabase/entities/collections/utils.unit.spec.ts
@@ -1,5 +1,9 @@
-import { setupEnterpriseTest } from "__support__/enterprise";
-import { createMockCollection } from "metabase-types/api/mocks";
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import { mockSettings } from "__support__/settings";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
import { PERSONAL_COLLECTIONS } from "./constants";
import {
@@ -310,7 +314,13 @@ describe("entities > collections > utils", () => {
describe("EE", () => {
beforeEach(() => {
- setupEnterpriseTest();
+ mockSettings({
+ "token-features": createMockTokenFeatures({
+ official_collections: true,
+ audit_app: true,
+ }),
+ });
+ setupEnterprisePlugins();
});
it("returns correct icon for official collections", () => {
@@ -389,7 +399,13 @@ describe("entities > collections > utils", () => {
describe("EE", () => {
beforeEach(() => {
- setupEnterpriseTest();
+ mockSettings({
+ "token-features": createMockTokenFeatures({
+ official_collections: true,
+ audit_app: true,
+ }),
+ });
+ setupEnterprisePlugins();
});
testCasesEE.forEach((testCase) => {
diff --git a/frontend/src/metabase/plugins/noop.js b/frontend/src/metabase/plugins/noop.js
new file mode 100644
index 00000000000..d4b448f06c1
--- /dev/null
+++ b/frontend/src/metabase/plugins/noop.js
@@ -0,0 +1,10 @@
+// Noop SDK plugins for OSS builds
+// This file provides the same interface as the enterprise SDK plugins
+// but without any actual functionality
+
+/**
+ * No-op version of SDK plugins initialization for OSS builds.
+ */
+export function initializePlugins() {
+ // No-op for OSS builds
+}
diff --git a/frontend/src/metabase/query_builder/components/SavedQuestionHeaderButton/SavedQuestionHeaderButton.unit.spec.js b/frontend/src/metabase/query_builder/components/SavedQuestionHeaderButton/SavedQuestionHeaderButton.unit.spec.js
index 39135a89118..94921c0a4fe 100644
--- a/frontend/src/metabase/query_builder/components/SavedQuestionHeaderButton/SavedQuestionHeaderButton.unit.spec.js
+++ b/frontend/src/metabase/query_builder/components/SavedQuestionHeaderButton/SavedQuestionHeaderButton.unit.spec.js
@@ -1,11 +1,16 @@
import userEvent from "@testing-library/user-event";
-import { setupEnterpriseTest } from "__support__/enterprise";
+import { setupEnterprisePlugins } from "__support__/enterprise";
import { createMockMetadata } from "__support__/metadata";
+import { mockSettings } from "__support__/settings";
import { getIcon, renderWithProviders, screen } from "__support__/ui";
import Question from "metabase-lib/v1/Question";
-import { createMockCollection } from "metabase-types/api/mocks";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+import { createMockState } from "metabase-types/store/mocks";
import { SavedQuestionHeaderButton } from "./SavedQuestionHeaderButton";
@@ -13,11 +18,24 @@ const metadata = createMockMetadata({
databases: [createSampleDatabase()],
});
-function setup({ question }) {
+function setup({ question, tokenFeatures = {}, hasEnterprisePlugins = false }) {
const onSave = jest.fn();
+ const state = createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ }),
+ });
+
+ if (hasEnterprisePlugins) {
+ setupEnterprisePlugins();
+ }
+
renderWithProviders(
<SavedQuestionHeaderButton question={question} onSave={onSave} />,
+ {
+ storeInitialState: state,
+ },
);
return { onSave };
@@ -78,8 +96,13 @@ describe("SavedQuestionHeaderButton", () => {
});
it("should have an additional icon to signify the question's moderation status", () => {
- setupEnterpriseTest();
- setup({ question });
+ setup({
+ question,
+ hasEnterprisePlugins: true,
+ tokenFeatures: {
+ content_verification: true,
+ },
+ });
expect(getIcon("verified")).toBeInTheDocument();
});
});
@@ -97,7 +120,11 @@ describe("SavedQuestionHeaderButton", () => {
);
it("should have an additional icon to signify the question's collection type", () => {
- setup({ question });
+ setup({
+ question,
+ hasEnterprisePlugins: true,
+ tokenFeatures: { audit_app: true },
+ });
expect(getIcon("audit")).toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/query_builder/components/template_tags/SnippetSidebar/tests/premium.unit.spec.tsx b/frontend/src/metabase/query_builder/components/template_tags/SnippetSidebar/tests/premium.unit.spec.tsx
index 90010cf0809..2748a94df54 100644
--- a/frontend/src/metabase/query_builder/components/template_tags/SnippetSidebar/tests/premium.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/template_tags/SnippetSidebar/tests/premium.unit.spec.tsx
@@ -1,6 +1,10 @@
import userEvent from "@testing-library/user-event";
import { getIcon, queryIcon, screen } from "__support__/ui";
+// TODO remove this and use proper reset functions once
+// plugins initialization functions return proper teardown functions
+// eslint-disable-next-line no-restricted-imports
+import { resetPlugin } from "metabase-enterprise/snippets";
import type { SetupOpts } from "./setup";
import { setup as baseSetup } from "./setup";
@@ -14,6 +18,10 @@ async function setup(options: SetupOpts = {}) {
}
describe("SnippetSidebar (EE with token feature)", () => {
+ beforeEach(() => {
+ resetPlugin();
+ });
+
it("should display the `Change permissions` menu for admin users", async () => {
await setup();
diff --git a/frontend/src/metabase/search/components/SearchResult/tests/SearchResult-Collections.unit.spec.tsx b/frontend/src/metabase/search/components/SearchResult/tests/SearchResult-Collections.unit.spec.tsx
index 6cffd9e2d9f..e90722108ab 100644
--- a/frontend/src/metabase/search/components/SearchResult/tests/SearchResult-Collections.unit.spec.tsx
+++ b/frontend/src/metabase/search/components/SearchResult/tests/SearchResult-Collections.unit.spec.tsx
@@ -1,8 +1,9 @@
-import { setupEnterpriseTest } from "__support__/enterprise";
+import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupCollectionByIdEndpoint,
setupUserRecipientsEndpoint,
} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
import {
getIcon,
queryIcon,
@@ -12,7 +13,13 @@ import {
} from "__support__/ui";
import { SearchResult } from "metabase/search/components/SearchResult";
import type { WrappedResult } from "metabase/search/types";
-import { createMockCollection, createMockUser } from "metabase-types/api/mocks";
+import type { TokenFeatures } from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
import { createWrappedSearchResult } from "./util";
@@ -40,14 +47,36 @@ const resultInOfficalCollection = createWrappedSearchResult({
collection: TEST_OFFICIAL_COLLECTION,
});
-const setup = ({ result }: { result: WrappedResult }) => {
+interface SetupOpts {
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasEnterprisePlugins?: boolean;
+ result: WrappedResult;
+}
+
+const setup = ({
+ tokenFeatures = {},
+ hasEnterprisePlugins = false,
+ result,
+}: SetupOpts) => {
setupCollectionByIdEndpoint({
collections: [TEST_REGULAR_COLLECTION, TEST_OFFICIAL_COLLECTION],
});
setupUserRecipientsEndpoint({ users: [createMockUser()] });
- renderWithProviders(<SearchResult result={result} index={0} />);
+ const state = createMockState({
+ settings: mockSettings({
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ }),
+ });
+
+ if (hasEnterprisePlugins) {
+ setupEnterprisePlugins();
+ }
+
+ renderWithProviders(<SearchResult result={result} index={0} />, {
+ storeInitialState: state,
+ });
};
describe("SearchResult > Collections", () => {
@@ -89,10 +118,6 @@ describe("SearchResult > Collections", () => {
getIcon: () => ({ name: "table" }),
};
- beforeAll(() => {
- setupEnterpriseTest();
- });
-
it("renders regular collection correctly", async () => {
setup({ result: resultInRegularCollection });
expect(
@@ -111,7 +136,11 @@ describe("SearchResult > Collections", () => {
});
it("renders official collections correctly", async () => {
- setup({ result: resultInOfficalCollectionEE });
+ setup({
+ result: resultInOfficalCollectionEE,
+ hasEnterprisePlugins: true,
+ tokenFeatures: { official_collections: true },
+ });
expect(
screen.getByText(resultInOfficalCollectionEE.name),
).toBeInTheDocument();
diff --git a/frontend/test/__support__/enterprise.js b/frontend/test/__support__/enterprise.js
index cfe4c3aaab0..cd92f9e106c 100644
--- a/frontend/test/__support__/enterprise.js
+++ b/frontend/test/__support__/enterprise.js
@@ -1,5 +1,29 @@
/**
* @deprecated use setupEnterprisePlugins with settings set via mockSettings
+ * ```ts
+ * import { createMockState } from "metabase-types/store/mocks";
+ * import { mockSettings } from "__support__/settings";
+ * import {
+ * createMockTokenFeatures,
+ * } from "metabase-types/api/mocks";
+ *
+ * const state = createMockState({
+ * settings: mockSettings({
+ * "token-features": createMockTokenFeatures(tokenFeatures),
+ * }),
+ * });
+ *
+ * if (hasEnterprisePlugins) {
+ * setupEnterprisePlugins();
+ * }
+ *
+ * renderWithProviders(
+ * <SomeComponent />,
+ * {
+ * storeInitialState: state,
+ * },
+ * );
+ * ```
*/
export function setupEnterpriseTest() {
jest.mock("metabase-enterprise/settings", () => ({
@@ -10,10 +34,12 @@ export function setupEnterpriseTest() {
}
export function setupEnterprisePlugins() {
- require("metabase-enterprise/plugins");
+ const { initializePlugins } = require(`metabase-enterprise/plugins`);
+ initializePlugins?.();
}
// function is used for optimization, so we don't need to import all plugins
export function setupEnterpriseOnlyPlugin(pluginName) {
- require(`metabase-enterprise/${pluginName}`);
+ const { initializePlugin } = require(`metabase-enterprise/${pluginName}`);
+ initializePlugin?.();
}
diff --git a/jest.config.js b/jest.config.js
index 9572301b327..935d554b5d1 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -48,7 +48,7 @@ const baseConfig = {
* This isn't a problem in the core app because we seem to not import to entry file directly
* for any component under tests.
*/
- "sdk-ee-plugins": "<rootDir>/frontend/src/metabase/lib/noop.js",
+ "sdk-ee-plugins": "<rootDir>/frontend/src/metabase/plugins/noop.js",
/**
* SDK iframe embedding imports the embedding sdk and its components.
* We want to exclude the SDK from the main app's bundle to reduce the bundle size.
diff --git a/rspack.main.config.js b/rspack.main.config.js
index 26dfeabc2f0..06f4b7181d3 100644
--- a/rspack.main.config.js
+++ b/rspack.main.config.js
@@ -236,7 +236,10 @@ const config = {
// with ie11 point to the minified version
icepick: __dirname + "/node_modules/icepick/icepick.min",
// conditionally load either the EE plugins file or a empty file in the CE code tree
- "ee-plugins": resolveEnterprisePathOrNoop("/plugins"),
+ "ee-plugins":
+ process.env.MB_EDITION === "ee"
+ ? ENTERPRISE_SRC_PATH + "/plugins"
+ : SRC_PATH + "/plugins/noop",
"ee-overrides": resolveEnterprisePathOrNoop("/overrides"),
embedding: EMBEDDING_SRC_PATH,
"embedding-sdk-package": SDK_PACKAGE_SRC_PATH,
@@ -245,7 +248,10 @@ const config = {
"sdk-iframe-embedding-ee-plugins": resolveEnterprisePathOrNoop(
"/sdk-iframe-embedding-plugins",
),
- "sdk-ee-plugins": resolveEnterprisePathOrNoop("/sdk-plugins"),
+ "sdk-ee-plugins":
+ process.env.MB_EDITION === "ee"
+ ? ENTERPRISE_SRC_PATH + "/sdk-plugins"
+ : SRC_PATH + "/plugins/noop",
"sdk-specific-imports": SRC_PATH + "/lib/noop",
},
fallback: {
diff --git a/tsconfig.json b/tsconfig.json
index 624a5985110..ce74fcc3f65 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -13,7 +13,8 @@
],
"build-configs/*": ["./frontend/build/*"],
"cljs/*": ["./target/cljs_dev/*"],
- "docs/*": ["./docs/*"]
+ "docs/*": ["./docs/*"],
+ "sdk-ee-plugins": ["./frontend/src/metabase/plugins/noop"]
},
"plugins": [
{