The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Convert metabase/utils files to TypeScript (#72314)
Anderson17465e9c8dba
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.tsindex 3915096304c..c632ec665b1 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts@@ -85,11 +85,10 @@ export const useInitDataInternal = ({}if (!api.onResponseError) {- api.onResponseError = ({- metabaseVersion,- }: {- metabaseVersion: string;- }) => {+ api.onResponseError = ({ metabaseVersion }) => {+ if (metabaseVersion == null) {+ return;+ }// Use ensureMetabaseProviderPropsStore to access the current instance of reduxStoreensureMetabaseProviderPropsStore().getState()diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.tsindex de9272cb850..966e67ce06b 100644--- a/frontend/src/metabase-types/api/dashboard.ts+++ b/frontend/src/metabase-types/api/dashboard.ts@@ -29,7 +29,12 @@ import type {WritebackAction,WritebackActionId,} from "./actions";-import type { Card, CardId, VisualizationSettings } from "./card";+import type {+ Card,+ CardId,+ ColumnSettings,+ VisualizationSettings,+} from "./card";import type { Dataset } from "./dataset";import type { ModerationReview } from "./moderation";import type { SearchModel } from "./search";@@ -137,6 +142,7 @@ export type DashCardVisualizationSettings = {[key: string]: unknown;virtual_card?: VirtualCard;iframe?: string;+ column_settings?: Record<string, ColumnSettings>;};export type BaseDashboardCard = DashboardCardLayoutAttrs & {diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-bookmark-list-query/use-bookmark-list-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-bookmark-list-query/use-bookmark-list-query.tsindex 55c67aaa4f0..44156273d86 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-bookmark-list-query/use-bookmark-list-query.ts+++ b/frontend/src/metabase/common/hooks/entity-framework/use-bookmark-list-query/use-bookmark-list-query.ts@@ -13,7 +13,7 @@ import { useEntityListQuery } from "../use-entity-list-query";export const useBookmarkListQuery = (props: UseEntityListQueryProps = {},): UseEntityListQueryResult<Bookmark> => {- return useEntityListQuery(props, {+ return useEntityListQuery<Bookmark>(props, {fetchList: Bookmarks.actions.fetchList,getError: Bookmarks.selectors.getError,getList: Bookmarks.selectors.getList,diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-database-list-query/use-database-list-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-database-list-query/use-database-list-query.tsindex 7472a8d5382..c2b50625f6d 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-database-list-query/use-database-list-query.ts+++ b/frontend/src/metabase/common/hooks/entity-framework/use-database-list-query/use-database-list-query.ts@@ -13,7 +13,7 @@ import type { ListDatabasesRequest } from "metabase-types/api";export const useDatabaseListQuery = (props: UseEntityListQueryProps<ListDatabasesRequest> = {},): UseEntityListQueryResult<Database> => {- return useEntityListQuery(props, {+ return useEntityListQuery<Database, ListDatabasesRequest>(props, {fetchList: Databases.actions.fetchList,getList: Databases.selectors.getList,getLoading: Databases.selectors.getLoading,diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-group-list-query/use-group-list-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-group-list-query/use-group-list-query.tsindex 5a84903e1b9..3d4e32e7279 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-group-list-query/use-group-list-query.ts+++ b/frontend/src/metabase/common/hooks/entity-framework/use-group-list-query/use-group-list-query.ts@@ -4,15 +4,15 @@ import type {} from "metabase/common/hooks/entity-framework/use-entity-list-query";import { useEntityListQuery } from "metabase/common/hooks/entity-framework/use-entity-list-query";import { Groups } from "metabase/entities/groups";-import type { GroupListQuery } from "metabase-types/api";+import type { GroupInfo, GroupListQuery } from "metabase-types/api";/*** @deprecated use "metabase/api" instead*/export const useGroupListQuery = (- props: UseEntityListQueryProps<Record<string, never>> = {},-): UseEntityListQueryResult<GroupListQuery> => {- return useEntityListQuery(props, {+ props: UseEntityListQueryProps<GroupListQuery> = {},+): UseEntityListQueryResult<GroupInfo> => {+ return useEntityListQuery<GroupInfo, GroupListQuery>(props, {fetchList: Groups.actions.fetchList,getList: Groups.selectors.getList,getLoading: Groups.selectors.getLoading,diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.tsindex 8ea06ef1367..3c45c2f4651 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts+++ b/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts@@ -13,7 +13,7 @@ import type { ListCardsRequest } from "metabase-types/api";export const useQuestionListQuery = (props: UseEntityListQueryProps<ListCardsRequest> = {},): UseEntityListQueryResult<Question> => {- return useEntityListQuery(props, {+ return useEntityListQuery<Question, ListCardsRequest>(props, {fetchList: Questions.actions.fetchList,getList: Questions.selectors.getList,getLoading: Questions.selectors.getLoading,diff --git a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.tsindex 836a3a63707..9f650566b74 100644--- a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts+++ b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts@@ -25,7 +25,7 @@ import {setParameterType,} from "./parameters";-function setup({ routing, ...initialState }: State) {+function setup(initialState: State) {return getStore(mainReducers, initialState);}diff --git a/frontend/src/metabase/entities/actions/actions.ts b/frontend/src/metabase/entities/actions/actions.tsindex a61e4e462c4..03a00594c1c 100644--- a/frontend/src/metabase/entities/actions/actions.ts+++ b/frontend/src/metabase/entities/actions/actions.ts@@ -206,7 +206,7 @@ export const Actions = createEntity({undo({}, t`action`, archived ? t`archived` : t`unarchived`),),},- reducer: (state = {}, { type, payload }: { type: string; payload: any }) => {+ reducer: (state, { type, payload }: { type: string; payload: any }) => {switch (type) {case CREATE_PUBLIC_LINK: {const { id, uuid } = payload;diff --git a/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsx b/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsxindex 002e70618d6..e06223a26e6 100644--- a/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsx+++ b/frontend/src/metabase/entities/containers/rtk-query/EntityListLoader.tsx@@ -237,14 +237,12 @@ export function EntityListLoader<Entity, EntityWrapper>({useEffect(() => {if (isFetching) {- // @ts-expect-error - invalid typings in redux-actions packagedispatch(setRequestLoading(requestStatePath, queryKey));}}, [dispatch, isFetching, requestStatePath, queryKey]);useEffect(() => {if (rtkError) {- // @ts-expect-error - invalid typings in redux-actions packagedispatch(setRequestError(requestStatePath, queryKey, rtkError));}}, [dispatch, rtkError, requestStatePath, queryKey]);@@ -277,7 +275,6 @@ export function EntityListLoader<Entity, EntityWrapper>({// NOTE Atte Keinänen 8/23/17:// Dispatch `setRequestLoaded` after clearing the call stack because we want to the actual data to be updated// before we notify components via `state.requests.fetches` that fetching the data is completed- // @ts-expect-error - invalid typings in redux-actions packagesetTimeout(() => dispatch(setRequestLoaded(requestStatePath, queryKey)));}}, [diff --git a/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsx b/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsxindex 52b6d579ad6..545f7abd727 100644--- a/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsx+++ b/frontend/src/metabase/entities/containers/rtk-query/EntityObjectLoader.tsx@@ -152,14 +152,12 @@ export function EntityObjectLoader<Entity, EntityWrapper>({useEffect(() => {if (isFetching) {- // @ts-expect-error - invalid typings in redux-actions packagedispatch(setRequestLoading(requestStatePath, queryKey));}}, [dispatch, isFetching, requestStatePath, queryKey]);useEffect(() => {if (rtkError) {- // @ts-expect-error - invalid typings in redux-actions packagedispatch(setRequestError(requestStatePath, queryKey, rtkError));}}, [dispatch, rtkError, requestStatePath, queryKey]);@@ -174,7 +172,6 @@ export function EntityObjectLoader<Entity, EntityWrapper>({// NOTE Atte Keinänen 8/23/17:// Dispatch `setRequestLoaded` after clearing the call stack because we want to the actual data to be updated// before we notify components via `state.requests.fetches` that fetching the data is completed- // @ts-expect-error - invalid typings in redux-actions packagesetTimeout(() => dispatch(setRequestLoaded(requestStatePath, queryKey)));}}, [diff --git a/frontend/src/metabase/reducers-common.ts b/frontend/src/metabase/reducers-common.tsindex a78a378a9e8..4b6aad48b27 100644--- a/frontend/src/metabase/reducers-common.ts+++ b/frontend/src/metabase/reducers-common.ts@@ -13,7 +13,7 @@ import { reducer as downloads } from "metabase/redux/downloads";import { embed } from "metabase/redux/embed";import { reducer as embeddingDataPicker } from "metabase/redux/embedding-data-picker";import entities, { enhanceRequestsReducer } from "metabase/redux/entities";-import requests from "metabase/redux/requests";+import { requestsReducer } from "metabase/redux/requests";import { settings } from "metabase/redux/settings";import { modal } from "metabase/redux/ui";import { undoReducer as undo } from "metabase/redux/undo";@@ -29,7 +29,7 @@ export const commonReducers = {embeddingDataPicker,currentUser,// "entities" framework needs control over "requests" state- requests: enhanceRequestsReducer(requests),+ requests: enhanceRequestsReducer(requestsReducer),settings,undo,entities,diff --git a/frontend/src/metabase/redux/requests.js b/frontend/src/metabase/redux/requests.jsdeleted file mode 100644index f1185ac7e37..00000000000--- a/frontend/src/metabase/redux/requests.js+++ /dev/null@@ -1,119 +0,0 @@-import { assoc, getIn, updateIn } from "icepick";-import { createAction, handleActions } from "redux-actions";--export const setRequestLoading = createAction(- "metabase/requests/SET_REQUEST_LOADING",- (statePath, queryKey) => ({- statePath,- queryKey,- }),-);-export const setRequestPromise = createAction(- "metabase/requests/SET_REQUEST_PROMISE",- (statePath, queryKey, queryPromise) => ({- statePath,- queryKey,- queryPromise,- }),-);-export const setRequestLoaded = createAction(- "metabase/requests/SET_REQUEST_LOADED",- (statePath, queryKey) => ({ statePath, queryKey }),-);-export const setRequestError = createAction(- "metabase/requests/SET_REQUEST_ERROR",- (statePath, queryKey, error) => ({ statePath, queryKey, error }),-);-export const setRequestUnloaded = createAction(- "metabase/requests/SET_REQUEST_UNLOADED",- (statePath) => ({ statePath }),-);--const initialRequestState = {- loading: false,- loaded: false,- fetched: false,- error: null,- _isRequestState: true,-};--const requestStateReducer = handleActions(- {- [setRequestLoading]: {- next: (state, { payload: { queryKey, queryPromise } }) => ({- ...state,- queryKey,- queryPromise,- loading: true,- loaded: false,- error: null,- }),- },- [setRequestPromise]: {- next: (state, { payload: { queryKey, queryPromise } }) => ({- ...state,- queryKey,- queryPromise,- }),- },- [setRequestLoaded]: {- next: (state, { payload: { queryKey } }) => ({- ...state,- queryKey,- loading: false,- loaded: true,- error: null,- fetched: true,- }),- },- [setRequestError]: {- next: (state, { payload: { queryKey, error } }) => ({- ...state,- queryKey,- loading: false,- loaded: false,- error: error,- }),- },- [setRequestUnloaded]: {- next: (state) => ({- ...state,- loaded: false,- error: null,- queryPromise: null,- }),- },- },- initialRequestState,-);--function requestStateReducerRecursive(state, action) {- if (!state || state._isRequestState) {- return requestStateReducer(state, action);- } else {- for (const [key, subState] of Object.entries(state)) {- state = assoc(state, key, requestStateReducerRecursive(subState, action));- }- return state;- }-}--const isBulkInvalidation = (statePath) => {- // Bulk invalidations only have a statePath with a length of 2- return statePath.length <= 2;-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default (state = {}, action) => {- if (action && action.payload && action.payload.statePath) {- const statePath = action.payload.statePath;- const hasStateToUpdate = !!getIn(state, statePath);-- if (hasStateToUpdate || !isBulkInvalidation(statePath)) {- state = updateIn(state, action.payload.statePath, (subState) =>- requestStateReducerRecursive(subState, action),- );- }- }- return state;-};diff --git a/frontend/src/metabase/redux/requests.ts b/frontend/src/metabase/redux/requests.tsnew file mode 100644index 00000000000..6d40fb12801--- /dev/null+++ b/frontend/src/metabase/redux/requests.ts@@ -0,0 +1,203 @@+import { assoc, getIn, updateIn } from "icepick";+import { type Action, createAction, handleActions } from "redux-actions";++export type RequestState = {+ loading: boolean;+ loaded: boolean;+ fetched: boolean;+ error: unknown | null;+ queryKey?: string;+ queryPromise?: Promise<unknown> | null;+ _isRequestState: true;+};++export type RequestsStateTree = {+ [key: string]: RequestsStateTree | RequestState;+};++type StatePath = (string | number)[];++type RequestActionPayload = {+ statePath?: StatePath;+ queryKey?: string;+ queryPromise?: Promise<unknown>;+ error?: unknown;+};++type RequestsAction = Action<RequestActionPayload | undefined>;++export const setRequestLoading = createAction<+ RequestActionPayload,+ StatePath,+ string | undefined+>(+ "metabase/requests/SET_REQUEST_LOADING",+ (statePath: StatePath, queryKey?: string) => ({+ statePath,+ queryKey,+ }),+);++export const setRequestPromise = createAction<+ RequestActionPayload,+ StatePath,+ string | undefined,+ Promise<unknown>+>(+ "metabase/requests/SET_REQUEST_PROMISE",+ (+ statePath: StatePath,+ queryKey: string | undefined,+ queryPromise: Promise<unknown>,+ ) => ({+ statePath,+ queryKey,+ queryPromise,+ }),+);++export const setRequestLoaded = createAction<+ RequestActionPayload,+ StatePath,+ string | undefined+>(+ "metabase/requests/SET_REQUEST_LOADED",+ (statePath: StatePath, queryKey?: string) => ({+ statePath,+ queryKey,+ }),+);++export const setRequestError = createAction<+ RequestActionPayload,+ StatePath,+ string | undefined,+ unknown+>(+ "metabase/requests/SET_REQUEST_ERROR",+ (statePath: StatePath, queryKey: string | undefined, error: unknown) => ({+ statePath,+ queryKey,+ error,+ }),+);++export const setRequestUnloaded = createAction<RequestActionPayload, StatePath>(+ "metabase/requests/SET_REQUEST_UNLOADED",+ (statePath: StatePath) => ({ statePath }),+);++const initialRequestState: RequestState = {+ loading: false,+ loaded: false,+ fetched: false,+ error: null,+ _isRequestState: true,+};++const requestStateReducer = handleActions<+ RequestState,+ RequestActionPayload | undefined+>(+ {+ [setRequestLoading.toString()]: {+ next: (+ state,+ { payload: { queryKey, queryPromise } = {} }: RequestsAction,+ ) => ({+ ...state,+ queryKey,+ queryPromise,+ loading: true,+ loaded: false,+ error: null,+ }),+ },+ [setRequestPromise.toString()]: {+ next: (+ state,+ { payload: { queryKey, queryPromise } = {} }: RequestsAction,+ ) => ({+ ...state,+ queryKey,+ queryPromise,+ }),+ },+ [setRequestLoaded.toString()]: {+ next: (state, { payload: { queryKey } = {} }: RequestsAction) => ({+ ...state,+ queryKey,+ loading: false,+ loaded: true,+ error: null,+ fetched: true,+ }),+ },+ [setRequestError.toString()]: {+ next: (state, { payload: { queryKey, error } = {} }: RequestsAction) => ({+ ...state,+ queryKey,+ loading: false,+ loaded: false,+ error: error,+ }),+ },+ [setRequestUnloaded.toString()]: {+ next: (state) => ({+ ...state,+ loaded: false,+ error: null,+ queryPromise: null,+ }),+ },+ },+ initialRequestState,+);++function isRequestState(+ state: RequestState | RequestsStateTree,+): state is RequestState {+ return "_isRequestState" in state && !!state._isRequestState;+}++function requestStateReducerRecursive(+ state: RequestState | RequestsStateTree | undefined,+ action: RequestsAction,+): RequestState | RequestsStateTree {+ if (!state || isRequestState(state)) {+ return requestStateReducer(state, action);+ } else {+ let newState = state;+ for (const [key, subState] of Object.entries(state)) {+ newState = assoc(+ newState,+ key,+ requestStateReducerRecursive(subState, action),+ );+ }++ return newState;+ }+}++const isBulkInvalidation = (statePath: (string | number)[]): boolean => {+ // Bulk invalidations only have a statePath with a length of 2+ return statePath.length <= 2;+};++export const requestsReducer = (+ state: RequestsStateTree,+ action: RequestsAction,+): RequestsStateTree => {+ if (action?.payload?.statePath) {+ const statePath = action.payload.statePath;+ const hasStateToUpdate = !!getIn(state, statePath);++ if (hasStateToUpdate || !isBulkInvalidation(statePath)) {+ state = updateIn(state, statePath, (subState: RequestState | undefined) =>+ requestStateReducerRecursive(subState, action),+ );+ }+ }+ return state;+};diff --git a/frontend/src/metabase/redux/store/entities.ts b/frontend/src/metabase/redux/store/entities.tsindex 9f19fe6edfa..9023697bbe3 100644--- a/frontend/src/metabase/redux/store/entities.ts+++ b/frontend/src/metabase/redux/store/entities.ts@@ -32,4 +32,6 @@ export interface EntitiesState {snippets: Record<string, NormalizedNativeQuerySnippet>;questions: Record<string, NormalizedCard>;groups: Record<string, NormalizedGroup>;++ [key: `${string}_list`]: unknown;}diff --git a/frontend/src/metabase/redux/store/mocks/requests.ts b/frontend/src/metabase/redux/store/mocks/requests.tsindex 70bba8a0145..57453817d7b 100644--- a/frontend/src/metabase/redux/store/mocks/requests.ts+++ b/frontend/src/metabase/redux/store/mocks/requests.ts@@ -1,8 +1,11 @@import type { RequestsState } from "../requests";-export const createMockRequestsState = (): RequestsState => {+export const createMockRequestsState = (+ opts: Partial<RequestsState> = {},+): RequestsState => {return {entities: {},plugins: {},+ ...opts,};};diff --git a/frontend/src/metabase/utils/analytics-untyped.js b/frontend/src/metabase/utils/analytics-untyped.tssimilarity index 64%rename from frontend/src/metabase/utils/analytics-untyped.jsrename to frontend/src/metabase/utils/analytics-untyped.tsindex a48a777d07b..8e3f6b19826 100644--- a/frontend/src/metabase/utils/analytics-untyped.js+++ b/frontend/src/metabase/utils/analytics-untyped.ts@@ -1,9 +1,11 @@+import type { EnhancedStore } from "@reduxjs/toolkit";import * as Snowplow from "@snowplow/browser-tracker";+import type { State } from "metabase/redux/store";import { getUserId } from "metabase/selectors/user";import Settings from "metabase/utils/settings";-export const trackPageView = (url) => {+export const trackPageView = (url: string): void => {if (!url || !Settings.trackingEnabled()) {return;}@@ -12,21 +14,24 @@ export const trackPageView = (url) => {trackSnowplowPageView(getSanitizedUrl(url));}};-export const createTracker = (store) => {++export const createTracker = (store: EnhancedStore<State>): void => {if (Settings.snowplowEnabled()) {createSnowplowTracker(store);}};-const createSnowplowPlugin = (store) => {+const createSnowplowPlugin = (store: EnhancedStore<State>) => {return {beforeTrack: () => {const userId = getUserId(store.getState());- userId && Snowplow.setUserId(String(userId));+ if (userId) {+ Snowplow.setUserId(String(userId));+ }},contexts: () => {const id = Settings.get("analytics-uuid");- const version = Settings.get("version", {});+ const version = Settings.get("version") ?? {};const createdAt = Settings.get("instance-creation");const tokenFeatures = Settings.get("token-features");@@ -36,7 +41,7 @@ const createSnowplowPlugin = (store) => {data: {id,version: {- tag: version.tag,+ tag: (version as { tag?: string }).tag,},created_at: createdAt,token_features: tokenFeatures,@@ -47,8 +52,8 @@ const createSnowplowPlugin = (store) => {};};-const createSnowplowTracker = (store) => {- Snowplow.newTracker("sp", Settings.snowplowUrl(), {+const createSnowplowTracker = (store: EnhancedStore<State>): void => {+ Snowplow.newTracker("sp", Settings.snowplowUrl() ?? "", {appId: "metabase",platform: "web",eventMethod: "post",@@ -60,15 +65,15 @@ const createSnowplowTracker = (store) => {});};-const trackSnowplowPageView = (url) => {+const trackSnowplowPageView = (url: string): void => {Snowplow.setReferrerUrl("#");Snowplow.setCustomUrl(url);Snowplow.trackPageView();};-const getSanitizedUrl = (url) => {- const urlWithoutSlug = url.replace(/(\/\d+)-[^\/]+$/, (match, path) => path);- const urlWithoutHost = new URL(urlWithoutSlug, Settings.snowplowUrl());+const getSanitizedUrl = (url: string): string => {+ const urlWithoutSlug = url.replace(/(\/\d+)-[^/]+$/, (match, path) => path);+ const urlWithoutHost = new URL(urlWithoutSlug, Settings.snowplowUrl() ?? "");return urlWithoutHost.href;};diff --git a/frontend/src/metabase/utils/api.js b/frontend/src/metabase/utils/api.tssimilarity index 62%rename from frontend/src/metabase/utils/api.jsrename to frontend/src/metabase/utils/api.tsindex dfed455a2fc..1962be40fa1 100644--- a/frontend/src/metabase/utils/api.js+++ b/frontend/src/metabase/utils/api.ts@@ -5,6 +5,7 @@ import querystring from "querystring";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { isTest } from "metabase/env";import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";+import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";import { getTraceparentHeader } from "metabase/utils/otel";import { delay } from "metabase/utils/promise";@@ -15,13 +16,35 @@ const MAX_RETRIES = 10;const ANTI_CSRF_HEADER = "X-Metabase-Anti-CSRF-Token";const METABASE_VERSION_HEADER = "X-Metabase-Version";-let ANTI_CSRF_TOKEN = null;+let ANTI_CSRF_TOKEN: string | null = null;++type RequestOptions = {+ json: boolean;+ hasBody: boolean;+ noEvent: boolean;+ transformResponse: (opts: {+ body: object;+ data?: Record<string, unknown>;+ response?: Response;+ }) => Response | undefined;+ raw: Record<string, boolean>;+ headers: Record<string, string>;+ retry: boolean;+ retryCount: number;+ retryDelayIntervals: number[];+ formData?: boolean;+ fetch?: boolean;+ bodyParamName?: string | null;+ cancelled?: Promise<unknown>;+ controller?: AbortController;+ signal?: AbortSignal;+};-const DEFAULT_OPTIONS = {+const DEFAULT_OPTIONS: RequestOptions = {json: true,hasBody: false,noEvent: false,- transformResponse: ({ body }) => body,+ transformResponse: ({ body }) => body as Response,raw: {},headers: {},retry: false,@@ -33,21 +56,46 @@ const DEFAULT_OPTIONS = {.map((_, i) => ONE_SECOND * Math.pow(2, i)),};+type RequestClientInfo = string | { name: string; version: string | null };++/**+ * Legacy API method. Consumers across the codebase pass concrete request shapes+ * (e.g. `CreateDashboardRequest`) and rely on destructuring a concrete response,+ * so we use broad `any` types here to match the JS version's behaviour.+ */+type ApiMethod = (+ rawData?: any,+ invocationOptions?: Partial<RequestOptions>,+) => Promise<any>;++type MethodCreator = (+ urlTemplate: string,+ methodOptions?:+ | Partial<RequestOptions>+ | ((opts: {+ body: object;+ data?: Record<string, unknown>;+ response?: Response;+ }) => Response | undefined),+) => ApiMethod;++type ResponseErrorInfo = {+ body: unknown;+ status: number;+ metabaseVersion: string | null;+};+export class Api extends EventEmitter {basename = "";apiKey = "";- sessionToken;- onResponseError;-- /**- * @type {string|{name: string, version: string | null}}- */- requestClient;+ sessionToken: string | undefined;+ onResponseError: ((info: ResponseErrorInfo) => void) | undefined;+ requestClient: RequestClientInfo | undefined;- GET;- POST;- PUT;- DELETE;+ GET: MethodCreator;+ POST: MethodCreator;+ PUT: MethodCreator;+ DELETE: MethodCreator;constructor() {super();@@ -57,16 +105,16 @@ export class Api extends EventEmitter {this.PUT = this._makeMethod("PUT", { hasBody: true });}- getClientHeaders() {+ getClientHeaders(): Record<string, string> {const self = this;- const headers = {};+ const headers: Record<string, string> = {};if (this.apiKey) {headers["X-Api-Key"] = self.apiKey;}if (this.sessionToken) {- headers["X-Metabase-Session"] = self.sessionToken;+ headers["X-Metabase-Session"] = self.sessionToken!;}if (isWithinIframe() && !self.requestClient) {@@ -111,28 +159,41 @@ export class Api extends EventEmitter {return headers;}- _makeMethod(methodTemplate, creatorOptions = {}) {+ _makeMethod(+ methodTemplate: string,+ creatorOptions: Partial<RequestOptions> = {},+ ): MethodCreator {return (urlTemplate, methodOptions = {}) => {if (typeof methodOptions === "function") {methodOptions = { transformResponse: methodOptions };}- const defaultOptions = {+ const defaultOptions: RequestOptions = {...DEFAULT_OPTIONS,...creatorOptions,...methodOptions,};- return async (rawData, invocationOptions = {}) => {- let { url, method, options, data } =- await this.apiRequestManipulationMiddleware({- url: urlTemplate,- method: methodTemplate,- options: { ...defaultOptions, ...invocationOptions },- // this will transform arrays to objects with numeric keys- // we shouldn't be using top level-arrays in the API- data: { ...rawData },- });+ return async (rawData = {}, invocationOptions = {}) => {+ const middlewareResult = await this.apiRequestManipulationMiddleware({+ url: urlTemplate,+ method: methodTemplate as "GET" | "POST",+ options: {+ ...defaultOptions,+ ...invocationOptions,+ } as OnBeforeRequestHandlerConfig["options"],+ // this will transform arrays to objects with numeric keys+ // we shouldn't be using top level-arrays in the API+ data: { ...rawData },+ });+ let { url, method } = middlewareResult;+ // Re-merge to preserve all RequestOptions fields after middleware (middleware can only extend options)+ const options: RequestOptions = {+ ...defaultOptions,+ ...invocationOptions,+ ...middlewareResult.options,+ } as RequestOptions;+ const { data } = middlewareResult;for (const tag of url.match(/:\w+/g) || []) {const paramName = tag.slice(1);let value = data[paramName];@@ -142,9 +203,9 @@ export class Api extends EventEmitter {value = "";}if (!options.raw || !options.raw[paramName]) {- value = encodeURIComponent(value);+ value = encodeURIComponent(value as string);}- url = url.replace(tag, value);+ url = url.replace(tag, value as string);}// remove undefinedfor (const name in data) {@@ -153,23 +214,23 @@ export class Api extends EventEmitter {}}- let body;+ let body: string | FormData | undefined;if (options.hasBody) {body = options.formData- ? rawData.formData+ ? (rawData["formData"] as FormData): JSON.stringify(options.bodyParamName != null- ? data[options.bodyParamName]+ ? data[options.bodyParamName!]: data,);} else {- const qs = querystring.stringify(data);+ const qs = querystring.stringify(data as Record<string, string>);if (qs) {url += (url.indexOf("?") >= 0 ? "&" : "?") + qs;}}- const headers = {+ const headers: Record<string, string> = {...this.getClientHeaders(),...(options.json? { Accept: "application/json", "Content-Type": "application/json" }@@ -197,7 +258,14 @@ export class Api extends EventEmitter {};}- async _makeRequestWithRetries(method, url, headers, body, data, options) {+ async _makeRequestWithRetries(+ method: string,+ url: string,+ headers: Record<string, string>,+ body: string | FormData | undefined,+ data: Record<string, unknown>,+ options: RequestOptions,+ ): Promise<unknown> {// Get a copy of the delay intervals that we can pop items from as we retryconst retryDelays = options.retryDelayIntervals.slice().reverse();let retryCount = 0;@@ -214,12 +282,15 @@ export class Api extends EventEmitter {data,options,);- } catch (e) {+ } catch (e: unknown) {retryCount++;// If the response is 503 and the next retry won't put us over the maxAttempts,// wait a bit and try again- if (e.status === 503 && retryCount < maxAttempts) {- await delay(retryDelays.pop());+ if (+ (e as { status?: number }).status === 503 &&+ retryCount < maxAttempts+ ) {+ await delay(retryDelays.pop() ?? 0);} else {throw e;}@@ -227,18 +298,45 @@ export class Api extends EventEmitter {} while (retryCount < maxAttempts);}- _makeRequest(...args) {- const options = args[5];+ _makeRequest(+ method: string,+ url: string,+ headers: Record<string, string>,+ body: string | FormData | undefined,+ data: Record<string, unknown>,+ options: RequestOptions,+ ): Promise<unknown> {// this is temporary to not deal with failed cypress tests// we should switch to using fetch in all cases (metabase#28489)if (isTest || options.fetch) {- return this._makeRequestWithFetch(...args);+ return this._makeRequestWithFetch(+ method,+ url,+ headers,+ body,+ data,+ options,+ );} else {- return this._makeRequestWithXhr(...args);+ return this._makeRequestWithXhr(+ method,+ url,+ headers,+ body,+ data,+ options,+ );}}- _makeRequestWithXhr(method, url, headers, body, data, options) {+ _makeRequestWithXhr(+ method: string,+ url: string,+ headers: Record<string, string>,+ body: string | FormData | undefined,+ data: Record<string, unknown>,+ options: RequestOptions,+ ): Promise<unknown> {return new Promise((resolve, reject) => {let isCancelled = false;const xhr = new XMLHttpRequest();@@ -258,35 +356,50 @@ export class Api extends EventEmitter {ANTI_CSRF_TOKEN = antiCsrfToken;}- let body = xhr.responseText;+ let responseBody: Response | string | undefined = xhr.responseText;+if (options.json) {try {- body = JSON.parse(body);+ responseBody = JSON.parse(xhr.responseText);} catch (e) {}}+let status = xhr.status;- if (status === 202 && body && body._status > 0) {- status = body._status;+ if (+ status === 202 &&+ responseBody &&+ typeof responseBody === "object" &&+ "_status" in responseBody &&+ (responseBody._status as number) > 0+ ) {+ status = responseBody._status as number;}if (status >= 200 && status <= 299) {if (options.transformResponse) {- body = options.transformResponse({ body, data });+ responseBody = options.transformResponse({+ body: responseBody as Response,+ data,+ });}- resolve(body);+ resolve(responseBody);} else {if (this.onResponseError) {- this.onResponseError({ body, status, metabaseVersion });+ this.onResponseError({+ body: responseBody,+ status,+ metabaseVersion,+ });}reject({status: status,- data: body,+ data: responseBody,isCancelled: isCancelled,});}if (!options.noEvent) {- this.emit(status, url);+ this.emit(String(status), url);}}};@@ -302,13 +415,13 @@ export class Api extends EventEmitter {}async _makeRequestWithFetch(- method,- url,- headers,- requestBody,- data,- options,- ) {+ method: string,+ url: string,+ headers: Record<string, string>,+ requestBody: string | FormData | undefined,+ data: Record<string, unknown>,+ options: RequestOptions,+ ): Promise<unknown> {const controller = options.controller || new AbortController();const signal = options.signal ?? controller.signal;options.cancelled?.then(() => controller.abort());@@ -324,16 +437,25 @@ export class Api extends EventEmitter {return fetch(request).then((response) => {const unreadResponse = response.clone();- return response.text().then((body) => {+ return response.text().then((bodyText) => {+ let body: string | Response | undefined = bodyText;+if (options.json) {try {- body = JSON.parse(body);+ body = JSON.parse(bodyText);} catch (e) {}}let status = response.status;- if (status === 202 && body && body._status > 0) {- status = body._status;+ if (+ status === 202 &&+ body &&+ typeof body === "object" &&+ "_status" in body &&+ body._status &&+ (body._status as number) > 0+ ) {+ status = (body as Record<string, number>)._status;}const token = response.headers.get(ANTI_CSRF_HEADER);@@ -344,13 +466,13 @@ export class Api extends EventEmitter {}if (!options.noEvent) {- this.emit(status, url);+ this.emit(String(status), url);}if (status >= 200 && status <= 299) {if (options.transformResponse) {body = options.transformResponse({- body,+ body: body as Response,data,response: unreadResponse,});@@ -365,7 +487,7 @@ export class Api extends EventEmitter {}});})- .catch((error) => {+ .catch((error: unknown) => {if (signal.aborted) {throw { isCancelled: true };} else {@@ -374,19 +496,20 @@ export class Api extends EventEmitter {});}- /**- * @param {import('metabase/plugins/oss/api').OnBeforeRequestHandlerConfig} data- * @return {Promise<import('metabase/plugins/oss/api').OnBeforeRequestHandlerConfig>}- */- async apiRequestManipulationMiddleware(requestConfig) {+ async apiRequestManipulationMiddleware(+ requestConfig: OnBeforeRequestHandlerConfig,+ ): Promise<OnBeforeRequestHandlerConfig> {let { method, url, options, data } = requestConfig;/*** Handlers order is important.* Handlers are executed in order and each handler uses the data returned by a previous handler.- * @type {import('metabase/plugins/oss/api').OnBeforeRequestHandler[]}*/- const handlers = [];+ const handlers: Array<+ (+ data: OnBeforeRequestHandlerConfig,+ ) => Promise<void | OnBeforeRequestHandlerConfig>+ > = [];if (isEmbeddingSdk()) {handlers.push(@@ -453,10 +576,10 @@ const instance = new Api();export default instance;export const { GET, POST, PUT, DELETE } = instance;-export const setLocaleHeader = (locale) => {+export const setLocaleHeader = (locale: string | null | undefined): void => {/* `X-Metabase-Locale` is a header that the BE stores as *user* locale for the scope of the request.* We need it to localize downloads. It *currently* only work if there is a user, so it won't work* for public/static embedding.*/- DEFAULT_OPTIONS.headers["X-Metabase-Locale"] = locale ?? undefined;+ DEFAULT_OPTIONS.headers["X-Metabase-Locale"] = locale ?? undefined!;};diff --git a/frontend/src/metabase/utils/api.unit.spec.js b/frontend/src/metabase/utils/api.unit.spec.jsdeleted file mode 100644index 81db063c04d..00000000000--- a/frontend/src/metabase/utils/api.unit.spec.js+++ /dev/null@@ -1,167 +0,0 @@-import fetchMock from "fetch-mock";--import api, { GET, POST, PUT } from "metabase/utils/api";-api.basename = "";--describe("api", () => {- const successResponse = { body: { status: "ok" } };-- it("should GET", async () => {- fetchMock.get("path:/hello", successResponse);- const hello = GET("/hello");- const response = await hello();- expect(response).toEqual({ status: "ok" });- });-- it("GET should throw on 503 with no retry", async () => {- fetchMock.get("path:/hello", 503);- const hello = GET("/hello", { retry: false });- await expect(hello()).rejects.toEqual(- expect.objectContaining({ status: 503 }),- );- });-- it("should POST", async () => {- fetchMock.post("path:/hello", successResponse);- const hello = POST("/hello");- const response = await hello();- expect(response).toEqual({ status: "ok" });- });-- it("should PUT with remaining params as body", async () => {- expect.assertions(1);- fetchMock.put("path:/hello/123", async (call) => {- const body = await call?.request?.json();- expect(body).toEqual({ other: "stuff" });- return 200;- });- await PUT("/hello/:id")({ id: 123, other: "stuff" });- });-- it("should PUT with a specific params as the body", async () => {- expect.assertions(1);- fetchMock.put("path:/hello/123", async (call) => {- const body = await call?.request?.json();- expect(body).toEqual(["i", "am", "an", "array"]);- return 200;- });- await PUT("/hello/:id")(- { id: 123, notAnObject: ["i", "am", "an", "array"] },- { bodyParamName: "notAnObject" },- );- });-- it("POST should throw on 503 with no retry", async () => {- expect.assertions(1);- fetchMock.post("path:/hello", 503);- const hello = POST("/hello", { retry: false });- await expect(hello()).rejects.toEqual(- expect.objectContaining({ status: 503 }),- );- });-- it("GET should retry and succeed if 503 then 200", async () => {- expect.assertions(1);- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- successResponse,- );- const hello = GET("/hello", { retry: true });- const response = await hello();- expect(response).toEqual({ status: "ok" });- });-- const RETRY_THREE_TIMES = {- retryCount: 3,- retryDelayIntervals: [1, 1, 1],- };-- it("GET should fail if after retryCount it still returns 503", async () => {- expect.assertions(1);- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- const limitedRetryGET = api._makeMethod("GET", RETRY_THREE_TIMES);- const hello = limitedRetryGET("/hello", { retry: true });- await expect(hello()).rejects.toEqual(- expect.objectContaining({ status: 503 }),- );- });-- it("GET should succeed if the last attempt succeeds", async () => {- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- 503,- );- fetchMock.getOnce(- {- url: "path:/hello",- },- successResponse,- );- const limitedRetryGET = api._makeMethod("GET", RETRY_THREE_TIMES);- const hello = limitedRetryGET("/hello", { retry: true });- const response = await hello();- expect(response).toEqual({ status: "ok" });- });-- it("should use _status from body when HTTP status is 202", async () => {- fetchMock.get("path:/async-status", {- status: 202,- body: {- _status: 400,- message: "error message",- },- });- const asyncStatus = GET("/async-status");- await expect(asyncStatus()).rejects.toEqual(- expect.objectContaining({- status: 400,- data: expect.objectContaining({ message: "error message" }),- }),- );- });-});diff --git a/frontend/src/metabase/utils/api.unit.spec.ts b/frontend/src/metabase/utils/api.unit.spec.tsindex 43323953cd4..ea9576e3d75 100644--- a/frontend/src/metabase/utils/api.unit.spec.ts+++ b/frontend/src/metabase/utils/api.unit.spec.ts@@ -22,6 +22,7 @@ describe("api", () => {method: "GET" as const,url: "/api/test",options: { hasBody: false, json: true },+ data: {},};const result =@@ -35,6 +36,7 @@ describe("api", () => {method: "POST" as const,url: "/api/test",options: { hasBody: true, json: true, headers: { "X-Test": "value" } },+ data: {},};// Mock a handler that returns void@@ -58,6 +60,7 @@ describe("api", () => {method: "GET" as const,url: "/api/original",options: { hasBody: false, json: true },+ data: {},};const expectedUrl = "/api/modified";@@ -89,6 +92,7 @@ describe("api", () => {method: "GET" as const,url: "/api/original",options: { hasBody: false, json: true },+ data: {},};const modifications = {@@ -117,6 +121,7 @@ describe("api", () => {headers: { "X-Original": "value" },retry: true,},+ data: {},};const newHeaders = { "X-Modified": "new-value" };@@ -152,6 +157,7 @@ describe("api", () => {method: "GET" as const,url: "/api/start",options: { hasBody: false, counter: 0 },+ data: {},};const executionOrder: number[] = [];@@ -233,6 +239,7 @@ describe("api", () => {method: "POST" as const,url: "/api/async",options: { hasBody: true, json: true },+ data: {},};const asyncHandler = jest.fn(async (data: OnBeforeRequestHandlerData) => {@@ -262,6 +269,7 @@ describe("api", () => {method: "GET" as const,url: "/api/test",options: { hasBody: false },+ data: {},};jest@@ -299,6 +307,7 @@ describe("api", () => {method: "POST" as const,url: "/api/complex",options: complexOptions,+ data: {},};jestdiff --git a/frontend/src/metabase/utils/click-behavior.ts b/frontend/src/metabase/utils/click-behavior.tsnew file mode 100644index 00000000000..f76bb73948e--- /dev/null+++ b/frontend/src/metabase/utils/click-behavior.ts@@ -0,0 +1,112 @@+import { msgid, ngettext, t } from "ttag";++import { Dashboards } from "metabase/entities/dashboards";+import { Questions } from "metabase/entities/questions";+import Question from "metabase-lib/v1/Question";+import type {+ ClickBehavior,+ ColumnSettings,+ DashboardCard,+ DatasetQuery,+} from "metabase-types/api";++type LinkTargetClickBehavior = {+ type: "link";+ linkType: "question" | "dashboard";+ targetId?: number;+};++export function getClickBehaviorDescription(dashcard: DashboardCard): string {+ const noBehaviorMessage = hasActionsMenu(dashcard)+ ? t`Open the drill-through menu`+ : t`Do nothing`;+ if (isTableDisplay(dashcard)) {+ const columnSettings =+ dashcard.visualization_settings?.column_settings ?? {};+ const count = Object.values(columnSettings).filter(+ (settings) => settings.click_behavior != null,+ ).length;+ if (count === 0) {+ return noBehaviorMessage;+ }+ return ngettext(+ msgid`${count} column has custom behavior`,+ `${count} columns have custom behavior`,+ count,+ );+ }+ const clickBehavior = dashcard.visualization_settings?.click_behavior as+ | ClickBehavior+ | undefined;+ if (clickBehavior == null) {+ return noBehaviorMessage;+ }+ if (clickBehavior.type === "link") {+ const { linkType } = clickBehavior;+ return linkType == null+ ? t`Go to...`+ : linkType === "dashboard"+ ? t`Go to dashboard`+ : linkType === "question"+ ? t`Go to question`+ : t`Go to url`;+ }++ return t`Filter this dashboard`;+}++export function hasActionsMenu(dashcard: DashboardCard): boolean {+ const datasetQuery = dashcard.card.dataset_query;+ if (!datasetQuery) {+ return false;+ }+ // This seems to work, but it isn't the right logic.+ // The right thing to do would be to check for any drills. However, we'd need a "clicked" object for that.+ const question = Question.create({+ dataset_query: datasetQuery as DatasetQuery,+ });+ return !question.isNative();+}++export function isTableDisplay(dashcard: DashboardCard): boolean {+ return dashcard?.card?.display === "table";+}++export function getLinkTargets(+ settings:+ | {+ click_behavior?: ClickBehavior;+ column_settings?: Record<string, ColumnSettings>;+ }+ | null+ | undefined,+) {+ const { click_behavior, column_settings = {} } = settings ?? {};+ return [+ click_behavior,+ ...Object.values(column_settings).map(+ (colSettings) => colSettings.click_behavior,+ ),+ ]+ .filter(hasLinkedQuestionOrDashboard)+ .map(mapLinkedEntityToEntityQuery);+}++function hasLinkedQuestionOrDashboard(+ behavior: ClickBehavior | null | undefined,+): behavior is LinkTargetClickBehavior {+ if (behavior?.type === "link") {+ return (+ behavior.linkType === "question" || behavior.linkType === "dashboard"+ );+ }+ return false;+}++function mapLinkedEntityToEntityQuery(behavior: LinkTargetClickBehavior) {+ return {+ entity: behavior.linkType === "question" ? Questions : Dashboards,+ entityType: behavior.linkType,+ entityId: behavior.targetId,+ };+}diff --git a/frontend/src/metabase/utils/dashboard_grid.js b/frontend/src/metabase/utils/dashboard_grid.tssimilarity index 87%rename from frontend/src/metabase/utils/dashboard_grid.jsrename to frontend/src/metabase/utils/dashboard_grid.tsindex 4bf5afd0506..fcef2693d61 100644--- a/frontend/src/metabase/utils/dashboard_grid.js+++ b/frontend/src/metabase/utils/dashboard_grid.ts@@ -24,21 +24,28 @@ export const DEFAULT_CARD_SIZE = { width: 4, height: 4 };export const MIN_ROW_HEIGHT = 40;+type CardPosition = {+ col: number;+ row: number;+ size_x: number;+ size_y: number;+};+// returns the first available position from left to right, top to bottom, based on the existing cards, item size, and// grid width. NOTE: If you change the way this function works, please change `get-position-for-new-dashcard` in// https://github.com/metabase/metabase/blob/master/src/metabase/dashboards/autoplace.cljexport function getPositionForNewDashCard(- cards,+ cards: CardPosition[],size_x = DEFAULT_CARD_SIZE.width,size_y = DEFAULT_CARD_SIZE.height,width = GRID_WIDTH,-) {+): CardPosition {let row = 0;let col = 0;while (row < 1000) {while (col <= width - size_x) {let good = true;- const position = { col, row, size_x, size_y };+ const position: CardPosition = { col, row, size_x, size_y };for (const card of cards) {if (intersects(card, position)) {good = false;@@ -57,7 +64,7 @@ export function getPositionForNewDashCard(return { col, row, size_x, size_y };}-function intersects(a, b) {+function intersects(a: CardPosition, b: CardPosition): boolean {return !(b.col >= a.col + a.size_x ||b.col + b.size_x <= a.col ||@@ -68,8 +75,8 @@ function intersects(a, b) {// for debugging/*eslint-disable */-function printGrid(cards, width) {- let grid = [];+function printGrid(cards: CardPosition[], width: number) {+ let grid: number[][] = [];for (let card of cards) {for (let col = card.col; col < card.col + card.size_x; col++) {for (let row = card.row; row < card.row + card.size_y; row++) {@@ -85,5 +92,4 @@ function printGrid(cards, width) {}console.log("\n" + grid.map((row) => row.join(".")).join("\n") + "\n");}-/*eslint-enable */diff --git a/frontend/src/metabase/utils/dayjs-parse-zone-plugin.js b/frontend/src/metabase/utils/dayjs-parse-zone-plugin.tssimilarity index 69%rename from frontend/src/metabase/utils/dayjs-parse-zone-plugin.jsrename to frontend/src/metabase/utils/dayjs-parse-zone-plugin.tsindex 6dc50a63c5d..7c8e894b6ad 100644--- a/frontend/src/metabase/utils/dayjs-parse-zone-plugin.js+++ b/frontend/src/metabase/utils/dayjs-parse-zone-plugin.ts@@ -1,13 +1,16 @@+import type { ConfigType, Dayjs, OptionType, PluginFunc } from "dayjs";+// This is the copy of https://github.com/iamkun/dayjs/pull/2060 which implements parseZone// which we rely on when using momentjs so we need this plugin to be able to migrate from momentjs// @authors: LucaColonnello and all contributors from https://github.com/iamkun/dayjs/issues/651#issuecomment-763033265// The colon is made optional with ':?' to support both '+0100' and '+01:00' timezone formats.+const REGEX_TIMEZONE_OFFSET_FORMAT = /^(.*)([+-])(\d{2}):?(\d{2})|(Z)$/;-const parseOffset = (dateString) =>+const parseOffset = (dateString: string): RegExpMatchArray | null =>dateString.match(REGEX_TIMEZONE_OFFSET_FORMAT);-const formatOffset = (parsedOffset) => {+const formatOffset = (parsedOffset: RegExpMatchArray): number => {const [, , sign, tzHour, tzMinute] = parsedOffset;const uOffset = parseInt(tzHour, 10) * 60 + parseInt(tzMinute, 10);return sign === "+" ? uOffset : -uOffset;@@ -20,17 +23,25 @@ const formatOffset = (parsedOffset) => {* This plugins depends on the UTC plugin. To support the custom format option,* you will need the CustomParseFormat plugin too.*/-const pluginFunc = (option, dayjsClass, dayjsFactory) => {- dayjsFactory.parseZone = function (date, format, locale, strict) {- if (typeof format === "string") {- format = { format };++const pluginFunc: PluginFunc = (_option, _dayjsClass, dayjsFactory) => {+ dayjsFactory.parseZone = function (+ date?: ConfigType,+ format?: OptionType,+ locale?: string,+ strict?: boolean,+ ): Dayjs {+ let parsedFormat = format;+ if (typeof parsedFormat === "string") {+ parsedFormat = { format: parsedFormat };}if (typeof date !== "string") {- return dayjsFactory(date, format, locale, strict);+ return dayjsFactory(date, parsedFormat, locale, strict);}const match = parseOffset(date);if (match === null) {return dayjsFactory(date, {+ // @ts-expect-error $offset is not defined in type definition, we'll keep it for guaranteed compatibility after migrating to ts$offset: 0,});}@@ -39,7 +50,7 @@ const pluginFunc = (option, dayjsClass, dayjsFactory) => {date,{utc: true,- ...format,+ ...(parsedFormat as object),},locale,strict,@@ -62,8 +73,9 @@ const pluginFunc = (option, dayjsClass, dayjsFactory) => {return dayjsFactory(adjustedDateTime,{+ // @ts-expect-error $offset is not defined in type definition, we'll keep it for guaranteed compatibility after migrating to ts$offset: offset,- ...format,+ ...(parsedFormat as object),},locale,strict,diff --git a/frontend/src/metabase/utils/embed.js b/frontend/src/metabase/utils/embed.tssimilarity index 74%rename from frontend/src/metabase/utils/embed.jsrename to frontend/src/metabase/utils/embed.tsindex 958972cc0be..d9481d7ff19 100644--- a/frontend/src/metabase/utils/embed.js+++ b/frontend/src/metabase/utils/embed.ts@@ -3,16 +3,17 @@ import _ from "underscore";import CS from "metabase/css/core/index.css";import { setInitialUrlOptions } from "metabase/redux/embed";+import type { Dispatch } from "metabase/redux/store";import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";// detect if this page is embedded in itself, i.e. it's a embed preview// will need to do something different if we ever embed metabase in itself for another reasonexport const IS_EMBED_PREVIEW = IFRAMED_IN_SELF;-export function initializeEmbedding(store) {+export function initializeEmbedding(store: { dispatch: Dispatch }): void {if (isWithinIframe()) {- let currentHref;- let currentFrame;+ let currentHref: string | undefined;+ let currentFrame: ReturnType<typeof getFrameSpec> | undefined;// NOTE: history.listen and window's onhashchange + popstate events were not// enough to catch all URL changes, so just poll for now :(setInterval(() => {@@ -21,7 +22,10 @@ export function initializeEmbedding(store) {sendMessage({type: "location",// extract just the string properties from window.location- location: _.pick(location, (v) => typeof v === "string"),+ location: _.pick(+ location,+ (v: unknown) => typeof v === "string",+ ) as Record<string, string>,});currentHref = location.href;}@@ -34,7 +38,7 @@ export function initializeEmbedding(store) {currentFrame = frame;}}, 100);- window.addEventListener("message", (e) => {+ window.addEventListener("message", (e: MessageEvent) => {if (e.source === window.parent && e.data.metabase) {if (e.data.metabase.type === "location") {store.dispatch(push(e.data.metabase.location));@@ -45,7 +49,11 @@ export function initializeEmbedding(store) {}}-function sendMessage(message) {+type MetabaseMessage =+ | { type: "location"; location: Record<string, string> }+ | { type: "frame"; frame: ReturnType<typeof getFrameSpec> };++function sendMessage(message: MetabaseMessage): void {// Reason for using "*" (see #18824)// 1) We cannot use MetabaseSettings.get("embedding-app-origin") because the format is different// - the setting value can have multiple URLs but postMessage only supports one URL@@ -56,7 +64,7 @@ function sendMessage(message) {window.parent.postMessage({ metabase: message }, "*");}-function isFitViewportMode() {+function isFitViewportMode(): boolean {const root = document.getElementById("root");// get the first div, which may be preceded by style nodes@@ -68,7 +76,11 @@ function isFitViewportMode() {return false;}-function getFrameSpec() {+type FrameSpec =+ | { mode: "fit"; height: number }+ | { mode: "normal"; height: number };++function getFrameSpec(): FrameSpec {if (isFitViewportMode()) {return { mode: "fit", height: getScrollHeight() };} else {@@ -76,16 +88,17 @@ function getFrameSpec() {}}-function defaultGetScrollHeight() {+function defaultGetScrollHeight(): number {return document.body.scrollHeight;}-function getScrollHeight() {+function getScrollHeight(): number {const appBarHeight =document.getElementById("[data-element-id=app-bar]")?.offsetHeight ?? 0;const dashboardHeaderHeight =- document.querySelector("[data-element-id=dashboard-header-container]")- ?.offsetHeight ?? 0;+ document.querySelector<HTMLElement>(+ "[data-element-id=dashboard-header-container]",+ )?.offsetHeight ?? 0;const dashboardContentHeight =document.querySelector("[data-element-id=dashboard-parameters-and-cards]")?.scrollHeight ?? 0;diff --git a/frontend/src/metabase/utils/entities.js b/frontend/src/metabase/utils/entities.jsdeleted file mode 100644index 92a17450f68..00000000000--- a/frontend/src/metabase/utils/entities.js+++ /dev/null@@ -1,686 +0,0 @@-/*- * # Entities abstract the interface between the back-end and the front-end.- *- * ## Endpoint requirements for entities:- *- * When fetching a list, each item of the list must include an `id` key/value pair.- *- * JSON must wrap response inside a `{ "data" : { …your data } }` structure.- *- * ## Required Properties:- *- * name:- * a string in plural form- * examples:- * "questions", "dashboards"- *- * path:- * a uri- * starting with "/api/"- * conventionally followed by the entity name in singular form- * examples:- * "/api/card", "/api/dashboard"- *- * ## Optional properties:- *- * api:- *- * here you can override the basic entity methods like `list`, `create`, `get`, `update`, `delete` (OR see `path` below)- *- * schema:- * normalizr schema- * default:- * `new schema.Entity(entity.name)`- *- * ## How to create a bare-bones entity- *- * Say we want to create a "books" entity, to be able to fetch a list of "books".- *- * Add the following line to `frontend/src/metabase/entities.index.js`:- *- * export { default as books } from "./books"- *- * Create file `frontend/src/metabase/entities/books.js`- *- * Add the following to it:- *- * import { createEntity } from "metabase/utils/entities";-- * const Books = createEntity({- * name: "books",- * nameOne: "book",- * path: "/api/book",- * });- *- * export default Books;- *- * ## How to consume an entity:- *- * Near the top of a container file, import the entity:- *- * import Book from "metabase/entities/books";- *- * Near the bottom of the container file, add the entity to a `compose` statement:- *- * export default _.compose(- * Book.loadList(),- * connect(mapStateToProps),- * )(BookContainer);- */--import { createSelector } from "@reduxjs/toolkit";-import { getIn, merge } from "icepick";-import inflection from "inflection"; // NOTE: need to use inflection directly here due to circular dependency-import { denormalize, normalize, schema } from "normalizr";-import createCachedSelector from "re-reselect";-import _ from "underscore";--import requestsReducer, { setRequestUnloaded } from "metabase/redux/requests";-import { addUndo } from "metabase/redux/undo";-import { DELETE, GET, POST, PUT } from "metabase/utils/api";-import {- combineReducers,- compose,- handleEntities,- withAction,- withCachedDataAndRequestState,- withRequestState,-} from "metabase/utils/redux";--const EMPTY_ENTITY_QUERY = {};--/**- * @deprecated use "metabase/api" instead- */-export function createEntity(def) {- const entity = { ...def };-- if (!entity.nameOne) {- entity.nameOne = inflection.singularize(entity.name);- }- if (!entity.nameMany) {- entity.nameMany = entity.name;- }-- if (!entity.displayNameOne) {- entity.displayNameOne = entity.nameOne;- }- if (!entity.displayNameMany) {- entity.displayNameMany = entity.nameMany;- }-- // defaults- if (!entity.schema) {- entity.schema = new schema.Entity(entity.name);- }-- // API- if (!entity.api) {- entity.api = {};- }- if (entity.path) {- const path = entity.path; // Flow not recognizing path won't be undefined- entity.api = {- list: GET(`${path}`),- create: POST(`${path}`),- get: GET(`${path}/:id`),- update: PUT(`${path}/:id`),- delete: DELETE(`${path}/:id`),- ...entity.api,- };- }-- const getQueryKey = (entityQuery) => JSON.stringify(entityQuery || null);- const getObjectStatePath = (entityId) => ["entities", entity.name, entityId];- const getListStatePath = (entityQuery) =>- ["entities", entity.name + "_list"].concat(getQueryKey(entityQuery));-- entity.getQueryKey = getQueryKey;- entity.getObjectStatePath = getObjectStatePath;- entity.getListStatePath = getListStatePath;-- const getWritableProperties = (object) =>- entity.writableProperties != null- ? _.pick(object, "id", ...entity.writableProperties)- : object;-- // ACTION TYPES- const CREATE_ACTION = `metabase/entities/${entity.name}/CREATE`;- const FETCH_ACTION = `metabase/entities/${entity.name}/FETCH`;- const UPDATE_ACTION = `metabase/entities/${entity.name}/UPDATE`;- const DELETE_ACTION = `metabase/entities/${entity.name}/DELETE`;- const FETCH_LIST_ACTION = `metabase/entities/${entity.name}/FETCH_LIST`;- const INVALIDATE_LISTS_ACTION = `metabase/entities/${entity.name}/INVALIDATE_LISTS`;-- entity.actionTypes = {- CREATE: CREATE_ACTION,- FETCH: FETCH_ACTION,- UPDATE: UPDATE_ACTION,- DELETE: DELETE_ACTION,- FETCH_LIST: FETCH_LIST_ACTION,- INVALIDATE_LISTS_ACTION: INVALIDATE_LISTS_ACTION,- ...(entity.actionTypes || {}),- };-- entity.actionDecorators = {- ...(entity.actionDecorators || {}),- };-- // normalize helpers- entity.normalize = (object, schema = entity.schema) => ({- // include raw `object` (and alias under nameOne) for convenience- object,- [entity.nameOne]: object,- // include standard normalizr properties, `result` and `entities`- ...normalize(object, schema),- });-- entity.normalizeList = (list, schema = entity.schema) => ({- // include raw `list` (and alias under nameMany) for convenience- list,- [entity.nameMany]: list,- // include standard normalizr properties, `result` and `entities`- ...normalize(list, [schema]),- });-- // thunk decorators:-- // same as withRequestState, but with automatic prefix- function withEntityRequestState(getSubStatePath) {- return withRequestState((...args) => [- "entities",- entity.name,- ...getSubStatePath(...args),- ]);- }-- function withEntityActionDecorators(action) {- return entity.actionDecorators[action] || ((_) => _);- }-- // `objectActions` are for actions that accept an entity as their first argument,- // and they are bound to instances when `wrapped: true` is passed to `EntityListLoader`- entity.objectActions = {- fetch: compose(- withAction(FETCH_ACTION),- withCachedDataAndRequestState(- ({ id }) => [...getObjectStatePath(id)],- ({ id }) => [...getObjectStatePath(id), "fetch"],- (entityQuery) => getQueryKey(entityQuery),- ),- withEntityActionDecorators("fetch"),- )(- (entityQuery, options = {}) =>- async (dispatch, getState) =>- entity.normalize(- await entity.api.get(entityQuery, options, dispatch, getState),- ),- ),-- create: compose(- withAction(CREATE_ACTION),- withEntityRequestState(() => ["create"]),- withEntityActionDecorators("create"),- )((entityObject) => async (dispatch, getState) => {- return entity.normalize(- await entity.api.create(- getWritableProperties(entityObject),- dispatch,- getState,- ),- );- }),-- update: compose(- withAction(UPDATE_ACTION),- withEntityRequestState((object) => [object.id, "update"]),- withEntityActionDecorators("update"),- )(- (entityObject, updatedObject = null, { notify } = {}) =>- async (dispatch, getState) => {- // save the original object for undo- const originalObject = getObject(getState(), {- entityId: entityObject.id,- });- // If a second object is provided just take the id from the first and- // update it with all the properties in the second- // NOTE: this is so that the object.update(updatedObject) method on- // the default entity wrapper class works correctly- if (updatedObject) {- entityObject = { id: entityObject.id, ...updatedObject };- }-- const result = entity.normalize(- await entity.api.update(- getWritableProperties(entityObject),- dispatch,- getState,- ),- );-- if (notify) {- if (notify.undo) {- // pick only the attributes that were updated- const undoObject = _.pick(- originalObject,- ...Object.keys(updatedObject || {}),- );- dispatch(- addUndo({- actions: [- entity.objectActions.update(- entityObject,- undoObject,- // don't show an undo for the undo- { notify: false },- ),- ],- ...notify,- }),- );- } else {- dispatch(addUndo(notify));- }- }- return result;- },- ),-- delete: compose(- withAction(DELETE_ACTION),- withEntityRequestState((object) => [object.id, "delete"]),- withEntityActionDecorators("delete"),- )((entityObject) => async (dispatch, getState) => {- await entity.api.delete(entityObject, dispatch, getState);- return {- entities: { [entity.name]: { [entityObject.id]: null } },- result: entityObject.id,- };- }),-- // user defined object actions should override defaults- ...(def.objectActions || {}),- };-- // ACTION CREATORS- entity.actions = {- fetchList: compose(- withAction(FETCH_LIST_ACTION),- withCachedDataAndRequestState(- (entityQuery) => [...getListStatePath(entityQuery)],- (entityQuery) => [...getListStatePath(entityQuery), "fetch"],- (entityQuery) => entity.getQueryKey(entityQuery),- ),- )((entityQuery = null) => async (dispatch, getState) => {- const fetched = await entity.api.list(- entityQuery || EMPTY_ENTITY_QUERY,- dispatch,- getState,- );- // for now at least paginated endpoints have a 'data' property that- // contains the actual entries, if that is on the response we should- // use that as the 'results'-- let results;- let metadata = {};-- if (fetched.data) {- const { data, ...rest } = fetched;- results = data;- metadata = rest;- } else {- results = fetched;- }-- if (!Array.isArray(results)) {- throw `Invalid response listing ${entity.name}`;- }- return {- ...entity.normalizeList(results),- metadata,- entityQuery,- };- }),-- invalidateLists: compose(- withAction(INVALIDATE_LISTS_ACTION),- withEntityActionDecorators("invalidateLists"),- )(() => null),-- // user defined actions should override defaults- ...entity.objectActions,- ...(def.actions || {}),- };-- // HACK: the above actions return the normalizr results- // (i.e. { entities, result }) rather than the loaded object(s), except- // for fetch and fetchList when the data is cached, in which case it returns- // the normalized object.- //- // This is a problem when we use the result of one of the actions as though- // though the action creator was an API client.- //- // For now just use this function until we figure out a cleaner way to do- // this. It will make it easy to find instances where we use the result of an- // action, and ensures a consistent result- //- // NOTE: this returns the normalized object(s), nested objects defined in- // the schema will be replaced with IDs.- //- // NOTE: A possible solution is to have an `updateEntities` action which is- // dispatched by the actions with the normalized data so that we can return- // the denormalized data from the action itself.- //- entity.HACK_getObjectFromAction = ({ payload }) => {- if (payload && "entities" in payload && "result" in payload) {- if (Array.isArray(payload.result)) {- return payload.result.map((id) => payload.entities[entity.name][id]);- } else {- return payload.entities[entity.name][payload.result];- }- } else {- return payload;- }- };-- // SELECTORS-- const getEntities = (state) => state.entities;- const getSettings = (state) => state.settings;-- // OBJECT SELECTORS-- const getEntityId = (state, props) =>- (props.params && props.params.entityId) || props.entityId;-- const getObject = createCachedSelector(- [getEntities, getEntityId],- (entities, entityId) => denormalize(entityId, entity.schema, entities),- )((state, { entityId } = {}) =>- typeof entityId === "object"- ? JSON.stringify(entityId)- : entityId- ? entityId- : "",- ); // must stringify objects-- // LIST SELECTORS-- const getEntityQueryId = (state, props) =>- getQueryKey(props && props.entityQuery);-- const getEntityLists = createSelector(- [getEntities],- (entities) => entities[`${entity.name}_list`],- );-- const getEntityList = createSelector(- [getEntityQueryId, getEntityLists],- (entityQueryId, lists) => lists[entityQueryId],- );-- const getEntityIds = createSelector(- [getEntityList],- (entities) => entities && entities.list,- );-- const getListMetadata = createSelector(- [getEntityList],- (entities) => entities && entities.metadata,- );-- const getList = createCachedSelector(- [getEntities, getEntityIds, getSettings],- // delegate to getObject- (entities, entityIds, settings) =>- entityIds &&- entityIds- .map((entityId) =>- entity.selectors.getObject({ entities, settings }, { entityId }),- )- .filter((e) => e != null), // deleted entities might remain in lists,- )((state, { entityQuery } = {}) =>- entityQuery ? JSON.stringify(entityQuery) : "",- );-- // REQUEST STATE SELECTORS-- const getStatePath = ({ entityId, entityQuery } = {}) =>- entityId != null- ? getObjectStatePath(entityId)- : getListStatePath(entityQuery);-- const getRequestStatePath = ({- entityId,- entityQuery,- requestType = "fetch",- } = {}) => [- "requests",- ...getStatePath({ entityId, entityQuery }),- requestType,- ];-- const defaultRequestState = {};- const getRequestState = (state, props) =>- getIn(state, getRequestStatePath(props)) || defaultRequestState;-- const getLoading = createSelector(- [getRequestState],- (requestState) => requestState.loading,- );- const getLoaded = createSelector(- [getRequestState],- (requestState) => requestState.loaded,- );- const getFetched = createSelector(- [getRequestState],- (requestState) => requestState.fetched,- );- const getError = createSelector(- [getRequestState],- (requestState) => requestState.error,- );-- const defaultSelectors = {- getEntityIds,- getList,- getObject,- getFetched,- getLoading,- getLoaded,- getError,- getListMetadata,- };- entity.selectors = {- ...defaultSelectors,- ...(def.selectors || {}),- ...(def.createSelectors ? def.createSelectors(defaultSelectors) : {}),- };-- entity.objectSelectors = {- getName(object) {- return object.name;- },- getIcon(object) {- return { name: "unknown" };- },- getColor(object) {- return undefined;- },- getCollection(object) {- return object.collection;- },- ...(def.objectSelectors || {}),- };-- // REDUCERS-- entity.reducers = {};-- entity.reducers[entity.name] = handleEntities(- /^metabase\/entities\//,- entity.name,- def.reducer,- );-- entity.reducers[entity.name + "_list"] = (- state = {},- { type, error, payload },- ) => {- if (error) {- return state;- }- if (type === FETCH_LIST_ACTION) {- if (payload && payload.result) {- const { entityQuery, metadata, result: list } = payload;- return {- ...state,- [getQueryKey(entityQuery)]: {- list,- metadata,- },- };- }- // NOTE: only add/remove from the "default" list (no entityQuery)- // TODO: just remove this entirely?- } else if (type === CREATE_ACTION && state[""]) {- return { ...state, "": state[""].concat([payload.result]) };- } else if (type === DELETE_ACTION && state[""]) {- return {- ...state,- "": state[""].filter((id) => id !== payload.result),- };- }- return state;- };-- // REQUEST STATE REDUCER-- // NOTE: ideally we'd only reset lists where there's a possibility the action,- // or even better, add/remove the item from appropriate lists in the reducer- // above. This will be difficult with pagination-- if (!entity.actionShouldInvalidateLists) {- entity.actionShouldInvalidateLists = (action) =>- action.type === CREATE_ACTION ||- action.type === DELETE_ACTION ||- action.type === UPDATE_ACTION ||- action.type === INVALIDATE_LISTS_ACTION;- }-- entity.requestsReducer = (state, action) => {- // reset all list request states when creating, deleting, or updating- // to force a reload- if (entity.actionShouldInvalidateLists(action)) {- return requestsReducer(- state,- setRequestUnloaded(["entities", entity.name + "_list"]),- );- }- return state;- };-- // OBJECT WRAPPER-- if (!entity.wrapEntity) {- // This is the default entity wrapper class implementation- //- // We automatically bind all objectSelectors and objectActions functions- //- // If a dispatch function is passed to the constructor the actions will be- // dispatched using it, otherwise the actions will be returned- //- class EntityWrapper {- _dispatch;-- constructor(object, dispatch = null) {- Object.assign(this, object);- this._dispatch = dispatch;- }- }- // object selectors- for (const [methodName, method] of Object.entries(entity.objectSelectors)) {- if (method) {- EntityWrapper.prototype[methodName] = function (...args) {- return method(this, ...args);- };- }- }- // object actions- for (const [methodName, method] of Object.entries(entity.objectActions)) {- if (method) {- EntityWrapper.prototype[methodName] = function (...args) {- if (this._dispatch) {- // if dispatch was provided to the constructor go ahead and dispatch- return this._dispatch(method(this, ...args));- } else {- // otherwise just return the action- return method(this, ...args);- }- };- }- }-- entity.wrapEntity = (object, dispatch = null) =>- new EntityWrapper(object, dispatch);- }-- // add container components and HOCs- require("metabase/entities/containers").addEntityContainers(entity);-- return entity;-}--export function combineEntities(entities) {- const entitiesMap = {};- const reducersMap = {};-- for (const entity of entities) {- if (entity.name in entitiesMap) {- console.warn(`Entity with name ${entity.name} already exists!`);- } else {- entitiesMap[entity.name] = entity;- Object.assign(reducersMap, entity.reducers);- }- }-- const requestsReducer = (state, action) => {- for (const entity of entities) {- if (entity.requestsReducer) {- state = entity.requestsReducer(state, action);- }- }- return state;- };-- return {- entities: entitiesMap,- reducers: reducersMap,- reducer: combineReducers(reducersMap),- requestsReducer,- };-}--// OBJECT ACTION DECORATORS--export const notify = (opts = {}, subject, verb) =>- merge({ notify: { subject, verb, undo: false } }, opts || {});--export const undo = (opts = {}, subject, verb) =>- merge({ notify: { subject, verb, undo: true } }, opts || {});--export async function entityCompatibleQuery(- entityQuery,- dispatch,- endpoint,- { forceRefetch = true } = {},-) {- const request = entityQuery === EMPTY_ENTITY_QUERY ? undefined : entityQuery;- const action = dispatch(endpoint.initiate(request, { forceRefetch }));-- try {- return await action.unwrap();- } finally {- action.unsubscribe?.();- }-}diff --git a/frontend/src/metabase/utils/entities.ts b/frontend/src/metabase/utils/entities.tsnew file mode 100644index 00000000000..fd4c08bd9a2--- /dev/null+++ b/frontend/src/metabase/utils/entities.ts@@ -0,0 +1,1076 @@+/*+ * # Entities abstract the interface between the back-end and the front-end.+ *+ * ## Endpoint requirements for entities:+ *+ * When fetching a list, each item of the list must include an `id` key/value pair.+ *+ * JSON must wrap response inside a `{ "data" : { …your data } }` structure.+ *+ * ## Required Properties:+ *+ * name:+ * a string in plural form+ * examples:+ * "questions", "dashboards"+ *+ * path:+ * a uri+ * starting with "/api/"+ * conventionally followed by the entity name in singular form+ * examples:+ * "/api/card", "/api/dashboard"+ *+ * ## Optional properties:+ *+ * api:+ *+ * here you can override the basic entity methods like `list`, `create`, `get`, `update`, `delete` (OR see `path` below)+ *+ * schema:+ * normalizr schema+ * default:+ * `new schema.Entity(entity.name)`+ *+ * ## How to create a bare-bones entity+ *+ * Say we want to create a "books" entity, to be able to fetch a list of "books".+ *+ * Add the following line to `frontend/src/metabase/entities.index.js`:+ *+ * export { default as books } from "./books"+ *+ * Create file `frontend/src/metabase/entities/books.js`+ *+ * Add the following to it:+ *+ * import { createEntity } from "metabase/lib/entities";++ * const Books = createEntity({+ * name: "books",+ * nameOne: "book",+ * path: "/api/book",+ * });+ *+ * export default Books;+ *+ * ## How to consume an entity:+ *+ * Near the top of a container file, import the entity:+ *+ * import Book from "metabase/entities/books";+ *+ * Near the bottom of the container file, add the entity to a `compose` statement:+ *+ * export default _.compose(+ * Book.loadList(),+ * connect(mapStateToProps),+ * )(BookContainer);+ */++import type { Reducer } from "@reduxjs/toolkit";+import { createSelector } from "@reduxjs/toolkit";+import { getIn, merge } from "icepick";+import inflection from "inflection"; // NOTE: need to use inflection directly here due to circular dependency+import { denormalize, normalize, schema } from "normalizr";+import createCachedSelector from "re-reselect";+import type React from "react";+import _ from "underscore";++import {+ type RequestsStateTree,+ requestsReducer,+ setRequestUnloaded,+} from "metabase/redux/requests";+import type { EntitiesState, State } from "metabase/redux/store";+import { addUndo } from "metabase/redux/undo";++import { DELETE, GET, POST, PUT } from "./api";+import {+ combineReducers,+ compose,+ withAction,+ withCachedDataAndRequestState,+ withRequestState,+} from "./redux";++const EMPTY_ENTITY_QUERY = {};++export type EntityId = string | number;++/**+ * The minimum shape required of an entity object: anything with an `id`.+ * Concrete entity types (Collection, Card, Dashboard, …) extend this implicitly+ * by having an `id` field. We avoid an `[key: string]: unknown` index signature+ * because it would prevent narrower types from being assignable to `EntityObject`.+ */+export type EntityObject = {+ id: EntityId;+ name?: string;+ collection?: unknown;+};++type NormalizedPayload = {+ entities?: Record<string, Record<EntityId, EntityObject>>;+ result?: EntityId | EntityId[];+};++type EntityAction = {+ payload?: NormalizedPayload;+};++// The entity framework is a runtime abstraction — consumers define selectors,+// action creators, and object methods with per-entity concrete types that can't be+// statically expressed here. These aliases document the intent of each `any`:++/** Redux dispatch accepted by entity actions. */++type AnyDispatch = (action: any) => any;+/** Redux getState accepted by entity thunks. */++type AnyGetState = () => any;+/** Action creator produced by `entity.actions` / `entity.objectActions`. Each entity+ * defines its own specific signatures, so we use a broad callable type here. */++type EntityActionCreator = (...args: any[]) => any;+/** Entity selector signature. Each entity defines its own specific selector signatures. */++type EntitySelector = (state: any, ...args: any[]) => any;+/** Entity query passed to list/fetch endpoints. Concrete shape depends on the entity. */++type EntityQuery = any;++/** Named selectors that every entity must expose. */+export type EntitySelectors = {+ getObject: EntitySelector;+ getList: EntitySelector;+ getEntityIds: EntitySelector;+ getLoading: EntitySelector;+ getLoaded: EntitySelector;+ getFetched: EntitySelector;+ getError: EntitySelector;+ getListMetadata: EntitySelector;+ getInitialCollectionId: EntitySelector;+ getExpandedCollectionsById: EntitySelector;+};++/** Shape returned by createEntity */+export type Entity = {+ // Names+ name: string;+ nameOne: string;+ nameMany: string;+ displayNameOne: string;+ displayNameMany: string;++ // Schema+ schema: schema.Entity;+ path?: string;++ // API — each method may accept any arguments (raw data + options objects)++ api: {+ list?: (...args: any[]) => Promise<+ | EntityObject[]+ | {+ data: EntityObject[];+ [key: string]: unknown;+ }+ >;+ create: (...args: any[]) => Promise<any>;+ get: (...args: any[]) => Promise<any>;+ update: (...args: any[]) => Promise<any>;+ delete: (...args: any[]) => Promise<any>;+ };++ // Action type constants. The values are strings at runtime, but consumers use them+ // with `builder.addCase(actionType, reducer)` and rely on the second arg being typed+ // as a `PayloadAction<any>` (matching the JS framework's behaviour). Typing them as+ // `any` here preserves that ergonomic.+ actionTypes: {+ CREATE: any;++ FETCH: any;++ UPDATE: any;++ DELETE: any;++ FETCH_LIST: any;++ INVALIDATE_LISTS_ACTION: any;++ [key: string]: any;+ };++ actionDecorators: Record<+ string,+ (action: EntityActionCreator) => EntityActionCreator+ >;++ // Path helpers+ getQueryKey: (entityQuery: EntityQuery) => string;+ getObjectStatePath: (entityId: EntityId) => (string | EntityId)[];+ getListStatePath: (entityQuery: EntityQuery) => string[];++ // Normalize helpers+ normalize: (+ object: EntityObject,+ entitySchema?: schema.Entity,+ ) => NormalizedPayload & { object: EntityObject };+ normalizeList: (+ list: EntityObject[],+ entitySchema?: schema.Entity,+ ) => NormalizedPayload & { list: EntityObject[] };++ // Actions (thunk action creators) — each entity defines its own signatures+ objectActions: Record<string, EntityActionCreator> & {+ fetch: EntityActionCreator;+ create: EntityActionCreator;+ update: EntityActionCreator;+ delete: EntityActionCreator;+ };++ actions: Record<string, EntityActionCreator> & {+ fetchList: EntityActionCreator;+ invalidateLists: EntityActionCreator;+ fetch: EntityActionCreator;+ create: EntityActionCreator;+ update: EntityActionCreator;+ delete: EntityActionCreator;+ };++ // Extract entity from dispatched action result. The return type depends on the+ // action's normalized payload and is best handled dynamically by consumers.++ HACK_getObjectFromAction: (action: any) => any;++ // Selectors+ selectors: EntitySelectors;++ // Per-entity object accessors. Each entity defines these with its own object type.+ objectSelectors: Record<string, (object: any, ...args: any[]) => any>;++ // Reducers+ reducer?: EntitiesReducer;+ reducers: Record<string, EntitiesReducer | Reducer<Record<string, unknown>>>;+ requestsReducer: (+ state: RequestsStateTree,+ action: { type: string },+ ) => RequestsStateTree;+ actionShouldInvalidateLists: (action: { type: string }) => boolean;++ // Writable properties (subset of entity fields sent to the API)+ writableProperties?: string[];++ // Wrap entity object with bound selectors/actions. The wrapper preserves the+ // input's properties and adds the entity's bound objectSelectors/objectActions+ // (e.g. `getName()`, `getIcon()`). Each entity defines its own object methods,+ // so we return `any` to allow consumers to use any wrapper-provided method.+ wrapEntity: (object: any, dispatch?: AnyDispatch | null) => any;++ // HOC factories and JSX components added by addEntityContainers at construction time.+ // These are always present on the returned entity, so consumers can rely on them.+ /** @deprecated HOCs are deprecated */++ load: (opts?: Record<string, unknown>) => any;+ /** @deprecated HOCs are deprecated */++ loadList: (opts?: Record<string, unknown>) => any;++ ListLoader: React.ComponentType<any>;+ // Accept nullable/undefined IDs: consumers commonly pass optional dashboard/card ids+ Name: React.ComponentType<+ { id: EntityId | null | undefined } & Record<string, any>+ >;+};++/**+ * Optional RTK Query bridge that a few entities use to expose RTK Query hooks+ * through the entity abstraction. Structure is deliberately loose — each entity+ * attaches a different set of helpers.+ */++type EntityRtkBridge = Record<string, any>;+type EntitiesReducer = Reducer<+ Partial<EntitiesState> | undefined,+ { type: string; payload: EntitiesState }+>;++type EntityDef = {+ name: string;+ nameOne?: string;+ nameMany?: string;+ displayNameOne?: string;+ displayNameMany?: string;+ path?: string;+ schema?: schema.Entity;+ api?: Partial<Entity["api"]>;+ writableProperties?: string[];+ actionTypes?: Record<string, string>;+ actionDecorators?: Record<+ string,+ (action: EntityActionCreator) => EntityActionCreator+ >;+ objectActions?: Record<string, EntityActionCreator>;+ actions?: Record<string, EntityActionCreator>;+ selectors?: Partial<EntitySelectors>;+ createSelectors?: (+ defaultSelectors: Partial<EntitySelectors>,+ ) => Partial<EntitySelectors>;+ objectSelectors?: Partial<Entity["objectSelectors"]>;+ // Reducers in entity defs typically destructure `{ type, payload }` from the action+ // and accept any payload shape, so we type the action loosely here.++ reducer?: EntitiesReducer;+ wrapEntity?: Entity["wrapEntity"];+ requestsReducer?: Entity["requestsReducer"];+ actionShouldInvalidateLists?: Entity["actionShouldInvalidateLists"];+ rtk?: EntityRtkBridge;+ // Per-entity custom fields (e.g. `getAnalyticsMetadata`, `form`, `forms`).+ // These are attached to the entity object and used by entity-aware machinery.++ [key: string]: any;+};++// helper for working with normalizr+// merge each entity from newEntities with existing entity, if any+// this ensures partial entities don't overwrite existing entities with more properties+export function mergeEntities<T = EntitiesState>(+ entities: T,+ newEntities: Partial<T>,+): T {+ const result = { ...entities };+ // Casting is necessary here because Object.keys always returns string[]+ const ids = Object.keys(newEntities) as Array<keyof T>;++ for (const id of ids) {+ const entry = newEntities[id];+ if (entry == null) {+ delete result[id];+ } else {+ result[id] = { ...(result[id] ?? {}), ...entry };+ }+ }+ return result;+}++// helper for working with normalizr+// reducer that merges payload.entities+export function handleEntities(+ actionPattern: RegExp,+ entityType: string,+ reducer?: EntitiesReducer,+): EntitiesReducer {+ return (state, action) => {+ const entities = getIn(action, ["payload", "entities", entityType]);+ if (state && actionPattern.test(action.type) && entities) {+ state = mergeEntities(state, entities);+ }+ return reducer?.(state, action) ?? state ?? {};+ };+}++/**+ * @deprecated use "metabase/api" instead+ */+export function createEntity(def: EntityDef): Entity {+ // We use a mutable object internally during construction+ // then return it typed as Entity at the end.+ const entity = { ...def } as Entity;++ if (!entity.nameOne) {+ entity.nameOne = inflection.singularize(entity.name);+ }+ if (!entity.nameMany) {+ entity.nameMany = entity.name;+ }++ if (!entity.displayNameOne) {+ entity.displayNameOne = entity.nameOne;+ }+ if (!entity.displayNameMany) {+ entity.displayNameMany = entity.nameMany;+ }++ // defaults+ if (!entity.schema) {+ entity.schema = new schema.Entity(entity.name);+ }++ if (entity.path) {+ const path = entity.path;+ const defaultApi: Entity["api"] = {+ list: GET(`${path}`),+ create: POST(`${path}`),+ get: GET(`${path}/:id`),+ update: PUT(`${path}/:id`),+ delete: DELETE(`${path}/:id`),+ };+ // merge: user-provided overrides win over path-derived defaults+ entity.api = { ...defaultApi, ...entity.api };+ }++ const getQueryKey = (entityQuery: EntityQuery): string =>+ JSON.stringify(entityQuery || null);+ const getObjectStatePath = (entityId: EntityId): (string | EntityId)[] => [+ "entities",+ entity.name,+ entityId,+ ];+ const getListStatePath = (entityQuery: EntityQuery): string[] =>+ ["entities", entity.name + "_list"].concat(getQueryKey(entityQuery));++ entity.getQueryKey = getQueryKey;+ entity.getObjectStatePath = getObjectStatePath;+ entity.getListStatePath = getListStatePath;++ const getWritableProperties = (+ object: EntityObject,+ ): Partial<EntityObject> =>+ entity.writableProperties != null+ ? _.pick(object, "id", ...entity.writableProperties)+ : object;++ // ACTION TYPES+ const CREATE_ACTION = `metabase/entities/${entity.name}/CREATE`;+ const FETCH_ACTION = `metabase/entities/${entity.name}/FETCH`;+ const UPDATE_ACTION = `metabase/entities/${entity.name}/UPDATE`;+ const DELETE_ACTION = `metabase/entities/${entity.name}/DELETE`;+ const FETCH_LIST_ACTION = `metabase/entities/${entity.name}/FETCH_LIST`;+ const INVALIDATE_LISTS_ACTION = `metabase/entities/${entity.name}/INVALIDATE_LISTS`;++ entity.actionTypes = {+ CREATE: CREATE_ACTION,+ FETCH: FETCH_ACTION,+ UPDATE: UPDATE_ACTION,+ DELETE: DELETE_ACTION,+ FETCH_LIST: FETCH_LIST_ACTION,+ INVALIDATE_LISTS_ACTION: INVALIDATE_LISTS_ACTION,+ ...(def.actionTypes || {}),+ };++ entity.actionDecorators = {+ ...(def.actionDecorators || {}),+ };++ // normalize helpers+ entity.normalize = (+ object: EntityObject,+ entitySchema: schema.Entity = entity.schema,+ ) => ({+ object,+ [entity.nameOne]: object,+ ...normalize(object, entitySchema),+ });++ entity.normalizeList = (+ list: EntityObject[],+ entitySchema: schema.Entity = entity.schema,+ ) => ({+ list,+ [entity.nameMany]: list,+ ...normalize(list, [entitySchema]),+ });++ // thunk decorators:++ // same as withRequestState, but with automatic prefix++ function withEntityRequestState(+ getSubStatePath: (...args: any[]) => (string | EntityId)[],+ ) {+ return withRequestState((...args: any[]) => [+ "entities",+ entity.name,+ ...getSubStatePath(...args).map(String),+ ]);+ }++ function withEntityActionDecorators(+ action: string,+ ): (fn: EntityActionCreator) => EntityActionCreator {+ return entity.actionDecorators[action] || ((fn: EntityActionCreator) => fn);+ }++ // `objectActions` are for actions that accept an entity as their first argument,+ // and they are bound to instances when `wrapped: true` is passed to `EntityListLoader`+ // compose(decorator, decorator)(fn) loses types through multiple levels; makeAction recovers them+ entity.objectActions = {+ fetch: compose<EntityActionCreator>(+ withAction(FETCH_ACTION),+ withCachedDataAndRequestState(+ ({ id }: { id: EntityId }) => [...getObjectStatePath(id).map(String)],+ ({ id }: { id: EntityId }) => [+ ...getObjectStatePath(id).map(String),+ "fetch",+ ],+ (entityQuery: EntityQuery) => getQueryKey(entityQuery),+ ),+ withEntityActionDecorators("fetch"),+ )(+ (entityQuery: EntityQuery, options: Record<string, unknown> = {}) =>+ async (dispatch: AnyDispatch, getState: AnyGetState) =>+ entity.normalize(+ await entity.api.get?.(entityQuery, options, dispatch, getState),+ ),+ ),++ create: compose<EntityActionCreator>(+ withAction(CREATE_ACTION),+ withEntityRequestState(() => ["create"]),+ withEntityActionDecorators("create"),+ )(+ (entityObject: EntityObject) =>+ async (dispatch: AnyDispatch, getState: AnyGetState) => {+ return entity.normalize(+ await entity.api.create?.(+ getWritableProperties(entityObject),+ dispatch,+ getState,+ ),+ );+ },+ ),++ update: compose<EntityActionCreator>(+ withAction(UPDATE_ACTION),+ withEntityRequestState((object: EntityObject) => [+ String(object.id),+ "update",+ ]),+ withEntityActionDecorators("update"),+ )(+ (+ entityObject: EntityObject,+ updatedObject: Partial<EntityObject> | null = null,+ {+ notify,+ }: {+ notify?: { undo?: boolean; subject?: string; verb?: string } | false;+ } = {},+ ) =>+ async (dispatch: AnyDispatch, getState: AnyGetState) => {+ // save the original object for undo+ const originalObject = getObject(getState(), {+ entityId: entityObject.id,+ });+ // If a second object is provided just take the id from the first and+ // update it with all the properties in the second+ if (updatedObject) {+ entityObject = { id: entityObject.id, ...updatedObject };+ }++ const result = entity.normalize(+ await entity.api.update?.(+ getWritableProperties(entityObject),+ dispatch,+ getState,+ ),+ );++ if (notify) {+ if (notify.undo) {+ // pick only the attributes that were updated+ const undoObject = _.pick(+ originalObject,+ ...Object.keys(updatedObject || {}),+ );+ dispatch(+ addUndo({+ actions: [+ entity.objectActions.update(+ entityObject,+ undoObject,+ // don't show an undo for the undo+ { notify: false },+ ),+ ],+ ...notify,+ }),+ );+ } else {+ dispatch(addUndo(notify));+ }+ }+ return result;+ },+ ),++ delete: compose<EntityActionCreator>(+ withAction(DELETE_ACTION),+ withEntityRequestState((object: EntityObject) => [+ String(object.id),+ "delete",+ ]),+ withEntityActionDecorators("delete"),+ )(+ (entityObject: EntityObject) =>+ async (dispatch: AnyDispatch, getState: AnyGetState) => {+ await entity.api.delete?.(entityObject, dispatch, getState);+ return {+ entities: { [entity.name]: { [entityObject.id]: null } },+ result: entityObject.id,+ };+ },+ ),++ // user defined object actions should override defaults+ ...(def.objectActions || {}),+ };++ // ACTION CREATORS+ entity.actions = {+ fetchList: compose<EntityActionCreator>(+ withAction(FETCH_LIST_ACTION),+ withCachedDataAndRequestState(+ (entityQuery: EntityQuery) => [...getListStatePath(entityQuery)],+ (entityQuery: EntityQuery) => [+ ...getListStatePath(entityQuery),+ "fetch",+ ],+ (entityQuery: EntityQuery) => entity.getQueryKey(entityQuery),+ ),+ )(+ (entityQuery: EntityQuery = null) =>+ async (dispatch: AnyDispatch, getState: AnyGetState) => {+ const fetched = await entity.api.list?.(+ entityQuery || EMPTY_ENTITY_QUERY,+ dispatch,+ getState,+ );++ let results: EntityObject[] | undefined;+ let metadata: Record<string, unknown> = {};++ if (!fetched || _.isArray(fetched)) {+ results = fetched;+ } else {+ const { data, ...rest } = fetched;+ results = data;+ metadata = rest;+ }++ if (!Array.isArray(results)) {+ throw `Invalid response listing ${entity.name}`;+ }+ return {+ ...entity.normalizeList(results),+ metadata,+ entityQuery,+ };+ },+ ),++ invalidateLists: compose<EntityActionCreator>(+ withAction(INVALIDATE_LISTS_ACTION),+ withEntityActionDecorators("invalidateLists"),+ )(() => null),++ // user defined actions should override defaults+ ...entity.objectActions,+ ...(def.actions || {}),+ };++ entity.HACK_getObjectFromAction = (+ rawAction: EntityAction | undefined,+ ): EntityObject | EntityObject[] | NormalizedPayload | undefined => {+ const { payload } = rawAction ?? {};+ if (payload && "entities" in payload && "result" in payload) {+ if (Array.isArray(payload.result)) {+ return payload.result.map((id) => payload.entities![entity.name][id]);+ } else {+ return payload.entities![entity.name][payload.result!];+ }+ } else {+ return payload;+ }+ };++ // SELECTORS++ const getEntities = (state: State) => state.entities;+ const getSettings = (state: State) => state.settings;++ // OBJECT SELECTORS++ const getEntityId = (+ state: State,+ props: { params?: { entityId?: EntityId }; entityId?: EntityId },+ ): EntityId | undefined =>+ (props.params && props.params.entityId) || props.entityId;++ const getObject = createCachedSelector(+ [getEntities, getEntityId],+ (entities: EntitiesState, entityId: EntityId | undefined) =>+ denormalize(entityId, entity.schema, entities),+ )((state: State, { entityId }: { entityId?: EntityId } = {}) =>+ typeof entityId === "object"+ ? JSON.stringify(entityId)+ : entityId+ ? String(entityId)+ : "",+ );++ // LIST SELECTORS++ const getEntityQueryId = (+ state: any,+ props: { entityQuery?: EntityQuery } | null | undefined,+ ): string => getQueryKey(props?.entityQuery);++ const getEntityLists = createSelector([getEntities], (entities) => {+ return entities[`${entity.name}_list`] as+ | Record<string, { list?: EntityId[]; metadata?: unknown }>+ | undefined;+ });++ const getEntityList = createSelector(+ [getEntityQueryId, getEntityLists],+ (+ entityQueryId: string,+ lists:+ | Record<string, { list?: EntityId[]; metadata?: unknown }>+ | undefined,+ ) => lists?.[entityQueryId],+ );++ const getEntityIds = createSelector(+ [getEntityList],+ (entityList: { list?: EntityId[]; metadata?: unknown } | undefined) =>+ entityList?.list,+ );++ const getListMetadata = createSelector(+ [getEntityList],+ (entityList: { list?: EntityId[]; metadata?: unknown } | undefined) =>+ entityList?.metadata,+ );++ const getList = createCachedSelector(+ [getEntities, getEntityIds, getSettings],+ (+ entities: EntitiesState,+ entityIds: EntityId[] | undefined,+ settings: unknown,+ ) =>+ entityIds &&+ entityIds+ .map((entityId) =>+ entity.selectors.getObject({ entities, settings }, { entityId }),+ )+ .filter((e): e is EntityObject => e != null),+ )((state: any, props: { entityQuery?: EntityQuery } | null | undefined) =>+ props?.entityQuery ? JSON.stringify(props.entityQuery) : "",+ );++ // REQUEST STATE SELECTORS++ type RequestStateEntry = {+ loading?: boolean;+ loaded?: boolean;+ fetched?: boolean;+ error?: unknown;+ queryKey?: string;+ queryPromise?: Promise<unknown>;+ };++ const getStatePath = ({+ entityId,+ entityQuery,+ }: { entityId?: EntityId; entityQuery?: EntityQuery } = {}): (+ | string+ | EntityId+ )[] =>+ entityId != null+ ? getObjectStatePath(entityId)+ : getListStatePath(entityQuery);++ const getRequestStatePath = ({+ entityId,+ entityQuery,+ requestType = "fetch",+ }: {+ entityId?: EntityId;+ entityQuery?: EntityQuery;+ requestType?: string;+ } = {}): string[] => [+ "requests",+ ...getStatePath({ entityId, entityQuery }).map(String),+ requestType,+ ];++ const defaultRequestState: RequestStateEntry = {};+ const getRequestState = (+ state: EntitiesState,+ props?: {+ entityId?: EntityId;+ entityQuery?: EntityQuery;+ requestType?: string;+ },+ ): RequestStateEntry =>+ getIn(state, getRequestStatePath(props)) || defaultRequestState;++ const getLoading = createSelector(+ [getRequestState],+ (requestState: RequestStateEntry) => requestState.loading,+ );+ const getLoaded = createSelector(+ [getRequestState],+ (requestState: RequestStateEntry) => requestState.loaded,+ );+ const getFetched = createSelector(+ [getRequestState],+ (requestState: RequestStateEntry) => requestState.fetched,+ );+ const getError = createSelector(+ [getRequestState],+ (requestState: RequestStateEntry) => requestState.error,+ );++ // createSelector/createCachedSelector attach cache methods; cast to the clean selector types+ const defaultSelectors: Partial<EntitySelectors> = {+ getEntityIds,+ getList,+ getObject,+ getFetched,+ getLoading,+ getLoaded,+ getError,+ getListMetadata,+ };+ entity.selectors = {+ ...defaultSelectors,+ ...(def.selectors || {}),+ ...(def.createSelectors ? def.createSelectors(defaultSelectors) : {}),+ } as EntitySelectors;++ entity.objectSelectors = {+ getName(object: EntityObject) {+ return object.name;+ },+ getIcon(_object: EntityObject) {+ return { name: "unknown" };+ },+ getColor(_object: EntityObject): string | undefined {+ return undefined;+ },+ getCollection(object: EntityObject) {+ return object.collection;+ },+ ...(def.objectSelectors || {}),+ };++ // REDUCERS++ entity.reducers = {};++ entity.reducers[entity.name] = handleEntities(+ /^metabase\/entities\//,+ entity.name,+ def.reducer,+ );++ const listReducer: Reducer<Record<string, unknown>> = (+ state: Record<string, unknown> = {},+ action: {+ type: string;+ error?: boolean;+ payload?: Record<string, unknown>;+ },+ ) => {+ if (action.error) {+ return state;+ }+ if (action.type === FETCH_LIST_ACTION) {+ if (action.payload && action.payload.result) {+ const { entityQuery, metadata, result: list } = action.payload;+ return {+ ...state,+ [getQueryKey(entityQuery)]: {+ list,+ metadata,+ },+ };+ }+ // NOTE: only add/remove from the "default" list (no entityQuery)+ // TODO: just remove this entirely?+ } else if (action.type === CREATE_ACTION && state[""]) {+ return {+ ...state,+ "": (state[""] as EntityId[]).concat([+ action.payload!.result as EntityId,+ ]),+ };+ } else if (action.type === DELETE_ACTION && state[""]) {+ return {+ ...state,+ "": (state[""] as EntityId[]).filter(+ (id) => id !== action.payload!.result,+ ),+ };+ }+ return state;+ };+ entity.reducers[`${entity.name}_list`] = listReducer;++ // REQUEST STATE REDUCER++ if (!entity.actionShouldInvalidateLists) {+ entity.actionShouldInvalidateLists = (action: { type: string }) =>+ action.type === CREATE_ACTION ||+ action.type === DELETE_ACTION ||+ action.type === UPDATE_ACTION ||+ action.type === INVALIDATE_LISTS_ACTION;+ }++ entity.requestsReducer = (+ state: RequestsStateTree = {},+ action: { type: string },+ ) => {+ if (entity.actionShouldInvalidateLists(action)) {+ return requestsReducer(+ state,+ setRequestUnloaded(["entities", entity.name + "_list"]),+ );+ }+ return state ?? {};+ };++ // OBJECT WRAPPER++ if (!entity.wrapEntity) {+ class EntityWrapper {+ [key: string]: unknown;+ _dispatch: AnyDispatch | null;++ constructor(+ object: { id: EntityId },+ dispatch: AnyDispatch | null = null,+ ) {+ Object.assign(this, object);+ this._dispatch = dispatch;+ }+ }+ // object selectors+ for (const [methodName, method] of Object.entries(entity.objectSelectors)) {+ if (method) {+ EntityWrapper.prototype[methodName] = function (+ this: EntityWrapper,+ ...args: unknown[]+ ) {+ return method(this, ...args);+ };+ }+ }+ // object actions+ for (const [methodName, method] of Object.entries(entity.objectActions)) {+ if (method) {+ EntityWrapper.prototype[methodName] = function (+ this: EntityWrapper,+ ...args: unknown[]+ ) {+ if (this._dispatch) {+ return this._dispatch(method(this, ...args));+ } else {+ return method(this, ...args);+ }+ };+ }+ }++ entity.wrapEntity = (+ object: any,+ dispatch: AnyDispatch | null = null,+ ): any => new EntityWrapper(object, dispatch);+ }++ // add container components and HOCs+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic require to avoid circular dependency+ require("metabase/entities/containers").addEntityContainers(entity);++ return entity;+}++type CombinedEntities = {+ entities: Record<string, Entity>;+ reducers: Record<string, Reducer<Record<string, unknown>>>;+ reducer: Reducer<Record<string, Record<string, unknown>>>;+ requestsReducer: (+ state: RequestsStateTree | undefined,+ action: { type: string },+ ) => RequestsStateTree;+};++export function combineEntities(entities: Entity[]): CombinedEntities {+ const entitiesMap: Record<string, Entity> = {};+ const reducersMap: Record<string, Reducer<Record<string, unknown>>> = {};++ for (const entity of entities) {+ if (entity.name in entitiesMap) {+ console.warn(`Entity with name ${entity.name} already exists!`);+ } else {+ entitiesMap[entity.name] = entity;+ Object.assign(reducersMap, entity.reducers);+ }+ }++ const combinedRequestsReducer = (+ state: RequestsStateTree = {},+ action: { type: string },+ ): RequestsStateTree => {+ let current = state;+ for (const entity of entities) {+ if (entity.requestsReducer) {+ current = entity.requestsReducer(current, action);+ }+ }+ return current;+ };++ return {+ entities: entitiesMap,+ reducers: reducersMap,+ reducer: combineReducers(reducersMap),+ requestsReducer: combinedRequestsReducer,+ };+}++// OBJECT ACTION DECORATORS++export const notify = (+ opts: Record<string, unknown> = {},+ subject: string,+ verb: string,+) => merge({ notify: { subject, verb, undo: false } }, opts || {});++export const undo = (+ opts: Record<string, unknown> = {},+ subject: string,+ verb: string,+) => merge({ notify: { subject, verb, undo: true } }, opts || {});++/**+ * Structural minimum of an RTK Query endpoint descriptor. Concrete endpoints from+ * RTK Query carry many extra properties (hooks, selectors, etc.) and concrete+ * argument/result types — we only rely on `initiate` here.+ */++type RTKEndpoint = { initiate: (request: any, options: any) => any };++export async function entityCompatibleQuery(+ entityQuery: EntityQuery,+ dispatch: AnyDispatch,+ endpoint: RTKEndpoint,++ { forceRefetch = true } = {},+): Promise<any> {+ const request = entityQuery === EMPTY_ENTITY_QUERY ? undefined : entityQuery;+ const action = dispatch(endpoint.initiate(request, { forceRefetch }));++ try {+ return await action.unwrap();+ } finally {+ action.unsubscribe?.();+ }+}diff --git a/frontend/src/metabase/utils/entities.unit.spec.js b/frontend/src/metabase/utils/entities.unit.spec.tssimilarity index 68%rename from frontend/src/metabase/utils/entities.unit.spec.jsrename to frontend/src/metabase/utils/entities.unit.spec.tsindex 67c1398b3db..dcbfd44de67 100644--- a/frontend/src/metabase/utils/entities.unit.spec.js+++ b/frontend/src/metabase/utils/entities.unit.spec.ts@@ -1,9 +1,13 @@import { combineReducers, configureStore } from "@reduxjs/toolkit";-import requestsReducer from "metabase/redux/requests";-import { combineEntities, createEntity } from "metabase/utils/entities";+import {+ type RequestsStateTree,+ requestsReducer,+} from "metabase/redux/requests";-function getObject(id) {+import { combineEntities, createEntity, mergeEntities } from "./entities";++function getObject(id: number) {return { id: id, name: `object${id}` };}@@ -11,7 +15,9 @@ function setup() {const widgets = createEntity({name: "widgets",api: {- get: jest.fn().mockImplementation(({ id }) => getObject(id)),+ get: jest+ .fn()+ .mockImplementation(({ id }: { id: number }) => getObject(id)),list: jest.fn().mockImplementation(() => [getObject(1), getObject(2)]),},});@@ -20,8 +26,10 @@ function setup() {const reducer = combineReducers({entities: entities.reducer,- requests: (state, action) =>- requestsReducer(entities.requestsReducer(state, action), action),+ requests: (+ state: RequestsStateTree | undefined,+ action: { type: string; payload: Record<string, unknown> | undefined },+ ) => requestsReducer(entities.requestsReducer(state, action), action),});const initialState = {@@ -35,7 +43,7 @@ function setup() {const store = configureStore({reducer,- initialState,+ preloadedState: initialState,middleware: (getDefaultMiddleware) =>getDefaultMiddleware({immutableCheck: false,@@ -110,4 +118,36 @@ describe("entities", () => {expect(widgets.api.list).toHaveBeenCalledTimes(2);});});++ describe("mergeEntities", () => {+ it("add an entity", () => {+ expect(+ mergeEntities<Record<string, { id: number; name: string }>>(+ { actions: { id: 1, name: "foo" } },+ { questions: { id: 2, name: "bar" } },+ ),+ ).toEqual({+ actions: { id: 1, name: "foo" },+ questions: { id: 2, name: "bar" },+ });+ });++ it("merge entity keys", () => {+ expect(+ mergeEntities<Record<string, Record<string, string | number>>>(+ { actions: { id: 1, name: "foo", prop1: 123 } },+ { actions: { id: 1, name: "bar", prop2: 456 } },+ ),+ ).toEqual({ actions: { id: 1, name: "bar", prop1: 123, prop2: 456 } });+ });++ it("delete an entity", () => {+ expect(+ mergeEntities(+ { databases: { id: 1 }, questions: { id: 2 } },+ { questions: undefined },+ ),+ ).toEqual({ databases: { id: 1 } });+ });+ });});diff --git a/frontend/src/metabase/utils/i18n.js b/frontend/src/metabase/utils/i18n.tssimilarity index 76%rename from frontend/src/metabase/utils/i18n.jsrename to frontend/src/metabase/utils/i18n.tsindex dcbd29718f6..ff30f81e571 100644--- a/frontend/src/metabase/utils/i18n.js+++ b/frontend/src/metabase/utils/i18n.ts@@ -1,17 +1,23 @@import dayjs from "dayjs";+import type { LocaleData } from "ttag";import { addLocale, useLocale } from "ttag";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import api from "metabase/utils/api";import { DAY_OF_WEEK_OPTIONS } from "metabase/utils/date-time";import MetabaseSettings from "metabase/utils/settings";+import type { DayOfWeekId } from "metabase-types/api";++type LocaleDataWithLanguage = LocaleData & { headers: { language: string } };// note this won't refresh strings that are evaluated at load time-export async function loadLocalization(locale) {+export async function loadLocalization(+ locale: string,+): Promise<LocaleDataWithLanguage> {// we need to be sure to set the initial localization before loading any files// so load metabase/services only when we need it// load and parse the locale- const translationsObject =+ const translationsObject: LocaleDataWithLanguage =locale !== "en"? // We don't use I18NApi.locale/the GET helper because those helpers adds custom headers,// which will make the browser do the pre-flight request on the SDK.@@ -20,7 +26,7 @@ export async function loadLocalization(locale) {await fetch(`${api.basename}/app/locales/${locale}.json`).then((response) => response.json(),)- : // We don't serve en.json. Instead, use this object to fall back to theliterals.+ : // We don't serve en.json. Instead, use this object to fall back to the literals.{headers: {language: "en",@@ -38,7 +44,9 @@ export async function loadLocalization(locale) {// Tell dayjs to use the value of the start-of-week Setting for its current locale// range Sunday (0) - Saturday (6)-export function updateStartOfWeek(startOfWeekDayName) {+export function updateStartOfWeek(+ startOfWeekDayName: DayOfWeekId | null | undefined,+): void {const startOfWeekDay = getStartOfWeekDay(startOfWeekDayName);if (startOfWeekDay != null) {dayjs.updateLocale(dayjs.locale(), { weekStart: startOfWeekDay });@@ -48,7 +56,7 @@ export function updateStartOfWeek(startOfWeekDayName) {// if the start of week Setting is updated, update the dayjs start of weekMetabaseSettings.on("start-of-week", updateStartOfWeek);-function setLanguage(translationsObject) {+function setLanguage(translationsObject: LocaleDataWithLanguage): void {const locale = translationsObject.headers.language;addMsgIds(translationsObject);@@ -60,11 +68,13 @@ function setLanguage(translationsObject) {const ARABIC_LOCALES = ["ar", "ar-sa"];-export function setLocalization(translationsObject) {+export function setLocalization(+ translationsObject: LocaleDataWithLanguage,+): void {const language = translationsObject.headers.language;setLanguage(translationsObject);updateDayjsLocale(language);- updateStartOfWeek(MetabaseSettings.get("start-of-week"));+ updateStartOfWeek(MetabaseSettings.get("start-of-week") as DayOfWeekId);if (ARABIC_LOCALES.includes(language)) {preserveLatinNumbersInDayjsLocale(language);@@ -75,25 +85,26 @@ export function setLocalization(translationsObject) {* Ensures that we consistently use latin numbers in Arabic locales.* See https://github.com/metabase/metabase/issues/34271*/-function preserveLatinNumbersInDayjsLocale(locale) {+function preserveLatinNumbersInDayjsLocale(locale: string): void {dayjs.updateLocale(locale, {// Preserve latin numbers, but still replace commas.// See https://github.com/moment/moment/blob/000ac1800e620f770f4eb31b5ae908f6167b0ab2/locale/ar.js#L185- postformat(string) {+ postformat(string: string) {return string.replace(/,/g, "،");},- meridiem: (hour) => {+ meridiem: (hour: number) => {// https://github.com/iamkun/dayjs/pull/2717#issuecomment-2868626450return hour < 12 ? "ص" : "م";},});}-function updateDayjsLocale(language) {+function updateDayjsLocale(language: string): void {const locale = getLocale(language);try {if (locale !== "en") {+ // eslint-disable-next-line @typescript-eslint/no-require-imports -- dynamic locale loadingrequire(`dayjs/locale/${locale}.js`);}dayjs.locale(locale);@@ -103,7 +114,7 @@ function updateDayjsLocale(language) {}}-function getLocale(language = "") {+function getLocale(language = ""): string {switch (language) {case "zh":case "zh-Hans":@@ -113,16 +124,18 @@ function getLocale(language = "") {}}-function getStartOfWeekDay(startOfWeekDayName) {+function getStartOfWeekDay(+ startOfWeekDayName: DayOfWeekId | null | undefined,+): number | undefined {if (!startOfWeekDayName) {- return;+ return undefined;}const startOfWeekDayNumber = DAY_OF_WEEK_OPTIONS.findIndex(({ id }) => id === startOfWeekDayName,);if (startOfWeekDayNumber === -1) {- return;+ return undefined;}return startOfWeekDayNumber;@@ -130,8 +143,11 @@ function getStartOfWeekDay(startOfWeekDayName) {// we delete msgid property since it's redundant, but have to add it back in to// make ttag happy-function addMsgIds(translationsObject) {- const msgs = translationsObject.translations[""];+function addMsgIds(translationsObject: LocaleDataWithLanguage): void {+ const msgs = translationsObject.translations[""] as Record<+ string,+ { msgid?: string; msgstr: string[] }+ >;for (const msgid in msgs) {if (msgs[msgid].msgid === undefined) {msgs[msgid].msgid = msgid;@@ -142,7 +158,7 @@ function addMsgIds(translationsObject) {// Runs `f` with the current language for ttag set to the instance (site) locale rather than the user locale, then// restores the user locale. This can be used for translating specific strings into the instance language; e.g. for// parameter values in dashboard text cards that should be translated the same for all users viewing the dashboard.-export function withInstanceLanguage(f) {+export function withInstanceLanguage<T>(f: () => T): T {if (window.MetabaseSiteLocalization) {setLanguage(window.MetabaseSiteLocalization);}@@ -155,10 +171,11 @@ export function withInstanceLanguage(f) {}}-export function siteLocale() {+export function siteLocale(): string | undefined {if (window.MetabaseSiteLocalization) {return window.MetabaseSiteLocalization.headers.language;}+ return undefined;}// register site locale with ttag, if needed later@@ -180,9 +197,11 @@ if (window.MetabaseUserLocalization) {* since they don't have a user locale. So this function is for them to set the locale from a URL hash as the user locale,* then the translation on some part of FE still works even after `withInstanceLanguage` is called.*- * @param {object} translationsObject A translated object with the same structure as the one produced in `loadLocalization` function.+ * @param translationsObject A translated object with the same structure as the one produced in `loadLocalization` function.*/-export function setUserLocale(translationsObject) {+export function setUserLocale(+ translationsObject: LocaleDataWithLanguage,+): void {if (!isEmbeddingSdk()) {window.MetabaseUserLocalization = translationsObject;}diff --git a/frontend/src/metabase/utils/redux/utils.js b/frontend/src/metabase/utils/redux/utils.tssimilarity index 63%rename from frontend/src/metabase/utils/redux/utils.jsrename to frontend/src/metabase/utils/redux/utils.tsindex c41b33a075b..3e9e392b4e0 100644--- a/frontend/src/metabase/utils/redux/utils.js+++ b/frontend/src/metabase/utils/redux/utils.ts@@ -1,6 +1,6 @@import { compose } from "@reduxjs/toolkit";import { getIn } from "icepick";-import { normalize } from "normalizr";+import { type Schema, normalize } from "normalizr";import _ from "underscore";import {@@ -10,6 +10,7 @@ import {setRequestPromise,setRequestUnloaded,} from "metabase/redux/requests";+import type { Dispatch, State } from "metabase/redux/store";import { delay } from "metabase/utils/promise";// convenience@@ -17,12 +18,25 @@ export { combineReducers, compose } from "@reduxjs/toolkit";export { handleActions, createAction } from "redux-actions";// turns into id indexed map-export const resourceListToMap = (resources) =>+export const resourceListToMap = <T extends { id: string | number }>(+ resources: T[],+): Record<string | number, T> =>resources.reduce((map, resource) => ({ ...map, [resource.id]: resource }),- {},+ {} as Record<string | number, T>,);+export type FetchDataArgs = {+ dispatch: Dispatch;+ getState: () => State;+ requestStatePath: string[];+ existingStatePath: string[];+ queryKey?: string;+ getData: () => Promise<unknown>;+ reload?: boolean;+ properties?: string[] | null;+};+// DEPRECATEDexport const fetchData = async ({dispatch,@@ -33,15 +47,15 @@ export const fetchData = async ({getData,reload = false,properties = null,-}) => {+}: FetchDataArgs): Promise<unknown> => {const existingData = getIn(getState(), existingStatePath);- // short circuit if we have loaded data, and we're givein a list of required properties, and they all existing in the loaded data+ // short circuit if we have loaded data, and we're given a list of required properties, and they all exist in the loaded dataif (!reload &&existingData &&properties &&- _.all(properties, (p) => existingData[p] !== undefined)+ _.all(properties, (p: string) => existingData[p] !== undefined)) {return existingData;}@@ -49,7 +63,7 @@ export const fetchData = async ({const statePath = requestStatePath.concat(["fetch"]);try {const requestState = getIn(getState(), ["requests", ...statePath]);- if (!requestState || requestState.error || reload) {+ if (!requestState || requestState?.error || reload) {dispatch(setRequestLoading(statePath, queryKey));const queryPromise = getData();@@ -73,6 +87,16 @@ export const fetchData = async ({}};+type UpdateDataArgs = {+ dispatch: Dispatch;+ getState: () => State;+ requestStatePath: string[];+ existingStatePath?: string[];+ queryKey?: string;+ dependentRequestStatePaths?: string[][];+ putData: () => Promise<unknown>;+};+// DEPRECATEDexport const updateData = async ({dispatch,@@ -80,10 +104,9 @@ export const updateData = async ({requestStatePath,existingStatePath,queryKey,- // specify any request paths that need to be invalidated after this updatedependentRequestStatePaths,putData,-}) => {+}: UpdateDataArgs): Promise<unknown> => {const existingData = existingStatePath? getIn(getState(), existingStatePath): null;@@ -97,8 +120,8 @@ export const updateData = async ({const data = await queryPromise;dispatch(setRequestLoaded(statePath, queryKey));- (dependentRequestStatePaths || []).forEach((statePath) =>- dispatch(setRequestUnloaded(statePath)),+ (dependentRequestStatePaths || []).forEach((path) =>+ dispatch(setRequestUnloaded(path)),);return data;@@ -109,54 +132,33 @@ export const updateData = async ({}};-// helper for working with normalizr-// merge each entity from newEntities with existing entity, if any-// this ensures partial entities don't overwrite existing entities with more properties-export function mergeEntities(entities, newEntities) {- entities = { ...entities };- for (const id in newEntities) {- if (newEntities[id] === null) {- delete entities[id];- } else {- entities[id] = { ...entities[id], ...newEntities[id] };- }- }- return entities;-}+// THUNK DECORATORS-// helper for working with normalizr-// reducer that merges payload.entities-export function handleEntities(- actionPattern,- entityType,- reducer = (state = {}, action) => state,-) {- return (state, action) => {- if (state === undefined) {- state = {};- }- const entities = getIn(action, ["payload", "entities", entityType]);- if (actionPattern.test(action.type) && entities) {- state = mergeEntities(state, entities);- }- return reducer(state, action);- };-}+type Thunk<R = unknown> = (+ dispatch: Dispatch,+ getState: () => State,+) => Promise<R> | R;-// THUNK DECORATORS+type ThunkCreator<TArgs extends unknown[], R = unknown> = (+ ...args: TArgs+) => Thunk<R>;++type PayloadOrThunkCreator<TArgs extends unknown[], R = unknown> = (+ ...args: TArgs+) => R | Thunk<R>;/*** Decorator for turning a payload creator or thunk (including one returning a promise) into a flux standard action*/-export function withAction(actionType) {- return (payloadOrThunkCreator) => {- function newCreator(...args) {+export function withAction<TArgs extends unknown[]>(actionType: string) {+ return (payloadOrThunkCreator: PayloadOrThunkCreator<TArgs>) => {+ function newCreator(...args: TArgs): unknown {const payloadOrThunk = payloadOrThunkCreator(...args);if (typeof payloadOrThunk === "function") {// thunk, return a new thunk- return async (dispatch, getState) => {+ return async (dispatch: Dispatch, getState: () => State) => {try {- const payload = await payloadOrThunk(dispatch, getState);+ const payload = await (payloadOrThunk as Thunk)(dispatch, getState);const dispatchValue = { type: actionType, payload: payload };dispatch(dispatchValue);@@ -179,20 +181,29 @@ export function withAction(actionType) {/*** Decorator that tracks the state of a request action*/-export function withRequestState(getRequestStatePath, getQueryKey) {+export function withRequestState<TArgs extends unknown[]>(+ getRequestStatePath: (...args: TArgs) => string[],+ getQueryKey?: (...args: TArgs) => string | undefined,+) {// thunk decorator:- return (thunkCreator) =>+ return (thunkCreator: ThunkCreator<TArgs>) =>// thunk creator:- (...args) =>+ (...args: TArgs) =>// thunk:- async (dispatch, getState) => {+ async (dispatch: Dispatch, getState: () => State) => {const statePath = getRequestStatePath(...args);const queryKey = getQueryKey && getQueryKey(...args);try {dispatch(setRequestLoading(statePath, queryKey));const queryPromise = thunkCreator(...args)(dispatch, getState);- dispatch(setRequestPromise(statePath, queryKey, queryPromise));+ dispatch(+ setRequestPromise(+ statePath,+ queryKey,+ queryPromise as Promise<unknown>,+ ),+ );const result = await queryPromise;@@ -214,10 +225,10 @@ export function withRequestState(getRequestStatePath, getQueryKey) {* Decorator that returns cached data if appropriate, otherwise calls the composed thunk.* Also tracks request state using withRequestState*/-export function withCachedDataAndRequestState(- getExistingStatePath,- getRequestStatePath,- getQueryKey,+export function withCachedDataAndRequestState<TArgs extends unknown[]>(+ getExistingStatePath: (...args: TArgs) => string[],+ getRequestStatePath: (...args: TArgs) => string[],+ getQueryKey?: (...args: TArgs) => string | undefined,) {return compose(withCachedData(getExistingStatePath, getRequestStatePath, getQueryKey),@@ -225,19 +236,36 @@ export function withCachedDataAndRequestState();}+type CachedRequestState = {+ loading?: boolean;+ loaded?: boolean;+ queryKey?: string;+ error?: { status?: number };+ queryPromise?: Promise<unknown>;+};++type CachedOptions = {+ useCachedForbiddenError?: boolean;+ reload?: boolean | (() => void);+ properties?: string[];+};+// NOTE: this should be used together with withRequestState, probably via withCachedDataAndRequestState-function withCachedData(- getExistingStatePath,- getRequestStatePath,- getQueryKey,+function withCachedData<TArgs extends unknown[]>(+ getExistingStatePath: (...args: TArgs) => string[],+ getRequestStatePath: (...args: TArgs) => string[],+ getQueryKey?: (...args: TArgs) => string | undefined,) {// thunk decorator:- return (thunkCreator) =>+ return (thunkCreator: ThunkCreator<TArgs>) =>// thunk creator:- (...args) =>+ (...args: TArgs) =>// thunk:- async function thunk(dispatch, getState) {- const options = args[args.length - 1] || {};+ async function thunk(+ dispatch: Dispatch,+ getState: () => State,+ ): Promise<unknown> {+ const options = (args[args.length - 1] as CachedOptions) || {};const { useCachedForbiddenError, reload, properties } = options;const existingStatePath = getExistingStatePath(...args);@@ -245,7 +273,7 @@ function withCachedData(const newQueryKey = getQueryKey && getQueryKey(...args);const existingData = getIn(getState(), existingStatePath);const { loading, loaded, queryKey, error } =- getIn(getState(), requestStatePath) || {};+ (getIn(getState(), requestStatePath) as CachedRequestState) || {};// Avoid requesting data with permanently forbidden accessif (useCachedForbiddenError && error?.status === 403) {@@ -255,7 +283,7 @@ function withCachedData(const hasRequestedProperties =properties &&existingData &&- _.all(properties, (p) => existingData[p] !== undefined);+ _.all(properties, (p: string) => existingData[p] !== undefined);// return existing data ifif (@@ -269,10 +297,10 @@ function withCachedData(if (loaded || hasRequestedProperties) {return existingData;} else if (loading) {- const queryPromise = getIn(- getState(),- requestStatePath,- )?.queryPromise;+ const requestState = getIn(getState(), requestStatePath) as+ | CachedRequestState+ | undefined;+ const queryPromise = requestState?.queryPromise;if (queryPromise) {// wait for current loading request to be resolved@@ -293,9 +321,9 @@ function withCachedData(};}-export function withNormalize(schema) {- return (thunkCreator) =>- (...args) =>- async (dispatch, getState) =>+export function withNormalize<TArgs extends unknown[]>(schema: Schema) {+ return (thunkCreator: ThunkCreator<TArgs>) =>+ (...args: TArgs) =>+ async (dispatch: Dispatch, getState: () => State) =>normalize(await thunkCreator(...args)(dispatch, getState), schema);}diff --git a/frontend/src/metabase/utils/redux/utils.unit.spec.js b/frontend/src/metabase/utils/redux/utils.unit.spec.tssimilarity index 60%rename from frontend/src/metabase/utils/redux/utils.unit.spec.jsrename to frontend/src/metabase/utils/redux/utils.unit.spec.tsindex e9d8a36e5ab..50ccce4c560 100644--- a/frontend/src/metabase/utils/redux/utils.unit.spec.js+++ b/frontend/src/metabase/utils/redux/utils.unit.spec.ts@@ -1,47 +1,102 @@import { delay } from "__support__/utils";+import type { Dispatch, RequestState, State } from "metabase/redux/store";+import { createMockState } from "metabase/redux/store/mocks";+import { createMockRequestsState } from "metabase/redux/store/mocks/requests";-import { fetchData, mergeEntities, updateData } from "./utils";+import { fetchData, updateData } from "./utils";describe("Metadata", () => {- const getDefaultArgs = ({- existingData = "data",- newData = "new data",- requestState = null,- requestStateLoading = { loading: true },- requestStateLoaded = { loaded: true },- requestStateError = { error: new Error("error") },- statePath = ["test", "path"],- statePathFetch = statePath.concat("fetch"),- statePathUpdate = statePath.concat("update"),- requestStatePath = statePath,- existingStatePath = statePath,- getState = () => ({- requests: {- test: { path: { fetch: requestState, update: requestState } },- },- test: { path: existingData },- }),- dispatch = jest.fn(),- getData = () => Promise.resolve(newData),- putData = () => Promise.resolve(newData),- } = {}) => ({- dispatch,- getState,- requestStatePath,- existingStatePath,- getData,- putData,- // passthrough args constants- existingData,- newData,- requestState,- requestStateLoading,- requestStateLoaded,- requestStateError,- statePath,- statePathFetch,- statePathUpdate,- });+ const getDefaultArgs = (+ overrides: {+ existingData?: string;+ newData?: string;+ requestState?: RequestState;+ requestStateLoading?: RequestState;+ requestStateLoaded?: RequestState;+ requestStateError?: RequestState;+ statePath?: string[];+ statePathFetch?: string[];+ statePathUpdate?: string[];+ requestStatePath?: string[];+ existingStatePath?: string[];+ getState?: () => State;+ dispatch?: Dispatch;+ getData?: () => Promise<unknown>;+ putData?: () => Promise<unknown>;+ } = {},+ ) => {+ const existingData = overrides.existingData ?? "data";+ const newData = overrides.newData ?? "new data";+ const requestState = overrides.requestState;+ const requestStateLoading = overrides.requestStateLoading ?? {+ loading: true,+ loaded: false,+ fetched: false,+ error: null,+ _isRequestState: true as const,+ };+ const requestStateLoaded = overrides.requestStateLoaded ?? {+ loading: false,+ loaded: true,+ fetched: true,+ error: null,+ _isRequestState: true as const,+ };+ const requestStateError = overrides.requestStateError ?? {+ loading: false,+ loaded: false,+ fetched: false,+ error: new Error("error"),+ _isRequestState: true as const,+ };+ const statePath = overrides.statePath ?? ["test", "path"];+ const statePathFetch =+ overrides.statePathFetch ?? statePath.concat("fetch");+ const statePathUpdate =+ overrides.statePathUpdate ?? statePath.concat("update");+ const requestStatePath = overrides.requestStatePath ?? [+ "entities",+ ...statePath,+ ];+ const existingStatePath = overrides.existingStatePath ?? statePath;+ const getState =+ overrides.getState ??+ (() => ({+ ...createMockState(),+ requests: createMockRequestsState({+ entities: {+ test: {+ path: requestState+ ? { fetch: requestState, update: requestState }+ : {},+ },+ },+ }),+ test: { path: existingData },+ }));+ const dispatch = overrides.dispatch ?? jest.fn();+ const getData = overrides.getData ?? (() => Promise.resolve(newData));+ const putData = overrides.putData ?? (() => Promise.resolve(newData));++ return {+ dispatch,+ getState,+ requestStatePath,+ existingStatePath,+ getData,+ putData,+ // passthrough args constants+ existingData,+ newData,+ requestState,+ requestStateLoading,+ requestStateLoaded,+ requestStateError,+ statePath,+ statePathFetch,+ statePathUpdate,+ };+ };const args = getDefaultArgs({});@@ -175,30 +230,4 @@ describe("Metadata", () => {expect(data).toEqual(args.existingData);});});-- describe("mergeEntities", () => {- it("add an entity", () => {- expect(- mergeEntities(- { 1: { id: 1, name: "foo" } },- { 2: { id: 2, name: "bar" } },- ),- ).toEqual({ 1: { id: 1, name: "foo" }, 2: { id: 2, name: "bar" } });- });-- it("merge entity keys", () => {- expect(- mergeEntities(- { 1: { id: 1, name: "foo", prop1: 123 } },- { 1: { id: 1, name: "bar", prop2: 456 } },- ),- ).toEqual({ 1: { id: 1, name: "bar", prop1: 123, prop2: 456 } });- });-- it("delete an entity", () => {- expect(- mergeEntities({ 1: { id: 1 }, 2: { id: 2 } }, { 2: null }),- ).toEqual({ 1: { id: 1 } });- });- });});diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsxindex 0b381cae00a..bc57b752f4c 100644--- a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx+++ b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx@@ -182,8 +182,7 @@ export class LeafletTilePinMap extends LeafletMap<LeafletTilePinMapProps> {GET(tileUrl, {fetch: true,signal: controller.signal,- transformResponse: ({ response }: { response: Response }) => response,- // TODO: Remove casting after api.js is migrated to TS+ transformResponse: ({ response }) => response,})() as Promise<Response>).then((response) => response.blob())diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.tsindex 725c84c7fac..e23a9ebdb41 100644--- a/frontend/src/types/global.d.ts+++ b/frontend/src/types/global.d.ts@@ -17,6 +17,23 @@ interface Window {heightCalculationMethod?: string;onReady?: () => void;};++ MetabaseSiteLocalization?: {+ headers: {+ language: string;+ "plural-forms"?: string;+ "content-type"?: string;+ };+ translations: Record<string, unknown>;+ };+ MetabaseUserLocalization?: {+ headers: {+ language: string;+ "plural-forms"?: string;+ "content-type"?: string;+ };+ translations: Record<string, unknown>;+ };}// This allows importing static SVGs from TypeScript filesdiff --git a/frontend/test/__support__/entities-store.js b/frontend/test/__support__/entities-store.jsdeleted file mode 100644index 96417d21580..00000000000--- a/frontend/test/__support__/entities-store.js+++ /dev/null@@ -1,23 +0,0 @@-import { combineReducers, configureStore } from "@reduxjs/toolkit";--import * as entities from "metabase/redux/entities";-import requestsReducer from "metabase/redux/requests";--export function getStore(reducers = {}, initialState = {}, middleware = []) {- const reducer = combineReducers({- entities: entities.reducer,- requests: (state, action) =>- requestsReducer(entities.requestsReducer(state, action), action),- ...reducers,- });-- return configureStore({- reducer,- preloadedState: initialState,- middleware: (getDefaultMiddleware) =>- getDefaultMiddleware({- immutableCheck: false,- serializableCheck: false,- }).concat(middleware),- });-}diff --git a/frontend/test/__support__/entities-store.ts b/frontend/test/__support__/entities-store.tsnew file mode 100644index 00000000000..18fa867acd9--- /dev/null+++ b/frontend/test/__support__/entities-store.ts@@ -0,0 +1,42 @@+import type { Middleware, Reducer } from "@reduxjs/toolkit";+import { combineReducers, configureStore } from "@reduxjs/toolkit";+import type { Action } from "redux-actions";++import * as entities from "metabase/redux/entities";+import {+ type RequestsStateTree,+ requestsReducer,+} from "metabase/redux/requests";+import type { State } from "metabase/redux/store";++/**+ * Build a configured Redux store for tests.+ *+ * Typings in this file are consciously loose to support regular and thunk actions+ * of different kinds throughout the codebase, including bizarre assertions in unit tests.+ */+export function getStore(+ reducers: Record<string, Reducer<any, any, any>> = {},+ initialState: Partial<State> = {},+ middleware: Middleware[] = [],+) {+ const reducer = combineReducers({+ entities: entities.reducer,+ requests: (+ state: RequestsStateTree | undefined,+ action: Action<undefined>,+ ) => requestsReducer(entities.requestsReducer(state, action), action),+ ...reducers,+ }) as unknown as Reducer<State>;++ return configureStore({+ reducer,+ preloadedState: initialState as State,++ middleware: ((getDefaultMiddleware: any) =>+ getDefaultMiddleware({+ immutableCheck: false,+ serializableCheck: false,+ }).concat(middleware)) as never,+ });+}diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex 84ceced7445..da26556b57b 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -1,5 +1,5 @@import { Global } from "@emotion/react";-import type { Reducer, Store } from "@reduxjs/toolkit";+import type { Middleware, Reducer, Store } from "@reduxjs/toolkit";import type { MatcherFunction } from "@testing-library/dom";import type { ByRoleMatcher, RenderHookOptions } from "@testing-library/react";import {@@ -204,7 +204,7 @@ export function getTestStoreAndWrapper({const store = getStore(reducers,initialState,- storeMiddleware,+ storeMiddleware as Middleware[],) as unknown as Store<State>;const wrapper = (props: any) => {