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
Call overrideRequestsForGuestOrPublicEmbeds for static/public embeddings (#67358)
Timofey Kachalov462a62a09270
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsxindex fa942cec8af..0395579b74f 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/DownloadWidget/DownloadWidget.tsx@@ -1,3 +1,4 @@+import { useEmbeddingEntityContext } from "metabase/embedding/context";import { QuestionDownloadWidget } from "metabase/query_builder/components/QuestionDownloadWidget";import {type UseDownloadDataParams,@@ -20,7 +21,9 @@ const DownloadWidgetInner = ({...rest}: DownloadWidgetProps &Pick<UseDownloadDataParams, "question" | "result">) => {- const { withDownloads, token } = useSdkQuestionContext();+ const { withDownloads } = useSdkQuestionContext();+ const { token } = useEmbeddingEntityContext();+const [, handleDownload] = useDownloadData({question,result,diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsxindex a55784f9610..e9bf6800dae 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx@@ -22,7 +22,6 @@ export const SqlParametersList = () => {const {question,originalQuestion,- token,parameterValues,updateParameterValues,hiddenParameters,@@ -92,7 +91,6 @@ export const SqlParametersList = () => {}}cardId={question.id()}dashboardId={question.dashboardId() ?? undefined}- token={token}parameters={parameters}setParameterValue={setParameterValue}enableParameterRequiredBehaviordiff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex 96ad7e106db..d4bc918410a 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -11,6 +11,7 @@ import {getPlugins,} from "embedding-sdk-bundle/store/selectors";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";import type { MetabasePluginsConfig as InternalMetabasePluginsConfig } from "metabase/embedding-sdk/types/plugins";import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";@@ -235,7 +236,9 @@ export const SdkQuestionProvider = ({return (<SdkQuestionContext.Provider value={questionContext}>- {children}+ <EmbeddingEntityContextProvider uuid={null} token={token}>+ {children}+ </EmbeddingEntityContextProvider></SdkQuestionContext.Provider>);};diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex 1098ec43383..99e0540fc48 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -50,6 +50,7 @@ import {useDashboardContext,} from "metabase/dashboard/context";import { getDashboardComplete, getIsDirty } from "metabase/dashboard/selectors";+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";import { isStaticEmbeddingEntityLoadingError } from "metabase/lib/errors/is-static-embedding-entity-loading-error";import { useSelector } from "metabase/lib/redux";@@ -330,116 +331,120 @@ const SdkDashboardInner = ({}return (- <DashboardContextProvider- ref={dashboardContextProviderRef}- dashboardId={dashboardId}- token={token}- isGuestEmbed={isGuestEmbed}- parameterQueryParams={initialParameters}- navigateToNewCardFromDashboard={- navigateToNewCardFromDashboard !== undefined- ? navigateToNewCardFromDashboard- : onNavigateToNewCardFromDashboard- }- onNewQuestion={() => {- if (isDashboardDirty) {- show({- title: t`Save your changes?`,- message: t`You’ll need to save your changes before leaving to create a new question.`,- confirmButtonText: t`Save changes`,- onConfirm: async () => {- /**- * Dispatch the same actions as in the DashboardLeaveConfirmationModal.- * @see {@link https://github.com/metabase/metabase/blob/4453fa8363eb37062a159f398050d050d91397a9/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx#L30-L34}- */- setRenderMode("queryBuilder");- dispatch(dismissAllUndo());- await dispatch(updateDashboardAndCards());- // After saving the dashboard, it will exit the editing mode.- dispatch(setEditingDashboard(dashboard));- },- confirmButtonProps: {- color: "brand",- },- });- } else {- setRenderMode("queryBuilder");+ <EmbeddingEntityContextProvider uuid={null} token={token}>+ <DashboardContextProvider+ ref={dashboardContextProviderRef}+ dashboardId={dashboardId}+ isGuestEmbed={isGuestEmbed}+ parameterQueryParams={initialParameters}+ navigateToNewCardFromDashboard={+ navigateToNewCardFromDashboard !== undefined+ ? navigateToNewCardFromDashboard+ : onNavigateToNewCardFromDashboard}- }}- downloadsEnabled={displayOptions.downloadsEnabled}- withSubscriptions={displayOptions.withSubscriptions}- background={displayOptions.background}- bordered={displayOptions.bordered}- hideParameters={displayOptions.hideParameters}- titled={displayOptions.titled}- cardTitled={displayOptions.cardTitled}- theme={displayOptions.theme}- onLoad={handleLoad}- onLoadWithoutCards={handleLoadWithoutCards}- onError={(error) => dispatch(setErrorPage(error))}- getClickActionMode={getClickActionMode}- dashcardMenu={finalDashcardMenu}- dashboardActions={dashboardActions}- onAddQuestion={(dashboard) => {- dispatch(setEditingDashboard(dashboard));- dispatch(toggleSidebar(SIDEBAR_NAME.addQuestion));- }}- autoScrollToDashcardId={autoScrollToDashcardId}- >- {match({ finalRenderMode, isGuestEmbed })- .with({ finalRenderMode: "question" }, () => (- <SdkDashboardStyledWrapperWithRef className={className} style={style}>- <SdkAdHocQuestion- // `adhocQuestionUrl` would have value if renderMode is "question"- questionPath={adhocQuestionUrl!}- onNavigateBack={onNavigateBackToDashboard}- {...drillThroughQuestionProps}- onVisualizationChange={onVisualizationChange}+ onNewQuestion={() => {+ if (isDashboardDirty) {+ show({+ title: t`Save your changes?`,+ message: t`You’ll need to save your changes before leaving to create a new question.`,+ confirmButtonText: t`Save changes`,+ onConfirm: async () => {+ /**+ * Dispatch the same actions as in the DashboardLeaveConfirmationModal.+ * @see {@link https://github.com/metabase/metabase/blob/4453fa8363eb37062a159f398050d050d91397a9/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx#L30-L34}+ */+ setRenderMode("queryBuilder");+ dispatch(dismissAllUndo());+ await dispatch(updateDashboardAndCards());+ // After saving the dashboard, it will exit the editing mode.+ dispatch(setEditingDashboard(dashboard));+ },+ confirmButtonProps: {+ color: "brand",+ },+ });+ } else {+ setRenderMode("queryBuilder");+ }+ }}+ downloadsEnabled={displayOptions.downloadsEnabled}+ withSubscriptions={displayOptions.withSubscriptions}+ background={displayOptions.background}+ bordered={displayOptions.bordered}+ hideParameters={displayOptions.hideParameters}+ titled={displayOptions.titled}+ cardTitled={displayOptions.cardTitled}+ theme={displayOptions.theme}+ onLoad={handleLoad}+ onLoadWithoutCards={handleLoadWithoutCards}+ onError={(error) => dispatch(setErrorPage(error))}+ getClickActionMode={getClickActionMode}+ dashcardMenu={finalDashcardMenu}+ dashboardActions={dashboardActions}+ onAddQuestion={(dashboard) => {+ dispatch(setEditingDashboard(dashboard));+ dispatch(toggleSidebar(SIDEBAR_NAME.addQuestion));+ }}+ autoScrollToDashcardId={autoScrollToDashcardId}+ >+ {match({ finalRenderMode, isGuestEmbed })+ .with({ finalRenderMode: "question" }, () => (+ <SdkDashboardStyledWrapperWithRef+ className={className}+ style={style}>- {AdHocQuestionView && <AdHocQuestionView />}- </SdkAdHocQuestion>- </SdkDashboardStyledWrapperWithRef>- ))- .with({ finalRenderMode: "dashboard" }, () => (- <SdkDashboardProvider- plugins={plugins}- onEditQuestion={onEditQuestion}- >- {children ?? (- <SdkDashboardStyledWrapperWithRef- className={className}- style={style}+ <SdkAdHocQuestion+ // `adhocQuestionUrl` would have value if renderMode is "question"+ questionPath={adhocQuestionUrl!}+ onNavigateBack={onNavigateBackToDashboard}+ {...drillThroughQuestionProps}+ onVisualizationChange={onVisualizationChange}>- <Dashboard className={EmbedFrameS.EmbedFrame} />- </SdkDashboardStyledWrapperWithRef>- )}- </SdkDashboardProvider>- ))- .with({ finalRenderMode: "queryBuilder" }, ({ isGuestEmbed }) =>- isGuestEmbed ? (- <SdkDashboardStyledWrapper className={className} style={style}>- <SdkError- message={t`You can't save questions in Guest Embed mode`}+ {AdHocQuestionView && <AdHocQuestionView />}+ </SdkAdHocQuestion>+ </SdkDashboardStyledWrapperWithRef>+ ))+ .with({ finalRenderMode: "dashboard" }, () => (+ <SdkDashboardProvider+ plugins={plugins}+ onEditQuestion={onEditQuestion}+ >+ {children ?? (+ <SdkDashboardStyledWrapperWithRef+ className={className}+ style={style}+ >+ <Dashboard className={EmbedFrameS.EmbedFrame} />+ </SdkDashboardStyledWrapperWithRef>+ )}+ </SdkDashboardProvider>+ ))+ .with({ finalRenderMode: "queryBuilder" }, ({ isGuestEmbed }) =>+ isGuestEmbed ? (+ <SdkDashboardStyledWrapper className={className} style={style}>+ <SdkError+ message={t`You can't save questions in Guest Embed mode`}+ />+ </SdkDashboardStyledWrapper>+ ) : (+ <DashboardQueryBuilder+ onCreate={(question) => {+ setNewDashboardQuestionId(question.id);+ setRenderMode("dashboard");+ dashboardContextProviderRef.current?.refetchDashboard();+ }}+ onNavigateBack={() => {+ setRenderMode("dashboard");+ }}+ dataPickerProps={dataPickerProps}+ onVisualizationChange={onVisualizationChange}/>- </SdkDashboardStyledWrapper>- ) : (- <DashboardQueryBuilder- onCreate={(question) => {- setNewDashboardQuestionId(question.id);- setRenderMode("dashboard");- dashboardContextProviderRef.current?.refetchDashboard();- }}- onNavigateBack={() => {- setRenderMode("dashboard");- }}- dataPickerProps={dataPickerProps}- onVisualizationChange={onVisualizationChange}- />- ),- )- .exhaustive()}- {modalContent}- </DashboardContextProvider>+ ),+ )+ .exhaustive()}+ {modalContent}+ </DashboardContextProvider>+ </EmbeddingEntityContextProvider>);};diff --git a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.ts b/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.tsdeleted file mode 100644index ef6fdc50fb8..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.ts+++ /dev/null@@ -1,181 +0,0 @@-import { sessionPropertiesPath } from "metabase/api";-import {- PLUGIN_CONTENT_TRANSLATION,- PLUGIN_EMBEDDING_SDK,-} from "metabase/plugins";-import { getEmbedBase, internalBase } from "metabase/services";--const getIgnoreOverridePatterns = () => [- sessionPropertiesPath,- PLUGIN_CONTENT_TRANSLATION.getDictionaryBasePath,-];--/**- * URL patterns used for matching and transforming API requests in Guest Embed mode.- * These patterns are needed only for endpoints that have different parameter names/path/structure for `/embed`- */-const URL_PATTERNS = {- CARD_QUERY: `${internalBase}/card/:cardId/query`,- CARD_PIVOT_QUERY: `${internalBase}/card/pivot/:cardId/query`,- CARD_PARAMETER_VALUES: `${internalBase}/card/:cardId/params/:paramId/values`,- CARD_PARAMETER_SEARCH: `${internalBase}/card/:cardId/params/:paramId/search/:query`,- CARD_PARAMETER_REMAPPING: `${internalBase}/card/:cardId/params/:paramId/remapping`,- DASHBOARD_PARAMETER_VALUES: `${internalBase}/dashboard/:dashId/params/:paramId/values`,- DASHBOARD_PARAMETER_SEARCH: `${internalBase}/dashboard/:dashId/params/:paramId/search/:query`,- DASHBOARD_PARAMETER_REMAPPING: `${internalBase}/dashboard/:dashId/params/:paramId/remapping`,-} as const;--/**- * Mapping of API endpoints to their Guest Embed equivalents.- * Each transformation specifies the embed URL and HTTP method to use.- */-const EMBED_URL_TRANSFORMATIONS: Record<- string,- {- url: string;- method: "GET" | "POST";- }-> = {- [URL_PATTERNS.CARD_QUERY]: {- url: `${getEmbedBase()}/card/:token/query`,- method: "GET",- },- [URL_PATTERNS.CARD_PIVOT_QUERY]: {- url: `${getEmbedBase()}/pivot/card/:token/query`,- method: "GET",- },- [URL_PATTERNS.CARD_PARAMETER_VALUES]: {- url: `${getEmbedBase()}/card/:token/params/:paramId/values`,- method: "GET",- },- [URL_PATTERNS.CARD_PARAMETER_SEARCH]: {- url: `${getEmbedBase()}/card/:token/params/:paramId/search/:query`,- method: "GET",- },- [URL_PATTERNS.DASHBOARD_PARAMETER_VALUES]: {- url: `${getEmbedBase()}/dashboard/:token/params/:paramId/values`,- method: "GET",- },- [URL_PATTERNS.DASHBOARD_PARAMETER_SEARCH]: {- url: `${getEmbedBase()}/dashboard/:token/params/:paramId/search/:query`,- method: "GET",- },-} as const;--type RequestData = {- method: "GET" | "POST";- url: string;- options: {- headers?: Record<string, string>;- hasBody: boolean;- } & Record<string, unknown>;-};--/**- * Converts a URL pattern with parameters (e.g., "/api/card/:id/query")- * into a regular expression that can match actual URLs.- *- * @example- * matchUrlPattern("/api/card/:id/query", "/api/card/123/query") // returns true- * matchUrlPattern("/api/card/:id/query", "/api/card/123/edit") // returns false- */-export function matchUrlPattern(pattern: string, url: string): boolean {- const regexString = pattern- .replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")- .replace(/:([a-zA-Z0-9_]+)/g, "([^/]+)");-- const regex = new RegExp(`^${regexString}$`);-- return regex.test(url);-}--/**- * Finds the URL pattern that matches the given URL.- */-function findMatchingPattern(url: string): string | null {- for (const pattern of Object.values(URL_PATTERNS)) {- if (matchUrlPattern(pattern, url)) {- return pattern;- }- }- return null;-}--/**- * Determines the appropriate request transformation for a given URL.- * Returns null if no transformation is needed.- */-function getRequestTransformation({- method,- url,- options,-}: RequestData): RequestData | null {- const matchedPattern = findMatchingPattern(url);-- if (- getIgnoreOverridePatterns().some(- (endpoint) => endpoint && url.includes(endpoint),- )- ) {- return null;- }-- // No transformation needed if pattern doesn't match- if (!matchedPattern) {- return { method, url, options };- }-- // Apply the transformation for this pattern- const transformation = EMBED_URL_TRANSFORMATIONS[matchedPattern];- if (!transformation) {- return { method, url, options };- }-- return {- ...transformation,- options: {- ...options,- hasBody: transformation.method === "POST",- },- };-}--/**- * Replaces the standard API base path with the embed API base path.- */-function replaceWithEmbedBase(url: string): string {- if (url.includes(internalBase) && !url.includes(getEmbedBase())) {- return url.replace(internalBase, getEmbedBase());- }- return url;-}--/**- * Registers a request interceptor that transforms standard API requests- * into guest embeds API requests.- */-export const overrideRequestsForGuestEmbeds = () => {- PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds =- async ({ method, url, options }) => {- const transformation = getRequestTransformation({ method, url, options });-- if (!transformation) {- return { method, url, options };- }-- if (!options.headers) {- options.headers = {};- }-- /**- * Set header to indicate that this request is for guest embed.- */- options.headers["x-metabase-guest-embed"] = "true";-- return {- method: transformation.method,- url: replaceWithEmbedBase(transformation.url),- options: transformation.options,- };- };-};diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.tsindex f9e6e35a519..ad318e158c8 100644--- a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts@@ -1,4 +1,4 @@-import { overrideRequestsForGuestEmbeds } from "embedding-sdk-bundle/lib/override-requests-for-guest-embeds";+import { overrideRequestsForGuestEmbeds } from "metabase/embedding/lib/override-requests-for-embeds";import { createAsyncThunk } from "metabase/lib/redux";import { refreshSiteSettings } from "metabase/redux/settings";diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.tsindex a00549b6c39..b4c56dd106a 100644--- a/frontend/src/metabase-types/api/card.ts+++ b/frontend/src/metabase-types/api/card.ts@@ -4,7 +4,7 @@ import type {} from "metabase/public/lib/types";import type { IconName } from "metabase/ui";import type { PieRow } from "metabase/visualizations/echarts/pie/model/types";-import type { EntityToken } from "metabase-types/api/entity";+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";import type { Collection, CollectionId, LastEditInfo } from "./collection";import type {@@ -480,7 +480,8 @@ export type GetPublicCard = Pick<Card, "id" | "name" | "public_uuid">;export type GetEmbeddableCard = Pick<Card, "id" | "name">;export type GetRemappedCardParameterValueRequest = {- card_id: CardId | EntityToken;+ card_id?: CardId | EntityToken;+ entityIdentifier?: EntityUuid | EntityToken;parameter_id: ParameterId;value: ParameterValueOrArray;};diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.tsindex 170dabf9bc3..97ee42967bf 100644--- a/frontend/src/metabase-types/api/dashboard.ts+++ b/frontend/src/metabase-types/api/dashboard.ts@@ -22,6 +22,7 @@ import type {VirtualCardDisplay,VisualizerVizDefinition,} from "metabase-types/api";+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";import type {ActionDisplayType,@@ -345,7 +346,8 @@ export type GetPublicDashboard = Pick<Dashboard, "id" | "name" | "public_uuid">;export type GetEmbeddableDashboard = Pick<Dashboard, "id" | "name">;export type GetRemappedDashboardParameterValueRequest = {- dashboard_id: DashboardId;+ dashboard_id?: DashboardId;+ entityIdentifier?: EntityUuid | EntityToken;parameter_id: ParameterId;value: ParameterValueOrArray;};diff --git a/frontend/src/metabase-types/api/entity.ts b/frontend/src/metabase-types/api/entity.tsindex 5eb770aeac9..df16b33d8f0 100644--- a/frontend/src/metabase-types/api/entity.ts+++ b/frontend/src/metabase-types/api/entity.ts@@ -1 +1,3 @@+export type EntityUuid = string;+export type EntityToken = string;diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsxindex 741d4b4f3b3..25a5d88d6a1 100644--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx@@ -17,6 +17,7 @@ import {getVirtualCardType,isVirtualDashCard,} from "metabase/dashboard/utils";+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import { duration } from "metabase/lib/formatting";import { measureTextWidth } from "metabase/lib/measure-text";import { useSelector } from "metabase/lib/redux";@@ -583,49 +584,49 @@ export function DashCardVisualization({})}ref={containerRef}>- <Visualization- className={cx(CS.flexFull, {- [CS.overflowAuto]: visualizationOverlay,- [CS.overflowHidden]: !visualizationOverlay,- })}- dashboard={dashboard ?? undefined}- dashcard={dashcard}- rawSeries={series}- visualizerRawSeries={- isVisualizerDashboardCard(dashcard) ? rawSeries : undefined- }- metadata={metadata}- mode={getClickActionMode}- getHref={getHref}- gridSize={gridSize}- totalNumGridCols={totalNumGridCols}- headerIcon={headerIcon}- expectedDuration={expectedDuration}- error={error?.message}- errorIcon={error?.icon}- showTitle={cardTitled}- canToggleSeriesVisibility={!isEditing}- isAction={isAction}- isDashboard- isSlow={isSlow}- isFullscreen={isFullscreen}- isEditing={isEditing}- isPreviewing={isPreviewing}- isEditingParameter={isEditingParameter}- isMobile={isMobile}- actionButtons={actionButtons}- replacementContent={visualizationOverlay}- getExtraDataForClick={getExtraDataForClick}- onUpdateVisualizationSettings={handleOnUpdateVisualizationSettings}- onTogglePreviewing={onTogglePreviewing}- onChangeCardAndRun={onChangeCardAndRun}- onChangeLocation={onChangeLocation}- renderLoadingView={renderLoadingView}- token={token}- uuid={uuid}- titleMenuItems={titleMenuItems}- errorMessageOverride={visualizerErrMsg}- />+ <EmbeddingEntityContextProvider uuid={uuid ?? null} token={token ?? null}>+ <Visualization+ className={cx(CS.flexFull, {+ [CS.overflowAuto]: visualizationOverlay,+ [CS.overflowHidden]: !visualizationOverlay,+ })}+ dashboard={dashboard ?? undefined}+ dashcard={dashcard}+ rawSeries={series}+ visualizerRawSeries={+ isVisualizerDashboardCard(dashcard) ? rawSeries : undefined+ }+ metadata={metadata}+ mode={getClickActionMode}+ getHref={getHref}+ gridSize={gridSize}+ totalNumGridCols={totalNumGridCols}+ headerIcon={headerIcon}+ expectedDuration={expectedDuration}+ error={error?.message}+ errorIcon={error?.icon}+ showTitle={cardTitled}+ canToggleSeriesVisibility={!isEditing}+ isAction={isAction}+ isDashboard+ isSlow={isSlow}+ isFullscreen={isFullscreen}+ isEditing={isEditing}+ isPreviewing={isPreviewing}+ isEditingParameter={isEditingParameter}+ isMobile={isMobile}+ actionButtons={actionButtons}+ replacementContent={visualizationOverlay}+ getExtraDataForClick={getExtraDataForClick}+ onUpdateVisualizationSettings={handleOnUpdateVisualizationSettings}+ onTogglePreviewing={onTogglePreviewing}+ onChangeCardAndRun={onChangeCardAndRun}+ onChangeLocation={onChangeLocation}+ renderLoadingView={renderLoadingView}+ titleMenuItems={titleMenuItems}+ errorMessageOverride={visualizerErrMsg}+ />+ </EmbeddingEntityContextProvider></div>);}diff --git a/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx b/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsxindex 3d1e5ef1d41..5b92b5a85f0 100644--- a/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardParameterList/DashboardParameterList.tsx@@ -52,7 +52,6 @@ export const DashboardParameterList = forwardRef<hideParameters,parameters: dashboardParameters,parameterValues,- token,} = useDashboardContext();const linkedFilterParameters = useMemo(@@ -73,7 +72,6 @@ export const DashboardParameterList = forwardRef<editingParameter={editingParameter}hideParameters={hideParameters}dashboardId={dashboard?.id}- token={token}isSortable={isSortable}isFullscreen={isFullscreen}isEditing={isEditing}diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex 36df13f0cb3..d05b0fd1a3b 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -13,6 +13,7 @@ import {import { usePrevious, useUnmount } from "react-use";import { isEqual, isObject, noop } from "underscore";+import { useEmbeddingEntityContext } from "metabase/embedding/context";import { getTabHiddenParameterSlugs } from "metabase/public/lib/tab-parameters";import type {Dashboard,@@ -52,7 +53,6 @@ type DashboardActionButtonList = DashboardActionKey[] | null;export type DashboardContextOwnProps = {dashboardId: DashboardId;- token?: EntityToken | null;parameterQueryParams?: ParameterValuesMap;onLoad?: (dashboard: Dashboard) => void;onError?: (error: unknown) => void;@@ -119,7 +119,6 @@ const DashboardContextProviderInner = forwardRef(function DashboardContextProviderInner({dashboardId,- token,parameterQueryParams = {},onLoad,onLoadWithoutCards,@@ -186,6 +185,8 @@ const DashboardContextProviderInner = forwardRef(const previousTabId = usePrevious(selectedTabId);const previousParameterValues = usePrevious(parameterValues);+ const { token } = useEmbeddingEntityContext();+const { refreshDashboardCardData } = useRefreshDashboard({dashboardId,parameterQueryParams,@@ -399,7 +400,6 @@ const DashboardContextProviderInner = forwardRef(<DashboardContext.Providervalue={{dashboardId,- token,dashboard: dashboardWithFilteredCards,parameterQueryParams,onLoad,diff --git a/frontend/src/metabase/embedding/context.tsx b/frontend/src/metabase/embedding/context.tsxnew file mode 100644index 00000000000..e9cb241dd47--- /dev/null+++ b/frontend/src/metabase/embedding/context.tsx@@ -0,0 +1,31 @@+import { type PropsWithChildren, createContext, useContext } from "react";++import type { EntityToken, EntityUuid } from "metabase-types/api/entity";++type EmbeddingEntityContextType = {+ uuid: EntityUuid | null;+ token: EntityToken | null;+};++export const EmbeddingEntityContext = createContext<EmbeddingEntityContextType>(+ undefined as unknown as EmbeddingEntityContextType,+);++export const EmbeddingEntityContextProvider = ({+ children,+ uuid,+ token,+}: PropsWithChildren<EmbeddingEntityContextType>) => (+ <EmbeddingEntityContext.Provider value={{ uuid, token }}>+ {children}+ </EmbeddingEntityContext.Provider>+);++export const useEmbeddingEntityContext = (): EmbeddingEntityContextType => {+ return (+ useContext(EmbeddingEntityContext) ?? {+ uuid: null,+ token: null,+ }+ );+};diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.tsnew file mode 100644index 00000000000..f9f94e632de--- /dev/null+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts@@ -0,0 +1,265 @@+import { sessionPropertiesPath } from "metabase/api";+import {+ PLUGIN_API,+ PLUGIN_CONTENT_TRANSLATION,+ PLUGIN_EMBEDDING_SDK,+} from "metabase/plugins";+import type { OnBeforeRequestHandlerData } from "metabase/plugins/oss/api";+import { getEmbedBase, internalBase, publicBase } from "metabase/services";+import type { CardId, DashboardId, ParameterId } from "metabase-types/api";++type EmbedType = "guest" | "static" | "public";++const getBaseUrlByEmbedType = (embedType: EmbedType): string =>+ ({+ guest: getEmbedBase(),+ static: getEmbedBase(),+ public: publicBase,+ })[embedType];++const getIgnoreOverridePatterns = () => [+ sessionPropertiesPath,+ PLUGIN_CONTENT_TRANSLATION.getDictionaryBasePath,+];++/**+ * URL patterns used for matching and transforming API requests in Guest Embed mode.+ * These patterns are needed only for endpoints that have different parameter names/path/structure for `/embed`+ */+const URL_PATTERNS = {+ CARD_QUERY: `${internalBase}/card/:cardId/query`,+ CARD_PIVOT_QUERY: `${internalBase}/card/pivot/:cardId/query`,+ CARD_PARAMETER_VALUES: `${internalBase}/card/:cardId/params/:paramId/values`,+ CARD_PARAMETER_SEARCH: `${internalBase}/card/:cardId/params/:paramId/search/:query`,+ CARD_PARAMETER_REMAPPING: `${internalBase}/card/:cardId/params/:paramId/remapping`,+ DASHBOARD_PARAMETER_VALUES: `${internalBase}/dashboard/:dashId/params/:paramId/values`,+ DASHBOARD_PARAMETER_SEARCH: `${internalBase}/dashboard/:dashId/params/:paramId/search/:query`,+ DASHBOARD_PARAMETER_REMAPPING: `${internalBase}/dashboard/:dashId/params/:paramId/remapping`,+} as const;++/**+ * Mapping of API endpoints to their Guest Embed equivalents.+ * Each transformation specifies the embed URL and HTTP method to use.+ */+const EMBED_URL_TRANSFORMATIONS: Record<+ string,+ (data: { embedType: EmbedType }) => {+ url: string;+ method: "GET" | "POST";+ }+> = {+ [URL_PATTERNS.CARD_QUERY]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/card/:token/query`,+ method: "GET",+ }),+ [URL_PATTERNS.CARD_PIVOT_QUERY]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/pivot/card/:token/query`,+ method: "GET",+ }),+ [URL_PATTERNS.CARD_PARAMETER_VALUES]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/card/:entityIdentifier/params/:paramId/values`,+ method: "GET",+ }),+ [URL_PATTERNS.CARD_PARAMETER_SEARCH]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/card/:entityIdentifier/params/:paramId/search/:query`,+ method: "GET",+ }),+ [URL_PATTERNS.CARD_PARAMETER_REMAPPING]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/card/:entityIdentifier/params/:paramId/remapping`,+ method: "GET",+ }),+ [URL_PATTERNS.DASHBOARD_PARAMETER_VALUES]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/dashboard/:entityIdentifier/params/:paramId/values`,+ method: "GET",+ }),+ [URL_PATTERNS.DASHBOARD_PARAMETER_SEARCH]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/dashboard/:entityIdentifier/params/:paramId/search/:query`,+ method: "GET",+ }),+ [URL_PATTERNS.DASHBOARD_PARAMETER_REMAPPING]: ({ embedType }) => ({+ url: `${getBaseUrlByEmbedType(embedType)}/dashboard/:entityIdentifier/params/:paramId/remapping`,+ method: "GET",+ }),+} as const;++type RequestData = {+ method: "GET" | "POST";+ url: string;+ options: {+ headers?: Record<string, string>;+ hasBody: boolean;+ } & Record<string, unknown>;+};++/**+ * Converts a URL pattern with parameters (e.g., "/api/card/:id/query")+ * into a regular expression that can match actual URLs.+ *+ * @example+ * matchUrlPattern("/api/card/:id/query", "/api/card/123/query") // returns true+ * matchUrlPattern("/api/card/:id/query", "/api/card/123/edit") // returns false+ */+export function matchUrlPattern(pattern: string, url: string): boolean {+ const regexString = pattern+ .replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")+ .replace(/:([a-zA-Z0-9_]+)/g, "([^/]+)");++ const regex = new RegExp(`^${regexString}$`);++ return regex.test(url);+}++/**+ * Finds the URL pattern that matches the given URL.+ */+function findMatchingPattern(url: string): string | null {+ for (const pattern of Object.values(URL_PATTERNS)) {+ if (matchUrlPattern(pattern, url)) {+ return pattern;+ }+ }+ return null;+}++/**+ * Determines the appropriate request transformation for a given URL.+ * Returns null if no transformation is needed.+ */+function getRequestTransformation({+ method,+ embedType,+ url,+ options,+}: RequestData & { embedType: EmbedType }): RequestData | null {+ const matchedPattern = findMatchingPattern(url);++ if (+ getIgnoreOverridePatterns().some(+ (endpoint) => endpoint && url.includes(endpoint),+ )+ ) {+ return null;+ }++ // No transformation needed if pattern doesn't match+ if (!matchedPattern) {+ return { method, url, options };+ }++ // Apply the transformation for this pattern+ const transformation = EMBED_URL_TRANSFORMATIONS[matchedPattern]({+ embedType,+ });+ if (!transformation) {+ return { method, url, options };+ }++ return {+ ...transformation,+ options: {+ ...options,+ hasBody: transformation.method === "POST",+ },+ };+}++/**+ * Replaces the standard API base path with the embed API base path.+ */+function replaceWithEmbedBase({+ embedType,+ url,+}: {+ embedType: EmbedType;+ url: string;+}): string {+ const baseUrl = getBaseUrlByEmbedType(embedType);++ if (url.includes(internalBase) && !url.includes(baseUrl)) {+ return url.replace(internalBase, baseUrl);+ }++ return url;+}++const overrideRequests = async ({+ embedType,+ method,+ url,+ options,+}: OnBeforeRequestHandlerData & {+ embedType: EmbedType;+}) => {+ const transformation = getRequestTransformation({+ method,+ embedType,+ url,+ options,+ });++ if (!transformation) {+ return { method, url, options };+ }++ if (!options.headers) {+ options.headers = {};+ }++ /**+ * Set header to indicate that this request is for guest embed.+ */+ options.headers["x-metabase-guest-embed"] = "true";++ return {+ method: transformation.method,+ url: replaceWithEmbedBase({ embedType, url: transformation.url }),+ options: transformation.options,+ };+};++const setupRemappingUrls = (embedType: EmbedType) => {+ const baseUrl = getBaseUrlByEmbedType(embedType);++ PLUGIN_API.getRemappedDashboardParameterValueUrl = (+ _dashboardId: DashboardId | undefined,+ parameterId: ParameterId,+ ) =>+ `${baseUrl}/dashboard/:entityIdentifier/params/${encodeURIComponent(parameterId)}/remapping`;++ PLUGIN_API.getRemappedCardParameterValueUrl = (+ _cardId: CardId | string | undefined,+ parameterId: ParameterId,+ ) =>+ `${baseUrl}/card/:entityIdentifier/params/${encodeURIComponent(parameterId)}/remapping`;+};++/**+ * Registers a request interceptor that transforms standard API requests+ * into guest embeds API requests.+ */+export const overrideRequestsForGuestEmbeds = () => {+ setupRemappingUrls("guest");++ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds =+ (data) =>+ overrideRequests({+ ...data,+ embedType: "guest",+ });+};++/**+ * Registers a request interceptor that transforms standard API requests+ * into public or static embeds API requests.+ */+export const overrideRequestsForPublicOrStaticEmbeds = (+ embedType: "static" | "public",+) => {+ setupRemappingUrls(embedType);++ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds = (data) =>+ overrideRequests({+ ...data,+ embedType,+ });+};diff --git a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.tssimilarity index 97%rename from frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.tsrename to frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.tsindex 8eb3f505c1b..fea63742cfd 100644--- a/frontend/src/embedding-sdk-bundle/lib/override-requests-for-guest-embeds.unit.spec.ts+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts@@ -1,4 +1,4 @@-import { matchUrlPattern } from "./override-requests-for-guest-embeds";+import { matchUrlPattern } from "./override-requests-for-embeds";describe("matchUrlPattern", () => {it("should match URL with single parameter", () => {diff --git a/frontend/src/metabase/hoc/Remapped.jsx b/frontend/src/metabase/hoc/Remapped.jsxindex b9fe7d7aab4..c5c82dc36b5 100644--- a/frontend/src/metabase/hoc/Remapped.jsx+++ b/frontend/src/metabase/hoc/Remapped.jsx@@ -35,6 +35,7 @@ export default (ComposedComponent) =>field: this.props.column,cardId: this.props.cardId,dashboardId: this.props.dashboardId,+ uuid: this.props.uuid,token: this.props.token,});}@@ -47,6 +48,7 @@ export default (ComposedComponent) =>this.props.parameter?.id !== nextProps.parameter?.id ||this.props.cardId !== nextProps.cardId ||this.props.dashboardId !== nextProps.dashboardId ||+ this.props.uuid !== nextProps.uuid ||this.props.token !== nextProps.token)) {this.props.fetchRemapping({@@ -55,6 +57,7 @@ export default (ComposedComponent) =>field: this.props.column,cardId: nextProps.cardId,dashboardId: nextProps.dashboardId,+ uuid: nextProps.uuid,token: nextProps.token,});}diff --git a/frontend/src/metabase/lib/api.js b/frontend/src/metabase/lib/api.jsindex d683181a219..41088676630 100644--- a/frontend/src/metabase/lib/api.js+++ b/frontend/src/metabase/lib/api.js@@ -6,7 +6,7 @@ import { isTest } from "metabase/env";import { isWithinIframe } from "metabase/lib/dom";import { IFRAMED_IN_SELF } from "metabase/lib/iframe";import { delay } from "metabase/lib/promise";-import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";+import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";const ONE_SECOND = 1000;const MAX_RETRIES = 10;@@ -399,6 +399,13 @@ export class Api extends EventEmitter {.overrideRequestsForGuestEmbeds,],);+ } else {+ handlers.push(+ ...[+ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds,+ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForStaticEmbeds,+ ],+ );}if (handlers.length) {diff --git a/frontend/src/metabase/parameters/actions.ts b/frontend/src/metabase/parameters/actions.tsindex c5d48e7940b..e0c4dc519fb 100644--- a/frontend/src/metabase/parameters/actions.ts+++ b/frontend/src/metabase/parameters/actions.ts@@ -10,7 +10,7 @@ import type {ParameterId,ParameterValues,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";import type { Dispatch, GetState } from "metabase-types/store";import { getParameterValuesCache } from "./selectors";@@ -50,16 +50,21 @@ export const fetchParameterValues =export interface FetchCardParameterValuesOpts {cardId: CardId;- token?: EntityToken | null;+ entityIdentifier: EntityUuid | EntityToken | null;parameter: Parameter;query?: string;}export const fetchCardParameterValues =- ({ cardId, token, parameter, query }: FetchCardParameterValuesOpts) =>+ ({+ cardId,+ entityIdentifier,+ parameter,+ query,+ }: FetchCardParameterValuesOpts) =>(dispatch: Dispatch, getState: GetState) => {const request: CardParameterValuesRequest = {- ...(token ? { token } : { cardId }),+ ...(entityIdentifier ? { entityIdentifier } : { cardId }),paramId: parameter.id,query,};@@ -74,7 +79,7 @@ export const fetchCardParameterValues =export interface FetchDashboardParameterValuesOpts {dashboardId: DashboardId;- token?: EntityToken | null;+ entityIdentifier: EntityUuid | EntityToken | null;parameter: Parameter;parameters: Parameter[];query?: string;@@ -83,14 +88,14 @@ export interface FetchDashboardParameterValuesOpts {export const fetchDashboardParameterValues =({dashboardId,- token,+ entityIdentifier,parameter,parameters,query,}: FetchDashboardParameterValuesOpts) =>(dispatch: Dispatch, getState: GetState) => {const request: DashboardParameterValuesRequest = {- ...(token ? { token } : { dashId: dashboardId }),+ ...(entityIdentifier ? { entityIdentifier } : { dashId: dashboardId }),paramId: parameter.id,query,...getFilteringParameterValuesMap(parameter, parameters),@@ -123,7 +128,7 @@ const loadParameterValues = async (request: ParameterValuesRequest) => {interface CardParameterValuesRequest {cardId?: CardId;- token?: EntityToken | null;+ entityIdentifier?: EntityUuid | EntityToken | null;paramId: ParameterId;query?: string;}@@ -141,7 +146,7 @@ const loadCardParameterValues = async (request: CardParameterValuesRequest) => {interface DashboardParameterValuesRequest {dashId?: DashboardId;- token?: EntityToken | null;+ entityIdentifier?: EntityUuid | EntityToken | null;paramId: ParameterId;query?: string;}diff --git a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsxindex ec17aceb544..f0a66a04664 100644--- a/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx+++ b/frontend/src/metabase/parameters/components/FormattedParameterValue/FormattedParameterValue.tsx@@ -22,14 +22,12 @@ import type {ParameterValue,RowValue,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";export type FormattedParameterValueProps = {parameter: UiParameter;value: string | number | number[] | ParameterValue;cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;placeholder?: string;isPopoverOpen?: boolean;dataTestId?: string;@@ -40,7 +38,6 @@ function FormattedParameterValue({value,cardId,dashboardId,- token,placeholder,isPopoverOpen = false,}: FormattedParameterValueProps) {@@ -72,7 +69,6 @@ function FormattedParameterValue({parameter={parameter}cardId={cardId}dashboardId={dashboardId}- token={token}displayValue={label}/>);diff --git a/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx b/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsxindex 60ede6e135a..aa757a31e59 100644--- a/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterDropdownWidget.tsx@@ -48,7 +48,6 @@ export const ParameterDropdownWidget = ({parameters,cardId,dashboardId,- token,enableRequiredBehavior,}: ParameterDropdownWidgetProps) => {const normalizedValue = Array.isArray(value)@@ -154,7 +153,6 @@ export const ParameterDropdownWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}value={normalizedValue}fields={parameter.fields}setValue={setValueOrDefault}diff --git a/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx b/frontend/src/metabase/parameters/components/ParameterValueWidget.tsxindex aa3211499a3..6b3d7f84d42 100644--- a/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterValueWidget.tsx@@ -23,7 +23,6 @@ import {parameterHasNoDisplayValue,} from "metabase-lib/v1/parameters/utils/parameter-values";import type { CardId, DashboardId, ParameterId } from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import {ParameterDropdownWidget,@@ -45,7 +44,6 @@ export type ParameterValueWidgetProps = {parameters?: UiParameter[];cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;setParameterValueToDefault?: (parameterId: ParameterId) => void;// This means the widget will take care of the default value.// Should be used for dashboards and native questions in the parameter bar,@@ -70,7 +68,6 @@ export const ParameterValueWidget = ({placeholder,cardId,dashboardId,- token,setParameterValueToDefault,setValue,value,@@ -223,7 +220,6 @@ export const ParameterValueWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}value={value}setValue={setValue}isEditing={isEditing}@@ -291,7 +287,6 @@ export const ParameterValueWidget = ({value={value}cardId={cardId}dashboardId={dashboardId}- token={token}placeholder={placeholderText}isPopoverOpen={isOpen}/>@@ -312,7 +307,6 @@ export const ParameterValueWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}value={value}setValue={setValue}isEditing={isEditing}diff --git a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsxindex 7f29d08d5a8..0e75171a504 100644--- a/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx+++ b/frontend/src/metabase/parameters/components/ParameterWidget/ParameterWidget.tsx@@ -21,7 +21,6 @@ import type {Parameter,ParameterId,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import { ParameterValueWidget } from "../ParameterValueWidget";@@ -35,7 +34,6 @@ export type ParameterWidgetProps = PropsWithChildren<setValue: (value: any) => void;cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;editingParameter: Parameter | null;commitImmediately: boolean;@@ -59,7 +57,6 @@ export type ParameterWidgetProps = PropsWithChildren<export const ParameterWidget = ({cardId,dashboardId,- token,parameter,editingParameter,commitImmediately = false,@@ -156,7 +153,6 @@ export const ParameterWidget = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}value={parameter.value}setValue={(value) => setValue?.(value)}isEditing={isEditingParameter}diff --git a/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx b/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsxindex 25430803e2e..48cef44da66 100644--- a/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx+++ b/frontend/src/metabase/parameters/components/ParametersList/ParametersList.tsx@@ -27,7 +27,6 @@ export const ParametersList = forwardRef<HTMLDivElement, ParametersListProps>(linkedFilterParameters = parameters,cardId,dashboardId,- token,editingParameter,isSortable = true,@@ -83,7 +82,6 @@ export const ParametersList = forwardRef<HTMLDivElement, ParametersListProps>(parameters={linkedFilterParameters}cardId={cardId}dashboardId={dashboardId}- token={token}editingParameter={editingParameter}setEditingParameter={setEditingParameter}setValue={diff --git a/frontend/src/metabase/parameters/components/ParametersList/types.ts b/frontend/src/metabase/parameters/components/ParametersList/types.tsindex 5de6f042478..10328422141 100644--- a/frontend/src/metabase/parameters/components/ParametersList/types.ts+++ b/frontend/src/metabase/parameters/components/ParametersList/types.ts@@ -8,7 +8,6 @@ import type {Parameter,ParameterId,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import type { ParameterWidgetProps } from "../ParameterWidget";@@ -20,7 +19,6 @@ export type ParametersListProps = {cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;editingParameter: Parameter | null | undefined;linkedFilterParameters: Parameter[];diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsxindex e4e9411ab28..578b957e983 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx@@ -24,6 +24,7 @@ import TokenField, {} from "metabase/common/components/TokenField";import type { LayoutRendererArgs } from "metabase/common/components/TokenField/TokenField";import CS from "metabase/css/core/index.css";+import { useEmbeddingEntityContext } from "metabase/embedding/context";import { Fields } from "metabase/entities/fields";import { useTranslateContent } from "metabase/i18n/hooks";import type { ContentTranslationFunction } from "metabase/i18n/types";@@ -54,7 +55,6 @@ import type {ParameterValueOrArray,RowValue,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import type { State } from "metabase-types/store";import { Value as ValueComponent } from "../Value";@@ -114,7 +114,6 @@ export interface IFieldValuesWidgetProps {fields: Field[];dashboardId?: DashboardId;cardId?: CardId;- token?: EntityToken | null;value: RowValue[];onChange: (value: RowValue[]) => void;@@ -153,7 +152,6 @@ export const FieldValuesWidgetInner = forwardRef<fields,dashboardId,cardId,- token,value,onChange,multi,@@ -184,6 +182,9 @@ export const FieldValuesWidgetInner = forwardRef<const previousWidth = usePrevious(width);+ const { uuid, token } = useEmbeddingEntityContext();+ const entityIdentifier = uuid ?? token ?? null;+useMount(() => {if (shouldList({ parameter, fields, disableSearch })) {fetchValues();@@ -251,7 +252,7 @@ export const FieldValuesWidgetInner = forwardRef<return dispatch(fetchCardParameterValues({cardId,- token,+ entityIdentifier,parameter,query,}),@@ -266,7 +267,7 @@ export const FieldValuesWidgetInner = forwardRef<return dispatch(fetchDashboardParameterValues({dashboardId,- token,+ entityIdentifier,parameter,parameters,query,@@ -329,7 +330,6 @@ export const FieldValuesWidgetInner = forwardRef<parameter,cardId,dashboardId,- token,autoLoad: true,compact: false,displayValue: option?.[1],@@ -346,7 +346,6 @@ export const FieldValuesWidgetInner = forwardRef<parameter,cardId,dashboardId,- token,autoLoad: false,displayValue: option[1],});@@ -489,7 +488,6 @@ export const FieldValuesWidgetInner = forwardRef<fields={fields}dashboardId={dashboardId}cardId={cardId}- token={token}value={isNumericParameter ? parseNumericValue(value) : value}tc={tc}/>@@ -679,7 +677,6 @@ function renderValue({parameter,cardId,dashboardId,- token,fields,value,formatOptions,@@ -693,7 +690,6 @@ function renderValue({parameter?: Parameter;cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;autoLoad?: boolean;compact?: boolean;displayValue?: string;@@ -705,7 +701,6 @@ function renderValue({parameter={parameter}cardId={cardId}dashboardId={dashboardId}- token={token}maximumFractionDigits={20}remap={displayValue || Field.remappedField(fields) != null}displayValue={displayValue}@@ -722,7 +717,6 @@ type RemappedValueProps = {value: ParameterValueOrArray | null;dashboardId?: DashboardId;cardId?: CardId;- token?: EntityToken | null;tc: ContentTranslationFunction;};@@ -732,9 +726,11 @@ function RemappedValue({value,dashboardId,cardId,- token,tc,}: RemappedValueProps) {+ const { uuid, token } = useEmbeddingEntityContext();+ const entityIdentifier = uuid ?? token ?? null;+const isRemapped =Field.remappedField(fields) != null ||getSourceType(parameter) === "static-list";@@ -742,7 +738,9 @@ function RemappedValue({const { data: dashboardData } = useGetRemappedDashboardParameterValueQuery(dashboardId != null && value != null && isRemapped? {- dashboard_id: token ?? dashboardId,+ ...(entityIdentifier+ ? { entityIdentifier }+ : { dashboard_id: dashboardId }),parameter_id: parameter.id,value,}@@ -752,7 +750,7 @@ function RemappedValue({const { data: cardData } = useGetRemappedCardParameterValueQuery(cardId != null && value != null && isRemapped? {- card_id: token ?? cardId,+ ...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),parameter_id: parameter.id,value,}diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsxindex bbfa6e1b667..fe65153c420 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx@@ -18,7 +18,6 @@ import {hasValue,} from "metabase-lib/v1/parameters/utils/parameter-values";import type { CardId, DashboardId, RowValue } from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import { Footer } from "../Widget";import { MIN_WIDTH } from "../constants";@@ -35,7 +34,6 @@ interface ParameterFieldWidgetProps {value?: string | string[];cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;}export function ParameterFieldWidget({@@ -47,7 +45,6 @@ export function ParameterFieldWidget({parameters,cardId,dashboardId,- token,}: ParameterFieldWidgetProps) {const [unsavedValue, setUnsavedValue] = useState<RowValue[]>(() =>normalizeValue(value),@@ -107,7 +104,6 @@ export function ParameterFieldWidget({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}onChange={onValueChange}placeholder={isEditing ? t`Enter a default value…` : undefined}fields={fields}diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsxindex 5d28f39cca6..ab4cb27c69f 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx@@ -1,7 +1,6 @@import { renderNumberOfSelections } from "metabase/parameters/utils/formatting";import Field from "metabase-lib/v1/metadata/Field";import type { CardId, DashboardId, Parameter } from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import { Value } from "../Value";import { normalizeValue } from "../normalizeValue";@@ -12,7 +11,6 @@ type ParameterFieldWidgetValueProps = {parameter: Parameter;cardId?: CardId;dashboardId?: DashboardId;- token?: EntityToken | null;displayValue?: string;};@@ -22,7 +20,6 @@ export function ParameterFieldWidgetValue({parameter,cardId,dashboardId,- token,displayValue,}: ParameterFieldWidgetValueProps) {const values = normalizeValue(value);@@ -40,7 +37,6 @@ export function ParameterFieldWidgetValue({parameter={parameter}cardId={cardId}dashboardId={dashboardId}- token={token}displayValue={displayValue}/>);diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsxindex 2f2df2f277f..6356c54fffb 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/Value.tsx@@ -1,10 +1,10 @@import { isValidElement } from "react";+import { useEmbeddingEntityContext } from "metabase/embedding/context";import { useTranslateContent } from "metabase/i18n/hooks";import { formatValue } from "metabase/lib/formatting";import type { OptionsType } from "metabase/lib/formatting/types";import type { DashboardId, Parameter } from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import RemappedValue from "./RemappedValue";@@ -19,9 +19,9 @@ export const Value = ({parameter?: Parameter;cardId?: number;dashboardId?: DashboardId;- token?: EntityToken | null;} & OptionsType) => {const tc = useTranslateContent<unknown>();+ const { uuid, token } = useEmbeddingEntityContext();if (rawOptions.hide) {return null;@@ -31,6 +31,8 @@ export const Value = ({const options = {...rawOptions,+ uuid,+ token,displayValue: tc(rawOptions.displayValue),};diff --git a/frontend/src/metabase/plugins/oss/api.ts b/frontend/src/metabase/plugins/oss/api.tsindex 89c841edcee..91bb76d35b2 100644--- a/frontend/src/metabase/plugins/oss/api.ts+++ b/frontend/src/metabase/plugins/oss/api.ts@@ -1,13 +1,34 @@import type { CardId, DashboardId, ParameterId } from "metabase-types/api";+export type OnBeforeRequestHandlerData = {+ method: "GET" | "POST";+ url: string;+ options: {+ headers?: Record<string, string>;+ hasBody: boolean;+ } & Record<string, unknown>;+};++export type OnBeforeRequestHandler = (+ data: OnBeforeRequestHandlerData,+) => Promise<void | OnBeforeRequestHandlerData>;+const getDefaultPluginApi = () => ({+ onBeforeRequestHandlers: {+ overrideRequestsForPublicEmbeds: async (+ _data: OnBeforeRequestHandlerData,+ ): Promise<OnBeforeRequestHandlerData | void> => {},+ overrideRequestsForStaticEmbeds: async (+ _data: OnBeforeRequestHandlerData,+ ): Promise<OnBeforeRequestHandlerData | void> => {},+ },getRemappedCardParameterValueUrl: (- cardId: CardId | string,+ cardId: CardId | string | undefined,parameterId: ParameterId,) =>`/api/card/${cardId}/params/${encodeURIComponent(parameterId)}/remapping`,getRemappedDashboardParameterValueUrl: (- dashboardId: DashboardId,+ dashboardId: DashboardId | undefined,parameterId: ParameterId,) =>`/api/dashboard/${dashboardId}/params/${encodeURIComponent(parameterId)}/remapping`,diff --git a/frontend/src/metabase/plugins/oss/embedding-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-sdk.tsindex a0cde686f9c..f25ae74eeb8 100644--- a/frontend/src/metabase/plugins/oss/embedding-sdk.ts+++ b/frontend/src/metabase/plugins/oss/embedding-sdk.ts@@ -1,15 +1,4 @@-export type OnBeforeRequestHandlerData = {- method: "GET" | "POST";- url: string;- options: {- headers?: Record<string, string>;- hasBody: boolean;- } & Record<string, unknown>;-};--export type OnBeforeRequestHandler = (- data: OnBeforeRequestHandlerData,-) => Promise<void | OnBeforeRequestHandlerData>;+import type { OnBeforeRequestHandlerData } from "metabase/plugins/oss/api";const getDefaultPluginEmbeddingSdk = () => ({isEnabled: () => false,diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsxindex 43ce71f88e4..45576cfa7fb 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx@@ -6,6 +6,7 @@ import { useDashboardLocationSync } from "metabase/dashboard/containers/Dashboarimport { DashboardContextProvider } from "metabase/dashboard/context";import { useDashboardUrlQuery } from "metabase/dashboard/hooks/use-dashboard-url-query";import { isActionDashCard, isQuestionCard } from "metabase/dashboard/utils";+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import { useDispatch, useSelector } from "metabase/lib/redux";import { LocaleProvider } from "metabase/public/LocaleProvider";import { useEmbedFrameOptions, useSetEmbedFont } from "metabase/public/hooks";@@ -14,8 +15,8 @@ import { getCanWhitelabel } from "metabase/selectors/whitelabel";import { Mode } from "metabase/visualizations/click-actions/Mode";import { PublicMode } from "metabase/visualizations/click-actions/modes/PublicMode";+import { usePublicEndpoints } from "../../../hooks/use-public-endpoints";import { PublicOrEmbeddedDashboardView } from "../PublicOrEmbeddedDashboardView";-import { usePublicDashboardEndpoints } from "../use-public-dashboard-endpoints";const PublicOrEmbeddedDashboardPageInner = ({location,@@ -30,10 +31,14 @@ const PublicOrEmbeddedDashboardPageInner = ({export const PublicOrEmbeddedDashboardPage = (props: WithRouterProps) => {const dispatch = useDispatch();- const { location } = props;+ const { location, params } = props;+ const { uuid, token } = params;+const parameterQueryParams = props.location.query;- const { dashboardId } = usePublicDashboardEndpoints(props);+ const dashboardId = uuid || token;++ usePublicEndpoints({ uuid, token });useSetEmbedFont({ location });@@ -54,35 +59,40 @@ export const PublicOrEmbeddedDashboardPage = (props: WithRouterProps) => {locale={canWhitelabel ? locale : undefined}shouldWaitForLocale>- <DashboardContextProvider- dashboardId={dashboardId}- hideParameters={hide_parameters}- theme={theme}- background={background}- bordered={bordered}- downloadsEnabled={downloadsEnabled}- titled={titled}- parameterQueryParams={parameterQueryParams}- cardTitled={true}- withFooter={true}- getClickActionMode={({ question }) => new Mode(question, PublicMode)}- navigateToNewCardFromDashboard={null}- onError={(error) => {- dispatch(setErrorPage(error));- }}- isDashcardVisible={(dashcard) => !isActionDashCard(dashcard)}- dashcardMenu={({ dashcard, result }) =>- downloadsEnabled?.results &&- isQuestionCard(dashcard.card) &&- !!result?.data &&- !result?.error && (- <PublicOrEmbeddedDashCardMenu result={result} dashcard={dashcard} />- )- }- dashboardActions={DASHBOARD_DISPLAY_ACTIONS}- >- <PublicOrEmbeddedDashboardPageInner {...props} />- </DashboardContextProvider>+ <EmbeddingEntityContextProvider uuid={uuid} token={token}>+ <DashboardContextProvider+ dashboardId={dashboardId}+ hideParameters={hide_parameters}+ theme={theme}+ background={background}+ bordered={bordered}+ downloadsEnabled={downloadsEnabled}+ titled={titled}+ parameterQueryParams={parameterQueryParams}+ cardTitled={true}+ withFooter={true}+ getClickActionMode={({ question }) => new Mode(question, PublicMode)}+ navigateToNewCardFromDashboard={null}+ onError={(error) => {+ dispatch(setErrorPage(error));+ }}+ isDashcardVisible={(dashcard) => !isActionDashCard(dashcard)}+ dashcardMenu={({ dashcard, result }) =>+ downloadsEnabled?.results &&+ isQuestionCard(dashcard.card) &&+ !!result?.data &&+ !result?.error && (+ <PublicOrEmbeddedDashCardMenu+ result={result}+ dashcard={dashcard}+ />+ )+ }+ dashboardActions={DASHBOARD_DISPLAY_ACTIONS}+ >+ <PublicOrEmbeddedDashboardPageInner {...props} />+ </DashboardContextProvider>+ </EmbeddingEntityContextProvider></LocaleProvider>);};diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/use-public-dashboard-endpoints.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/use-public-dashboard-endpoints.tsxdeleted file mode 100644index de78a01f72d..00000000000--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/use-public-dashboard-endpoints.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useEffect } from "react";-import type { WithRouterProps } from "react-router";--import {- setEmbedDashboardEndpoints,- setPublicDashboardEndpoints,-} from "metabase/services";--export const usePublicDashboardEndpoints = (props: WithRouterProps) => {- const { uuid, token } = props.params;-- useEffect(() => {- if (uuid) {- setPublicDashboardEndpoints(uuid);- } else if (token) {- setEmbedDashboardEndpoints(token);- }- }, [uuid, token]);-- const dashboardId = uuid || token;-- return { dashboardId };-};diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsxindex c01ed7e22b4..d8dac69752f 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx@@ -2,21 +2,17 @@ import type { Location } from "history";import { useCallback, useEffect, useState } from "react";import { useLatest, useMount } from "react-use";+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";import { useDispatch, useSelector } from "metabase/lib/redux";import { LocaleProvider } from "metabase/public/LocaleProvider";import { useEmbedFrameOptions } from "metabase/public/hooks";+import { usePublicEndpoints } from "metabase/public/hooks/use-public-endpoints";import { useSetEmbedFont } from "metabase/public/hooks/use-set-embed-font";import { setErrorPage } from "metabase/redux/app";import { addFields } from "metabase/redux/metadata";import { getMetadata } from "metabase/selectors/metadata";import { getCanWhitelabel } from "metabase/selectors/whitelabel";-import {- EmbedApi,- PublicApi,- maybeUsePivotEndpoint,- setEmbedQuestionEndpoints,- setPublicQuestionEndpoints,-} from "metabase/services";+import { EmbedApi, PublicApi, maybeUsePivotEndpoint } from "metabase/services";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";import { getParameterValuesByIdFromQueryParams } from "metabase-lib/v1/parameters/utils/parameter-parsing";import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";@@ -59,13 +55,9 @@ export const PublicOrEmbeddedQuestion = ({const canWhitelabel = useSelector(getCanWhitelabel);- useMount(async () => {- if (uuid) {- setPublicQuestionEndpoints(uuid);- } else if (token) {- setEmbedQuestionEndpoints(token);- }+ usePublicEndpoints({ uuid, token });+ useMount(async () => {try {let card;if (token) {@@ -189,24 +181,24 @@ export const PublicOrEmbeddedQuestion = ({locale={canWhitelabel ? locale : undefined}shouldWaitForLocale>- <PublicOrEmbeddedQuestionView- initialized={initialized}- card={card}- metadata={metadata}- result={result}- uuid={uuid}- token={token}- getParameters={getParameters}- parameterValues={parameterValues}- setParameterValue={setParameterValue}- setParameterValueToDefault={setParameterValueToDefault}- bordered={bordered}- hide_parameters={hide_parameters}- theme={theme}- titled={titled}- setCard={setCard}- downloadsEnabled={downloadsEnabled}- />+ <EmbeddingEntityContextProvider uuid={uuid} token={token}>+ <PublicOrEmbeddedQuestionView+ initialized={initialized}+ card={card}+ metadata={metadata}+ result={result}+ getParameters={getParameters}+ parameterValues={parameterValues}+ setParameterValue={setParameterValue}+ setParameterValueToDefault={setParameterValueToDefault}+ bordered={bordered}+ hide_parameters={hide_parameters}+ theme={theme}+ titled={titled}+ setCard={setCard}+ downloadsEnabled={downloadsEnabled}+ />+ </EmbeddingEntityContextProvider></LocaleProvider>);};diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestionView.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestionView.tsxindex a76dd9e1496..8ee839e3828 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestionView.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestionView.tsx@@ -24,15 +24,12 @@ import type {RawSeries,VisualizationSettings,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";export interface PublicOrEmbeddedQuestionViewProps {initialized: boolean;card: Card | null;metadata: Metadata;result: Dataset | null;- uuid: string;- token: EntityToken;getParameters: () => UiParameter[];parameterValues: ParameterValuesMap;setParameterValue: (parameterId: ParameterId, value: any) => Promise<void>;@@ -49,8 +46,6 @@ export function PublicOrEmbeddedQuestionView({card,metadata,result,- uuid,- token,getParameters,parameterValues,setParameterValue,@@ -78,8 +73,6 @@ export function PublicOrEmbeddedQuestionView({)}question={question}result={result}- uuid={uuid}- token={token}floating={!titled && !isTable}/>) : null;@@ -140,8 +133,6 @@ export function PublicOrEmbeddedQuestionView({isDashboardmetadata={metadata}onChangeCardAndRun={() => {}}- token={token}- uuid={uuid}tableFooterExtraButtons={downloadInFooter ? questionResultDownloadButton : null}diff --git a/frontend/src/metabase/public/hooks/use-public-endpoints.tsx b/frontend/src/metabase/public/hooks/use-public-endpoints.tsxnew file mode 100644index 00000000000..e558d0995d3--- /dev/null+++ b/frontend/src/metabase/public/hooks/use-public-endpoints.tsx@@ -0,0 +1,22 @@+import { useMount } from "react-use";++import { overrideRequestsForPublicOrStaticEmbeds } from "metabase/embedding/lib/override-requests-for-embeds";+import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";++export const usePublicEndpoints = ({+ uuid,+ token,+}: {+ uuid: EntityUuid;+ token: EntityToken;+}) => {+ useMount(() => {+ if (uuid) {+ overrideRequestsForPublicOrStaticEmbeds("public");+ } else if (token) {+ PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);+ overrideRequestsForPublicOrStaticEmbeds("static");+ }+ });+};diff --git a/frontend/src/metabase/query_builder/components/QuestionDownloadPopover/QuestionDownloadPopover.tsx b/frontend/src/metabase/query_builder/components/QuestionDownloadPopover/QuestionDownloadPopover.tsxindex 7a7bf47e60f..e7ab72ae5f3 100644--- a/frontend/src/metabase/query_builder/components/QuestionDownloadPopover/QuestionDownloadPopover.tsx+++ b/frontend/src/metabase/query_builder/components/QuestionDownloadPopover/QuestionDownloadPopover.tsx@@ -6,6 +6,7 @@ import type {ExportFormat,TableExportFormat,} from "metabase/common/types/export";+import { useEmbeddingEntityContext } from "metabase/embedding/context";import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";import {ActionIcon,@@ -47,13 +48,12 @@ const BaseQuestionDownloadPopover = ({result,dashboardId,dashcardId,- uuid,- token,visualizationSettings,variant,floating,formatPreference,}: BaseQuestionDownloadPopoverProps) => {+ const { uuid, token } = useEmbeddingEntityContext();const [isPopoverOpen, setIsPopoverOpen] = useState(false);const [, handleDownload] = useDownloadData({diff --git a/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx b/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsxindex 9fd5a2e6354..66c01da3e96 100644--- a/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx+++ b/frontend/src/metabase/query_builder/components/ResponsiveParametersList.tsx@@ -6,7 +6,6 @@ import Button from "metabase/common/components/Button";import useIsSmallScreen from "metabase/common/hooks/use-is-small-screen";import { Box, Flex } from "metabase/ui";import type { CardId, DashboardId, Parameter } from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import ResponsiveParametersListS from "./ResponsiveParametersList.module.css";import { SyncedParametersList } from "./SyncedParametersList";@@ -17,7 +16,6 @@ interface ResponsiveParametersListProps {parametersList?: string;};cardId?: CardId;- token?: EntityToken | null;dashboardId?: DashboardId;parameters: Parameter[];setParameterValue: (parameterId: string, value: string) => void;@@ -30,7 +28,6 @@ interface ResponsiveParametersListProps {export const ResponsiveParametersList = ({classNames,cardId,- token,dashboardId,parameters,setParameterValue,@@ -102,7 +99,6 @@ export const ResponsiveParametersList = ({)}cardId={cardId}dashboardId={dashboardId}- token={token}parameters={parameters}setParameterValue={setParameterValue}setParameterIndex={setParameterIndex}diff --git a/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx b/frontend/src/metabase/query_builder/components/SyncedParametersList.tsxindex b97a7159732..542cf90076b 100644--- a/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx+++ b/frontend/src/metabase/query_builder/components/SyncedParametersList.tsx@@ -15,7 +15,6 @@ export const SyncedParametersList = ({editingParameter,cardId,dashboardId,- token,className,hideParameters,@@ -47,7 +46,6 @@ export const SyncedParametersList = ({parameters={parameters}cardId={cardId}dashboardId={dashboardId}- token={token}editingParameter={editingParameter}isFullscreen={isFullscreen}isSortable={isSortable}diff --git a/frontend/src/metabase/redux/downloads.ts b/frontend/src/metabase/redux/downloads.tsindex 9e2ac041736..4dc2da125c8 100644--- a/frontend/src/metabase/redux/downloads.ts+++ b/frontend/src/metabase/redux/downloads.ts@@ -18,7 +18,7 @@ import type {Dataset,VisualizationSettings,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";import type { DownloadsState, State } from "metabase-types/store";import { trackDownloadResults } from "./downloads-analytics";@@ -31,7 +31,7 @@ export interface DownloadQueryResultsOpts {enablePivot?: boolean;dashboardId?: DashboardId;dashcardId?: DashCardId;- uuid?: string;+ uuid?: EntityUuid | null;token?: EntityToken | null;documentUuid?: string;documentId?: number;diff --git a/frontend/src/metabase/redux/metadata.js b/frontend/src/metabase/redux/metadata.jsindex b2a09dbd338..18d028132f3 100644--- a/frontend/src/metabase/redux/metadata.js+++ b/frontend/src/metabase/redux/metadata.js@@ -195,7 +195,7 @@ export const addRemappings = (fieldId, remappings) => {const FETCH_REMAPPING = "metabase/metadata/FETCH_REMAPPING";export const fetchRemapping = createThunkAction(FETCH_REMAPPING,- ({ parameter, value, field, cardId, dashboardId, token }) =>+ ({ parameter, value, field, cardId, dashboardId, uuid, token }) =>async (dispatch, getState) => {if (field == null ||@@ -205,10 +205,14 @@ export const fetchRemapping = createThunkAction(return;}+ const entityIdentifier = uuid ?? token ?? null;+if (dashboardId != null && parameter != null) {const remapping = await entityCompatibleQuery({- dashboard_id: token ?? dashboardId,+ ...(entityIdentifier+ ? { entityIdentifier }+ : { dashboard_id: dashboardId }),parameter_id: parameter.id,value,},@@ -222,7 +226,7 @@ export const fetchRemapping = createThunkAction(} else if (cardId != null && parameter != null) {const remapping = await entityCompatibleQuery({- card_id: token ?? cardId,+ ...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),parameter_id: parameter.id,value,},diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.jsindex c246c2ae1e8..3c8fcf4729d 100644--- a/frontend/src/metabase/services.js+++ b/frontend/src/metabase/services.js@@ -1,7 +1,4 @@-import _ from "underscore";-import api, { DELETE, GET, POST, PUT } from "metabase/lib/api";-import { PLUGIN_API, PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";import Question from "metabase-lib/v1/Question";import { normalizeParameters } from "metabase-lib/v1/parameters/utils/parameter-values";import { isNative } from "metabase-lib/v1/queries/utils/card";@@ -338,74 +335,6 @@ export const UtilApi = {},};-export function setPublicQuestionEndpoints(uuid) {- const encodedUuid = encodeURIComponent(uuid);- setCardEndpoints({ base: publicBase, encodedUuid });-}--export function setPublicDashboardEndpoints(uuid) {- const encodedUuid = encodeURIComponent(uuid);- setDashboardEndpoints({ base: publicBase, encodedUuid });-}--/**- * @param token {string}- */-export function setEmbedQuestionEndpoints(token) {- const encodedToken = encodeURIComponent(token);- setCardEndpoints({ base: getEmbedBase(), encodedToken });- PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(encodedToken);-}--/**- * @param token {string}- */-export function setEmbedDashboardEndpoints(token) {- const encodedToken = encodeURIComponent(token);- setDashboardEndpoints({ base: getEmbedBase(), encodedToken });- PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(encodedToken);-}--function GET_with(url, omitKeys) {- return (data, options) => GET(url)({ ..._.omit(data, omitKeys) }, options);-}--function setCardEndpoints({ base, encodedUuid, encodedToken }) {- const prefix = `${base}/card/${encodedUuid ?? encodedToken}`;-- // RTK query- PLUGIN_API.getRemappedCardParameterValueUrl = (_cardId, parameterId) =>- `${prefix}/params/${encodeURIComponent(parameterId)}/remapping`;-- // legacy API- CardApi.parameterValues = GET_with(`${prefix}/params/:paramId/values`, [- "cardId",- ]);- CardApi.parameterSearch = GET_with(- `${prefix}/params/:paramId/search/:query`,- ["cardId"],- );-}--function setDashboardEndpoints({ base, encodedUuid, encodedToken }) {- const prefix = `${base}/dashboard/${encodedUuid ?? encodedToken}`;-- // RTK query- PLUGIN_API.getRemappedDashboardParameterValueUrl = (- _dashboardId,- parameterId,- ) => `${prefix}/params/${encodeURIComponent(parameterId)}/remapping`;-- // legacy API- DashboardApi.parameterValues = GET_with(`${prefix}/params/:paramId/values`, [- "dashId",- ]);- DashboardApi.parameterSearch = GET_with(- `${prefix}/params/:paramId/search/:query`,- ["dashId"],- );-}-export const ActionsApi = {execute: POST("/api/action/:id/execute"),prefetchValues: GET("/api/action/:id/execute"),diff --git a/frontend/src/metabase/services.unit.spec.ts b/frontend/src/metabase/services.unit.spec.tsindex 3a4e4bae323..7b0bb589e48 100644--- a/frontend/src/metabase/services.unit.spec.ts+++ b/frontend/src/metabase/services.unit.spec.ts@@ -23,12 +23,7 @@ import {} from "metabase-types/api/mocks/presets";import { createMockState } from "metabase-types/store/mocks";-import * as getIsEmbedPreviewModule from "./get-is-embed-preview";-import {- DashboardApi,- runQuestionQuery,- setEmbedDashboardEndpoints,-} from "./services";+import { runQuestionQuery } from "./services";const MOCK_QUERY = createMockStructuredDatasetQuery({database: SAMPLE_DB_ID,@@ -206,52 +201,3 @@ describe("metabase/services > runQuestionQuery", () => {});});});--describe("DashboardApi parameter endpoints with IS_EMBED_PREVIEW", () => {- let isEmbedPreviewMock: jest.SpyInstance<boolean, []>;-- beforeEach(() => {- isEmbedPreviewMock = jest.spyOn(- getIsEmbedPreviewModule,- "getIsEmbedPreview",- );- });-- it("should use /api/embed prefix when IS_EMBED_PREVIEW is false", async () => {- isEmbedPreviewMock.mockReturnValue(false);-- setEmbedDashboardEndpoints("test-token");-- fetchMock.get(- "path:/api/embed/dashboard/test-token/params/param1/values",- {},- );-- await DashboardApi.parameterValues({ dashId: "123", paramId: "param1" });-- expect(- fetchMock.callHistory.called(- "path:/api/embed/dashboard/test-token/params/param1/values",- ),- ).toBe(true);- });-- it("should use /api/preview_embed prefix when IS_EMBED_PREVIEW is true", async () => {- isEmbedPreviewMock.mockReturnValue(true);-- setEmbedDashboardEndpoints("test-token");-- fetchMock.get(- "path:/api/preview_embed/dashboard/test-token/params/param1/values",- {},- );-- await DashboardApi.parameterValues({ dashId: "123", paramId: "param1" });-- expect(- fetchMock.callHistory.called(- "path:/api/preview_embed/dashboard/test-token/params/param1/values",- ),- ).toBe(true);- });-});diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsxindex f71554a33f3..d9a06cab3d4 100644--- a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx+++ b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx@@ -1,5 +1,6 @@import L from "leaflet";+import { EmbeddingEntityContext } from "metabase/embedding/context";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { GET } from "metabase/lib/api";import { isWithinIframe } from "metabase/lib/dom";@@ -9,6 +10,8 @@ import { getTileUrl } from "../lib/map";import LeafletMap from "./LeafletMap";export default class LeafletTilePinMap extends LeafletMap {+ static contextType = EmbeddingEntityContext;+componentDidMount() {super.componentDidMount();@@ -55,7 +58,9 @@ export default class LeafletTilePinMap extends LeafletMap {const latFieldParam = JSON.stringify(latitudeField.field_ref);const lonFieldParam = JSON.stringify(longitudeField.field_ref);- const { dashboard, dashcard, uuid, token } = this.props;+ const { dashboard, dashcard } = this.props;+ // EmbeddingEntityContext is only available under embedding environment+ const { uuid, token } = this.context ?? {};return getTileUrl({cardId: id,diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsxindex 3135d32e456..62de4346ceb 100644--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx@@ -77,7 +77,6 @@ import type {TimelineEvent,VisualizationSettings,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import type { Dispatch, State } from "metabase-types/store";import { EmptyVizState } from "../EmptyVizState";@@ -164,8 +163,6 @@ type VisualizationOwnProps = {style?: CSSProperties;timelineEvents?: TimelineEvent[];tc?: ContentTranslationFunction;- uuid?: string;- token?: EntityToken;zoomedRowIndex?: number;onOpenChartSettings?: (data: {initialChartSettings: { section: string };@@ -687,9 +684,7 @@ class Visualization extends PureComponent<style,tableHeaderHeight,timelineEvents,- token,totalNumGridCols,- uuid,width: rawWidth,onDeselectTimelineEvents,onOpenChartSettings,@@ -949,8 +944,6 @@ class Visualization extends PureComponent<totalNumGridCols={totalNumGridCols}visualizationIsClickable={this.visualizationIsClickable}width={rawWidth}- uuid={uuid}- token={token}zoomedRowIndex={zoomedRowIndex}onActionDismissal={this.hideActions}onChangeCardAndRun={diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.tsindex a9ae9736da6..aa89de5d1a9 100644--- a/frontend/src/metabase/visualizations/types/visualization.ts+++ b/frontend/src/metabase/visualizations/types/visualization.ts@@ -29,7 +29,6 @@ import type {TransformedSeries,VisualizationSettings,} from "metabase-types/api";-import type { EntityToken } from "metabase-types/api/entity";import type { VisualizationDisplay } from "metabase-types/api/visualization";import type { Dispatch, QueryBuilderMode } from "metabase-types/store";@@ -143,8 +142,6 @@ export interface VisualizationProps {timelineEvents?: TimelineEvent[];selectedTimelineEventIds?: TimelineEventId[];queryBuilderMode?: QueryBuilderMode;- uuid?: string;- token?: EntityToken;gridSize?: VisualizationGridSize;width: number;@@ -234,10 +231,6 @@ export type VisualizationPassThroughProps = {// frontend/src/metabase/visualizations/components/ChartSettings/ChartSettingsVisualization/ChartSettingsVisualization.tsxisSettings?: boolean;- // Public & Embedded questions, needed for pin maps to generate the correct tile URL- uuid?: string;- token?: EntityToken;-/*** Extra buttons to be shown in the table footer (if the visualization is a table)*/