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
Clean up API client options and remove XHR calls (#74368)
Romeo Van Snick5dc0b835b0c8
diff --git a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsxindex debf2c7e6b8..31f8c4a3130 100644--- a/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/requests.cy.spec.tsx@@ -91,14 +91,22 @@ describe("scenarios > embedding-sdk > requests", () => {cy.findByText("Product ID").should("be.visible");cy.wait("@jwtProvider");- // We ensure that both `dataset` requests are made after the token refresh request++ // Adding then removing the breakout triggers two queries while the token+ // is expired. They share a single token refresh (dedup); the earlier+ // query is superseded and dropped before dispatch, so only the latest+ // dataset request goes out — and it carries the refreshed session token.cy.get("@dataset.all", { timeout: 60_000 })- .should("have.length", 2)+ .should("have.length", 1).each((interception: any) => {expect(interception.request.headers["x-metabase-session"]).to.equal(sessionIds[1],);});++ // One `/auth/sso` at mount + one after expiry = 2 (deduped, not one+ // refresh per query).+ cy.get("@jwtToSession.all").should("have.length", 2);});});});diff --git a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.tsindex 9d0461ddc45..a38a3fa1753 100644--- a/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-studio-library.cy.spec.ts@@ -403,8 +403,17 @@ describe("scenarios > data studio > library", () => {H.DataStudio.Library.visit();cy.log("Verify Data empty state is visible initially");+ // `Library.visit()` only waits for the page container, not the library+ // tree fetch. The empty-state row renders once that resolves; under+ // fetch (microtask) timing the load can exceed the default assertion+ // timeout, so give this first post-visit assertion a longer one.H.DataStudio.Library.libraryPage()- .findByText("Cleaned, pre-transformed data sources ready for exploring")+ .findByText(+ "Cleaned, pre-transformed data sources ready for exploring",+ {+ timeout: 10000,+ },+ ).should("be.visible");cy.log("Publish a table via the +New menu");diff --git a/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js b/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.jsindex 325451b24ea..d8adb58d179 100644--- a/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-reproductions.cy.spec.js@@ -1441,10 +1441,19 @@ describe("issue 51934 (EMB-189)", () => {.should("have.length.at.least", 1).last();+ // Each click below swaps the picker view (or selects an item), which+ // remounts the popover. A single `latestPopover().within(...)` would pin+ // the popover element from its first command, so a later command in the+ // same block hits the now-detached node. Re-acquire `latestPopover()` for+ // every remounting action so Cypress re-queries onto the newest popover.cy.log("select a table as a data source");latestPopover().within(() => {cy.findByText("Raw Data").click();+ });+ latestPopover().within(() => {cy.findByRole("heading", { name: QA_DB_NAME }).click();+ });+ latestPopover().within(() => {cy.findByRole("option", { name: DATA_SOURCE_NAME }).click();});H.getNotebookStep("data").button("Join data").click();@@ -1465,6 +1474,8 @@ describe("issue 51934 (EMB-189)", () => {cy.log('go back to the "Bucket" step');latestPopover().within(() => {cy.icon("chevronleft").click();+ });+ latestPopover().within(() => {cy.icon("chevronleft").click();});@@ -1473,9 +1484,9 @@ describe("issue 51934 (EMB-189)", () => {);latestPopover().within(() => {cy.findByText("Saved Questions").click();- clickPickerItem(COLLECTION_NAME);- clickPickerItem(QUESTION_IN_COLLECTION_NAME);});+ latestPopover().within(() => clickPickerItem(COLLECTION_NAME));+ latestPopover().within(() => clickPickerItem(QUESTION_IN_COLLECTION_NAME));cy.log("the join popover is automatically opened");latestPopover().within(() => {@@ -1494,15 +1505,16 @@ describe("issue 51934 (EMB-189)", () => {);H.getNotebookStep("data").findByText(QUESTION_IN_COLLECTION_NAME).click();+ // Go back to the "Bucket" steplatestPopover().within(() => {- // Go back to the "Bucket" stepcy.findByText("Saved Questions").click();-- // We're now at the "Bucket" step+ });+ // We're now at the "Bucket" step+ latestPopover().within(() => {cy.findByText("Models").click();- clickPickerItem(COLLECTION_NAME);- clickPickerItem(MODEL_IN_COLLECTION_NAME);});+ latestPopover().within(() => clickPickerItem(COLLECTION_NAME));+ latestPopover().within(() => clickPickerItem(MODEL_IN_COLLECTION_NAME));cy.log("the join popover is automatically opened");latestPopover().within(() => {@@ -1520,10 +1532,8 @@ describe("issue 51934 (EMB-189)", () => {"select a data source after selecting a join step should refresh the data picker on the join step",);H.getNotebookStep("data").findByText(MODEL_IN_COLLECTION_NAME).click();- latestPopover().within(() => {- clickPickerItem("Our analytics");- clickPickerItem(MODEL_IN_ROOT_NAME);- });+ latestPopover().within(() => clickPickerItem("Our analytics"));+ latestPopover().within(() => clickPickerItem(MODEL_IN_ROOT_NAME));latestPopover().within(() => {cy.log("the collection of the new data source should be selected");diff --git a/e2e/test/scenarios/models/reproductions-1.cy.spec.ts b/e2e/test/scenarios/models/reproductions-1.cy.spec.tsindex 9c1ab56ff66..532032726d3 100644--- a/e2e/test/scenarios/models/reproductions-1.cy.spec.ts+++ b/e2e/test/scenarios/models/reproductions-1.cy.spec.ts@@ -837,6 +837,12 @@ describe("issue 33844", () => {function testModelMetadata(isNew: boolean) {cy.log("make a column visible only in detail views");+ // Wait for the metadata editor to finish loading before clicking the+ // header. Otherwise a late query/metadata load remounts the results+ // table and closes the column-settings sidebar we just opened, so the+ // "Detail views only" option never appears.+ H.waitForLoaderToBeRemoved();+ H.tableInteractive().findByText("ID").should("be.visible");cy.findAllByTestId("detail-shortcut").should("not.exist");H.tableHeaderClick("ID");cy.findByLabelText("Detail views only").click();diff --git a/e2e/test/scenarios/visualizations-charts/line-bar-tooltips.cy.spec.js b/e2e/test/scenarios/visualizations-charts/line-bar-tooltips.cy.spec.jsindex a4abca3931e..5bc487c20bf 100644--- a/e2e/test/scenarios/visualizations-charts/line-bar-tooltips.cy.spec.js+++ b/e2e/test/scenarios/visualizations-charts/line-bar-tooltips.cy.spec.js@@ -437,8 +437,12 @@ describe("scenarios > visualizations > line/bar chart > tooltips", () => {cy.button("Settings").click();updateColumnTitle(originalSeriesName, updatedOriginalSeriesName);updateColumnTitle(addedSeriesName, updatedAddedSeriesName);- cy.button("Save").click();});+ // Use the helper (instead of an inline Save click) so we wait for the+ // modal to close and the dashcard change to commit. Otherwise+ // `saveDashboard()` can run before the dashboard is marked dirty and no+ // PUT /api/dashboard/* request is ever made.+ H.saveDashcardVisualizerModalSettings();H.saveDashboard();showTooltipForCircleInSeries("#88BF4D");diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.tsindex 64b7df5c840..6bd4ab019b1 100644--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts@@ -28,7 +28,7 @@ import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";import { getWindow } from "embedding-sdk-shared/lib/get-window";import type { SdkAuthState } from "embedding-sdk-shared/types/auth-state";import { SDK_AUTH_STATE_KEY } from "embedding-sdk-shared/types/auth-state";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils";import {EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,diff --git a/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts b/enterprise/frontend/src/metabase-enterprise/api/content-translation.tsindex be38f044c1a..24dab992a34 100644--- a/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/content-translation.ts@@ -34,7 +34,6 @@ export const contentTranslationApi = EnterpriseApi.injectEndpoints({method: "POST",url: contentTranslationEndpoints.uploadDictionary,body: formData,- fetch: true,};},invalidatesTags: (_, error) =>diff --git a/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts b/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.tsindex 44837f52e70..eea5df97183 100644--- a/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts@@ -44,7 +44,6 @@ export const customVizPluginApi = EnterpriseApi.injectEndpoints({method: "POST",url: "/api/ee/custom-viz-plugin",body: formData,- fetch: true,};},invalidatesTags: (_, error) =>@@ -61,7 +60,6 @@ export const customVizPluginApi = EnterpriseApi.injectEndpoints({method: "PUT",url: `/api/ee/custom-viz-plugin/${id}/bundle`,body: formData,- fetch: true,};},invalidatesTags: (_, error, { id }) =>diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyDiagnosticsPage/DependencyDiagnosticsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyDiagnosticsPage/DependencyDiagnosticsPage.unit.spec.tsxindex 015f60730f0..97c8d6eb0a7 100644--- a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyDiagnosticsPage/DependencyDiagnosticsPage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyDiagnosticsPage/DependencyDiagnosticsPage.unit.spec.tsx@@ -123,8 +123,9 @@ describe("DependencyDiagnosticsPage", () => {it("renders provided nodes in the list", async () => {setup({ nodes: CARD_NODES });- expect(await screen.findByText("Question 1")).toBeInTheDocument();- expect(await screen.findByText("Question 2")).toBeInTheDocument();+ const list = await screen.findByRole("treegrid");+ expect(await within(list).findByText("Question 1")).toBeInTheDocument();+ expect(await within(list).findByText("Question 2")).toBeInTheDocument();});});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 e5e3d46e7b7..210d4b9c507 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@@ -16,7 +16,7 @@ import { useLazySelector } from "embedding-sdk-shared/hooks/use-lazy-selector";import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";import {EMBEDDING_SDK_CONFIG,@@ -29,13 +29,10 @@ const reactSdkEmbedReferrerHandler = async (config: OnBeforeRequestHandlerConfig,): Promise<OnBeforeRequestHandlerConfig | void> => ({...config,- options: {- ...config.options,- headers: {- ...config.options.headers,- // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name- "X-Metabase-Embed-Referrer": window.location.href,- },+ headers: {+ ...config.headers,+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ "X-Metabase-Embed-Referrer": window.location.href,},});diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex e1ac68c7f7c..4b7390c16b8 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -16,7 +16,7 @@ import type {SdkQuestionState,SqlParameterValues,} from "embedding-sdk-bundle/types/question";-import { isAbortError } from "metabase/api/legacy-client";+import { isAbortError } from "metabase/api/client";import { isStaticEmbeddingEntityLoadingError } from "metabase/utils/errors/is-static-embedding-entity-loading-error";import type Question from "metabase-lib/v1/Question";import type { ParameterValuesMap } from "metabase-types/api";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 2951d99851c..abdbb3725e1 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@@ -23,7 +23,11 @@ export const initGuestEmbed = createAsyncThunk<void, MetabaseAuthConfig>(getOrRefreshGuestSession(authConfig),).unwrap();- // The URL is templated (e.g. /api/embed/card/:entityIdentifier/params/:paramId/values or /api/embed/card/:token/query)+ // The URL is templated (e.g. /api/embed/card/:entityIdentifier/params/:paramId/values or /api/embed/card/:token/query).+ // `entityIdentifier` arrives as a URL param (in `data`); `token`+ // arrives in the request body for the saved-card query rewrite (and in+ // `data` for the legacy whole-bag callers). Refresh whichever channel+ // carries it before the URL `:tag` substitution reads it.if (newToken && "entityIdentifier" in config.data) {return merge(config, {data: {@@ -32,6 +36,14 @@ export const initGuestEmbed = createAsyncThunk<void, MetabaseAuthConfig>(});}+ if (newToken && config.body && "token" in config.body) {+ return merge(config, {+ body: {+ token: newToken,+ },+ });+ }+if (newToken && "token" in config.data) {return merge(config, {data: {diff --git a/frontend/src/metabase/admin/tools/components/Help/Help.tsx b/frontend/src/metabase/admin/tools/components/Help/Help.tsxindex 89b3ed58107..90e8f9b1913 100644--- a/frontend/src/metabase/admin/tools/components/Help/Help.tsx+++ b/frontend/src/metabase/admin/tools/components/Help/Help.tsx@@ -9,7 +9,7 @@ import {} from "metabase/admin/components/SettingsSection";import { UpsellBetterSupport } from "metabase/admin/upsells";import { useGetBugReportDetailsQuery } from "metabase/api/bug-report";-import legacyApi from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { CopyButton } from "metabase/common/components/CopyButton";import { ExternalLink } from "metabase/common/components/ExternalLink";import { useSetting } from "metabase/common/hooks";@@ -29,7 +29,7 @@ function navigatorInfo() {// to support Metabase deployments at a subpath.function getConnectionPoolDetailsUrl() {const path = "/api/bug-reporting/connection-pool-details";- return new URL(legacyApi.basename + path, location.origin).href;+ return new URL(api.basename + path, location.origin).href;}const template = `**Describe the bug**diff --git a/frontend/src/metabase/api/ai-streaming/requests.ts b/frontend/src/metabase/api/ai-streaming/requests.tsindex 2bed10e0bd0..6ca31b01245 100644--- a/frontend/src/metabase/api/ai-streaming/requests.ts+++ b/frontend/src/metabase/api/ai-streaming/requests.ts@@ -1,6 +1,6 @@import { nanoid } from "@reduxjs/toolkit";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import type { JSONValue } from "metabase-types/api";import { type AIStreamingConfig, processChatResponse } from "./process-stream";@@ -56,38 +56,26 @@ export async function aiStreamingQuery(abortController,});- // The basename is needed to work within the Embedding SDK- const response = await fetch(`${api.basename}${req.url}`, {+ const response = await api.fetch({method: "POST",- headers: {- ...api.getClientHeaders(),- Accept: "text/event-stream",- "Content-Type": "application/json",- },+ url: req.url,+ body: req.body,+ headers: { Accept: "text/event-stream" },signal: abortController.signal,- body: JSON.stringify(req.body),});if (!response.ok) {- let responseBody: unknown;+ // Mirror the legacy client's error shape (`{ status, data }`) so streaming+ // and non-streaming callers handle failures the same way. A non-JSON or+ // empty error body leaves `data` undefined; the status still identifies it.+ let data: unknown;try {- responseBody = await response.json();+ data = await response.json();} catch {// ignore json parse errors}- if (typeof responseBody === "string") {- throw { status: response.status, message: responseBody };- }-- if (responseBody && typeof responseBody === "object") {- throw {- status: response.status,- ...(responseBody as Record<string, unknown>),- };- }-- throw new Error(`Response status: ${response.status}`);+ throw { status: response.status, data };}if (!response.body) {diff --git a/frontend/src/metabase/api/ai-streaming/requests.unit.spec.ts b/frontend/src/metabase/api/ai-streaming/requests.unit.spec.tsindex 3bc91ad24e4..da9cea61267 100644--- a/frontend/src/metabase/api/ai-streaming/requests.unit.spec.ts+++ b/frontend/src/metabase/api/ai-streaming/requests.unit.spec.ts@@ -1,6 +1,6 @@import fetchMock from "fetch-mock";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import {aiStreamingQuery,@@ -31,9 +31,10 @@ describe("ai requests", () => {await aiStreamingQuery({ url: endpoint, body: {} });- expect(fetchSpy).toHaveBeenCalledWith(+ // The client wraps the args in a `Request`, so assert on its URL.+ const [request] = fetchSpy.mock.calls[0];+ expect((request as Request).url).toBe("http://example.com/some-streamed-endpoint",- expect.anything(),);fetchSpy.mockRestore();@@ -92,7 +93,7 @@ describe("ai requests", () => {fetchMock.post(`path:${endpoint}`, 500);await expect(aiStreamingQuery({ url: endpoint, body: {} }),- ).rejects.toThrow(/Response status: 500/);+ ).rejects.toMatchObject({ status: 500 });});it("preserves structured JSON error responses", async () => {@@ -108,8 +109,10 @@ describe("ai requests", () => {aiStreamingQuery({ url: endpoint, body: {} }),).rejects.toMatchObject({status: 402,- message: "You've used all of your included AI service tokens.",- "error-code": "metabase_ai_managed_locked",+ data: {+ message: "You've used all of your included AI service tokens.",+ "error-code": "metabase_ai_managed_locked",+ },});});diff --git a/frontend/src/metabase/api/ai-streaming/test-utils.ts b/frontend/src/metabase/api/ai-streaming/test-utils.tsindex c7182b87a95..f8c235d8c2a 100644--- a/frontend/src/metabase/api/ai-streaming/test-utils.ts+++ b/frontend/src/metabase/api/ai-streaming/test-utils.ts@@ -31,7 +31,7 @@ export function createMockReadableStream(export function mockEndpoint<T extends Response>(url: string,- endpointMock: (init?: RequestInit) => Promise<T>,+ endpointMock: (init?: RequestInit | Request) => Promise<T>,) {const originalFetch = global.fetch;const mockedFetch = jest.spyOn(global, "fetch");@@ -39,11 +39,21 @@ export function mockEndpoint<T extends Response>(// fetch-mock is supposed to work with ReadableStreams, but when passed one// the getReader methods ends up as undefinedreturn mockedFetch.mockImplementation((fetchedUrl, ...args) => {+ // The client calls `fetch(new Request(url, init))`, so the first arg may be+ // a Request (or URL) rather than a string.+ const requestUrl =+ fetchedUrl instanceof Request+ ? fetchedUrl.url+ : fetchedUrl instanceof URL+ ? fetchedUrl.href+ : fetchedUrl;const isRequestedUrl =- typeof fetchedUrl === "string" && fetchedUrl.includes(url);+ typeof requestUrl === "string" && requestUrl.includes(url);if (isRequestedUrl) {- return endpointMock(args?.[0]);+ return endpointMock(+ fetchedUrl instanceof Request ? fetchedUrl : args?.[0],+ );} else {// remove calls that route to global fetchmockedFetch.mock.calls.pop();@@ -105,7 +115,7 @@ export function mockStreamedEndpoint(};}- return { status: 202, ok: true, body } as any;+ return { status: 202, ok: true, body, headers: new Headers() } as any;});return Object.assign(mock, {diff --git a/frontend/src/metabase/api/api.ts b/frontend/src/metabase/api/api.tsindex ce8c01f0255..f79cc5b38f7 100644--- a/frontend/src/metabase/api/api.ts+++ b/frontend/src/metabase/api/api.ts@@ -1,3 +1,4 @@+import type { BaseQueryFn } from "@reduxjs/toolkit/query/react";import {buildCreateApi,coreModule,@@ -10,11 +11,32 @@ import {createStoreHook,} from "react-redux";+import { api } from "metabase/api/client";import { metabaseReduxContext } from "metabase/redux";-import { apiQuery } from "./query";import { TAG_TYPES } from "./tags";+// Adapts our legacy API client to RTK Query's `BaseQueryFn` contract: pull the+// abort signal off the query lifecycle context and turn the client's+// resolve/throw into RTK's `{ data } | { error }` shape. All request-shaping and+// validation lives in the client itself.+export const baseQuery: BaseQueryFn = async (args, ctx, extraOptions) => {+ const requestArgs = typeof args === "string" ? { url: args } : args;+ try {+ const method = requestArgs.method ?? "GET";+ const data = await api.request({+ method: "GET",+ ...requestArgs,+ retry: method === "GET" || method === "POST",+ signal: ctx.signal,+ ...extraOptions,+ });+ return { data };+ } catch (error) {+ return { error };+ }+};+const createApi = buildCreateApi(coreModule(),reactHooksModule({@@ -29,7 +51,7 @@ const createApi = buildCreateApi(export const Api = createApi({reducerPath: "metabase-api",tagTypes: TAG_TYPES,- baseQuery: apiQuery,+ baseQuery,endpoints: () => ({}),});diff --git a/frontend/src/metabase/api/api.unit.spec.ts b/frontend/src/metabase/api/api.unit.spec.tsnew file mode 100644index 00000000000..e359b111661--- /dev/null+++ b/frontend/src/metabase/api/api.unit.spec.ts@@ -0,0 +1,79 @@+import type { BaseQueryApi } from "@reduxjs/toolkit/query/react";++import { api } from "metabase/api/client";++import { baseQuery } from "./api";++describe("baseQuery (RTK Query adapter)", () => {+ const ctx = { signal: new AbortController().signal } as BaseQueryApi;++ afterEach(() => {+ jest.restoreAllMocks();+ });++ // GET/POST retried on transient 503s on the legacy client, and the baseQuery+ // must keep opting them in; PUT/DELETE never retried and must stay off.+ it.each([+ { method: "GET", retry: true },+ { method: "POST", retry: true },+ { method: "PUT", retry: false },+ { method: "DELETE", retry: false },+ ])("passes retry=$retry for $method", async ({ method, retry }) => {+ const requestSpy = jest.spyOn(api, "request").mockResolvedValue({});++ await baseQuery({ method, url: "/api/thing" }, ctx, {});++ expect(requestSpy).toHaveBeenCalledWith(+ expect.objectContaining({ method, retry }),+ );+ });++ it("defaults a bare-string arg to a retriable GET", async () => {+ const requestSpy = jest.spyOn(api, "request").mockResolvedValue({});++ await baseQuery("/api/thing", ctx, {});++ expect(requestSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ url: "/api/thing",+ method: "GET",+ retry: true,+ }),+ );+ });++ it("forwards the lifecycle abort signal to the client", async () => {+ const requestSpy = jest.spyOn(api, "request").mockResolvedValue({});++ await baseQuery({ method: "GET", url: "/api/thing" }, ctx, {});++ expect(requestSpy).toHaveBeenCalledWith(+ expect.objectContaining({ signal: ctx.signal }),+ );+ });++ it("returns the resolved value under `data`", async () => {+ jest.spyOn(api, "request").mockResolvedValue({ id: 1 });++ const result = await baseQuery(+ { method: "GET", url: "/api/thing" },+ ctx,+ {},+ );++ expect(result).toEqual({ data: { id: 1 } });+ });++ it("returns a thrown failure under `error`", async () => {+ const failure = { status: 500, data: "boom" };+ jest.spyOn(api, "request").mockRejectedValue(failure);++ const result = await baseQuery(+ { method: "GET", url: "/api/thing" },+ ctx,+ {},+ );++ expect(result).toEqual({ error: failure });+ });+});diff --git a/frontend/src/metabase/api/cache-config.ts b/frontend/src/metabase/api/cache-config.tsindex e9fdbef4977..10587f56a91 100644--- a/frontend/src/metabase/api/cache-config.ts+++ b/frontend/src/metabase/api/cache-config.ts@@ -37,9 +37,6 @@ export const cacheConfigApi = Api.injectEndpoints({url: "/api/cache",body,}),- extraOptions: {- hasBody: true,- },invalidatesTags: ["cache-config"],}),invalidateCacheConfigs: builder.mutation<@@ -56,9 +53,6 @@ export const cacheConfigApi = Api.injectEndpoints({url: "/api/cache/invalidate",params,}),- extraOptions: {- hasBody: false,- },}),}),});diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.tsindex 4ff34f578be..a8806c58072 100644--- a/frontend/src/metabase/api/card.ts+++ b/frontend/src/metabase/api/card.ts@@ -182,7 +182,6 @@ export const cardApi = Api.injectEndpoints({method: "POST",url: "/api/upload/csv",body: formData,- fetch: true,};},invalidatesTags: (_, error) =>diff --git a/frontend/src/metabase/api/client/client.ts b/frontend/src/metabase/api/client/client.tsnew file mode 100644index 00000000000..e20cb5edd14--- /dev/null+++ b/frontend/src/metabase/api/client/client.ts@@ -0,0 +1,406 @@+/* eslint-disable metabase/no-literal-metabase-strings */+import EventEmitter from "events";++import { isEmbeddingSdk } from "metabase/embedding-sdk/config";+import type {+ OnBeforeRequestHandler,+ OnBeforeRequestHandlerConfig,+} from "metabase/plugins/oss/api";+import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";+import { getTraceparentHeader } from "metabase/utils/otel";+import { retry } from "metabase/utils/retry";++import { addAntiCsrfToken, updateAntiCsrfToken } from "./csrf";+import { NetworkError, isRetriableError } from "./errors";+import { getLocaleHeader } from "./locale";+import { type RequestMethod, isRequestMethod } from "./method";+import { apiRequestManipulationMiddleware } from "./middleware";+import type {+ EventMap,+ RequestClientInfo,+ RequestInit,+ RequestOptions,+ ResponseFor,+} from "./types";+import {+ appendQueryParameters,+ handleResponse,+ relativeUrl,+ substituteUrlTags,+} from "./utils";++const MAX_RETRIES = 10;++export class ApiClient extends EventEmitter<EventMap> {+ basename = "";+ apiKey = "";+ sessionToken: string | undefined;+ requestClient: RequestClientInfo | undefined;++ beforeRequestHandlers: OnBeforeRequestHandler[] = [];++ private buildUrl(+ template: string,+ data: Record<string, unknown>,+ body?: Record<string, unknown>,+ ): URL {+ const relativePath = substituteUrlTags(template, data, body);+ return new URL(this.basename.concat(relativePath), location.origin);+ }++ private getClientHeaders(+ extraHeaders: Record<string, string> = {},+ ): Record<string, string> {+ const headers: Record<string, string> = {+ Accept: "application/json",+ "Content-Type": "application/json",+ };++ if (this.apiKey) {+ headers["X-Api-Key"] = this.apiKey;+ }++ if (this.sessionToken) {+ headers["X-Metabase-Session"] = this.sessionToken;+ }++ if (isWithinIframe() && !isEmbeddingSdk()) {+ headers["X-Metabase-Embedded"] = "true";+ }++ if (this.requestClient) {+ if (IFRAMED_IN_SELF) {+ headers["X-Metabase-Embedded-Preview"] = "true";+ }+ if (typeof this.requestClient === "object") {+ headers["X-Metabase-Client"] = this.requestClient.name;+ if (this.requestClient.version) {+ headers["X-Metabase-Client-Version"] = this.requestClient.version;+ }+ } else {+ headers["X-Metabase-Client"] = this.requestClient;+ }+ }++ const locale = getLocaleHeader();+ if (locale) {+ headers["X-Metabase-Locale"] = locale;+ }++ const traceparent = getTraceparentHeader();+ if (traceparent) {+ headers["traceparent"] = traceparent;+ }++ return {+ ...headers,+ ...extraHeaders,+ };+ }++ private async _resolveOptions(options: OnBeforeRequestHandlerConfig) {+ const middlewareResult = await apiRequestManipulationMiddleware(+ this.beforeRequestHandlers,+ {+ ...options,+ // `headers` is optional on the public API, but handlers may merge into+ // it, so always hand the pipeline a real object to spread into.+ headers: options.headers ?? {},+ // This will transform arrays to objects with numeric keys+ // we shouldn't be using top level-arrays in the API.+ // Both bags are defensively copied so middleware can safely mutate them.+ data: { ...options.data },+ body: options.body ? { ...options.body } : undefined,+ },+ );++ return {+ ...middlewareResult,+ url: this.buildUrl(+ middlewareResult.url,+ middlewareResult.data,+ middlewareResult.body,+ ),+ headers: this.getClientHeaders(middlewareResult.headers),+ };+ }++ private async _dispatch(+ init: RequestInit,+ withRetries: boolean = false,+ ): Promise<unknown> {+ if (!isRequestMethod(init.method)) {+ throw new Error("Invalid HTTP method");+ }++ try {+ if (withRetries) {+ return await retry(() => this._makeRequest(init), {+ maxRetries: MAX_RETRIES,+ shouldRetry: isRetriableError,+ signal: init.signal,+ });+ }+ return await this._makeRequest(init);+ } catch (error) {+ // When the request is aborted, `fetch` rejects with the standard+ // `DOMException` of name "AbortError". Let it propagate untouched so+ // callers can `isAbortError`-check the standard web shape instead of a+ // bespoke `{ isCancelled }` flag.+ if (init.signal?.aborted) {+ throw error;+ }+ // A genuine transport failure (server dropped the connection, DNS+ // lookup failed, offline) is the one case where `fetch` itself rejects,+ // and per the Fetch spec it always rejects with a `TypeError`. Wrap only+ // that so downstream renderers can `isNetworkError`-check and route it to+ // the connectivity error message. Any other `Error` here — notably a+ // `SyntaxError` from `response.json()` on an empty or malformed body — is+ // a response/parse problem, not a transport failure, so let it pass+ // through unwrapped instead of misclassifying it as a NetworkError.+ if (error instanceof TypeError) {+ throw new NetworkError(error.message);+ }+ throw error;+ }+ }++ /**+ * Run the request over the network: build an explicit `Request`, attach the+ * anti-CSRF token, `fetch`, and capture the anti-CSRF token from the response.+ * Returns the raw `Response` untouched — no body read, status check, or events.+ */+ private async _fetch({ url, ...init }: RequestInit): Promise<Response> {+ // We wrap the fetch args in an explicit `Request` (instead of just calling+ // `fetch(url, init)`) so fetch-mock populates `call.request` on every+ // recorded call. `findRequests()` in our Jest helpers reads `call.request`+ // to filter by method; without the Request object that field is undefined+ // and the helper returns nothing.+ const request = new Request(url, init);++ addAntiCsrfToken(request);++ const response = await fetch(request);++ updateAntiCsrfToken(response);++ return response;+ }++ private async _makeRequest<RawResponse extends boolean>(+ init: RequestInit<RawResponse>,+ ): Promise<ResponseFor<RawResponse>> {+ const response = await this._fetch(init);++ const { ok, status, body } = await handleResponse(+ response,+ init.rawResponse,+ );++ if (!init.noEvent && (status === 401 || status === 403)) {+ // Strip basename so listeners (app-main.js) see the relative path.+ const path = relativeUrl(this.basename, init.url);+ this.emit(status, path);+ }++ if (!ok) {+ const metabaseVersion = response.headers.get("X-Metabase-Version");+ this.emit("responseError", { metabaseVersion });+ throw { status, data: body };+ }++ return body as ResponseFor<RawResponse>;+ }++ /**+ * Resolve options through the middleware pipeline and assemble a `RequestInit`:+ * URL (basename + `:tag` substitution), client headers, and body placement.+ * Shared by `request` and `fetch`.+ *+ * Body/params semantics:+ * - `params`: URL `:tag` substitution first, leftover keys become querystring.+ * - `body`: sent as the request body. `FormData` / `URLSearchParams` are+ * forwarded as-is so the browser sets the right Content-Type. Anything+ * else is `JSON.stringify`'d. For `GET` it's folded into the querystring.+ * Body fields can also fill URL `:tag`s a handler introduces (the embed+ * `:token` rewrite), and any tag-consumed field drops out of the body.+ */+ private async _prepareRequest(+ options: {+ method: RequestMethod;+ url: string;+ body?: unknown;+ params?: Record<string, unknown>;+ } & RequestOptions,+ ): Promise<RequestInit> {+ if (Array.isArray(options.body)) {+ throw new Error("API bodies must be plain objects, not arrays");+ }++ const bodyIsRaw =+ options.body instanceof FormData ||+ options.body instanceof URLSearchParams;++ // Hand the middleware `params` and `body` as separate channels (`data` vs+ // `body`). URL-tag substitution pulls from either — so the embed override+ // fills `:token` from the body — and what's left stays sorted into its own+ // bag, so there's nothing to unweave afterwards. `FormData` /+ // `URLSearchParams` can't be inspected, so they skip the body channel and+ // attach as-is below.+ const {+ url,+ method,+ data,+ body: resolvedBody,+ headers,+ } = await this._resolveOptions({+ url: options.url,+ method: options.method,+ headers: options.headers,+ data: options.params ?? {},+ body: bodyIsRaw+ ? undefined+ : (options.body as Record<string, unknown> | undefined),+ });++ let body: BodyInit | undefined = undefined;++ // Leftover params (post URL-tag substitution) always go to the querystring.+ appendQueryParameters(url, data);++ if (method === "GET") {+ // GET cannot carry a body: fold the leftover body fields into the+ // querystring too.+ if (resolvedBody) {+ appendQueryParameters(url, resolvedBody);+ }+ } else if (bodyIsRaw) {+ body = options.body as BodyInit;++ // Let the browser set Content-Type with the multipart boundary+ // (FormData) or urlencoded charset (URLSearchParams).+ delete headers["Content-Type"];+ } else if (options.body !== undefined) {+ body = JSON.stringify(resolvedBody ?? {});+ }++ return { ...options, url, method, headers, body };+ }++ /**+ * RTK Query entry point with explicit body/params semantics. Reads and parses+ * the body, throwing `{ status, data }` on a non-2xx response. Pass+ * `rawResponse: true` to resolve with the raw `Response` instead. Pass+ * `retry: true` for the legacy retry-on-transient-failure behavior used by+ * the GET/POST helpers; RTK callers leave it off.+ */+ async request<Raw extends boolean = false>(+ options: {+ method: RequestMethod;+ url: string;+ body?: unknown;+ params?: Record<string, unknown>;+ retry?: boolean;+ } & RequestOptions<Raw>,+ ): Promise<ResponseFor<Raw>> {+ const init = await this._prepareRequest(options);+ return this._dispatch(init, options.retry ?? false) as ResponseFor<Raw>;+ }++ /**+ * Resolve with the raw `Response`, leaving everything after the network to the+ * caller: unlike `request`, it does not read the body, recover a 202 `_status`,+ * emit events, or throw on a non-2xx status. For streaming callers (e.g. SSE)+ * that consume `response.body` and do their own error handling, while still+ * getting the client pipeline — middleware, client headers, anti-CSRF, and+ * basename resolution — that a hand-rolled `fetch` would otherwise miss.+ */+ async fetch(+ options: {+ method: RequestMethod;+ url: string;+ body?: unknown;+ params?: Record<string, unknown>;+ } & RequestOptions,+ ): Promise<Response> {+ const init = await this._prepareRequest(options);+ return this._fetch(init);+ }++ /**+ * Builds a legacy `GET`/`POST`/`PUT`/`DELETE` helper bound to a URL template.+ * Legacy callers pack URL `:tag` values and body fields into a single+ * `rawData` bag, which flows through middleware as `data` — letting handlers+ * like the embed URL override substitute `:tag` tokens from fields that+ * morally live in the body. After URL-tag substitution the leftover bag+ * becomes the JSON body (POST/PUT) or the querystring (GET/DELETE).+ * FormData / URLSearchParams sidestep this and go through as-is.+ *+ * @deprecated Call `api.request(...)` directly with explicit `body`/`params`.+ * TODO: remove once `metabase/services` and the remaining legacy callers+ * (see `rg "from .metabase/api/legacy-client.""`) move to `api.request`.+ */+ private makeMethod(method: RequestMethod, retry: boolean) {+ const hasBody = method === "POST" || method === "PUT";+ return (urlTemplate: string, methodOptions: RequestOptions = {}) =>+ async <Raw extends boolean = false>(+ rawData: any = {},+ invocationOptions: RequestOptions<Raw> = {},+ ): Promise<Raw extends true ? Response : any> => {+ const options = { ...methodOptions, ...invocationOptions };+ const headers = {+ ...methodOptions.headers,+ ...invocationOptions.headers,+ };++ if (rawData instanceof FormData || rawData instanceof URLSearchParams) {+ const resolved = await this._resolveOptions({+ url: urlTemplate,+ method,+ headers,+ data: {},+ });+ // Let the browser set Content-Type with the multipart boundary+ // (FormData) or urlencoded charset (URLSearchParams).+ delete resolved.headers["Content-Type"];+ return this._dispatch(+ { ...options, ...resolved, body: rawData },+ retry,+ ) as any;+ }++ const resolved = await this._resolveOptions({+ url: urlTemplate,+ method,+ headers,+ data: rawData,+ });++ let body: BodyInit | undefined = undefined;+ if (hasBody && resolved.method !== "GET") {+ // Leftover bag → JSON body. Middleware saw the whole bag, so embed+ // URL `:token` etc. were already substituted from it.+ body = JSON.stringify(resolved.data);+ } else {+ // GET (including POST/PUT overridden to GET by middleware) and+ // DELETE: leftover bag goes to the querystring. `fetch` rejects+ // GET-with-body, so the override POST→GET embed case lands here too+ // — matching the old XHR path that silently dropped the body.+ appendQueryParameters(resolved.url, resolved.data);+ }++ return this._dispatch({ ...options, ...resolved, body }, retry) as any;+ };+ }++ /** @deprecated Use `api.request({ method: "GET", ... })` instead. */+ GET = this.makeMethod("GET", true);+ /** @deprecated Use `api.request({ method: "POST", ... })` instead. */+ POST = this.makeMethod("POST", true);+ /** @deprecated Use `api.request({ method: "PUT", ... })` instead. */+ PUT = this.makeMethod("PUT", false);+ /** @deprecated Use `api.request({ method: "DELETE", ... })` instead. */+ DELETE = this.makeMethod("DELETE", false);+}++export const api = new ApiClient();diff --git a/frontend/src/metabase/api/client/client.unit.spec.ts b/frontend/src/metabase/api/client/client.unit.spec.tsnew file mode 100644index 00000000000..cef4b6a61ae--- /dev/null+++ b/frontend/src/metabase/api/client/client.unit.spec.ts@@ -0,0 +1,483 @@+import fetchMock from "fetch-mock";++import { ApiClient } from "./client";++describe("api", () => {+ describe("request (RTK entry point)", () => {+ let apiInstance: ApiClient;++ beforeEach(() => {+ apiInstance = new ApiClient();+ });++ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ });++ it("`:tag*` substitutes a multi-segment value without URL-encoding the slashes", async () => {+ fetchMock.get("path:/api/automagic-dashboards/table/3/cell/4", {+ items: [],+ });++ await apiInstance.request({+ method: "GET",+ url: "/api/automagic-dashboards/:subPath*",+ params: { subPath: "table/3/cell/4" },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(+ /\/api\/automagic-dashboards\/table\/3\/cell\/4$/,+ );+ // sanity-check: slashes were NOT %2F-encoded+ expect(call?.url).not.toContain("%2F");+ });++ it("substitutes :tag URL placeholders from `params`", async () => {+ fetchMock.get("path:/api/card/123/params/abc-def/values", { values: [] });++ await apiInstance.request({+ method: "GET",+ url: "/api/card/:cardId/params/:paramId/values",+ params: { cardId: 123, paramId: "abc-def" },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(/\/api\/card\/123\/params\/abc-def\/values$/);+ });++ it("appends leftover (non-template) `params` as querystring", async () => {+ fetchMock.post("path:/api/cache/invalidate", { count: 0 });++ await apiInstance.request({+ method: "POST",+ url: "/api/cache/invalidate",+ params: { include: "overrides", database: 1 },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toContain("include=overrides");+ expect(call?.url).toContain("database=1");+ expect(call?.options?.body).toBeFalsy();+ });++ it("substitutes URL :tags and querystrings the leftover keys", async () => {+ fetchMock.get("path:/api/card/7/params/p/search/foo", { values: [] });++ await apiInstance.request({+ method: "GET",+ url: "/api/card/:cardId/params/:paramId/search/:query",+ params: {+ cardId: 7,+ paramId: "p",+ query: "foo",+ limit: 10,+ },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toContain("/api/card/7/params/p/search/foo");+ expect(call?.url).toContain("limit=10");+ });++ it("sends `body` as JSON for POST", async () => {+ fetchMock.post("path:/api/card/42/query", { rows: [] });++ await apiInstance.request({+ method: "POST",+ url: "/api/card/:cardId/query",+ params: { cardId: 42 },+ body: { parameters: ["a"], ignore_cache: true },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(/\/api\/card\/42\/query$/);+ expect(call?.options?.body).toBe(+ JSON.stringify({ parameters: ["a"], ignore_cache: true }),+ );+ });++ it("sends FormData bodies as-is and strips Content-Type", async () => {+ fetchMock.post("path:/api/table/9/append-csv", { success: true });++ const formData = new FormData();+ formData.append("file", new Blob(["a,b\n1,2"]), "x.csv");++ await apiInstance.request({+ method: "POST",+ url: "/api/table/:tableId/append-csv",+ params: { tableId: 9 },+ body: formData,+ });++ const call = fetchMock.callHistory.lastCall();+ // fetchMock serializes the body to string; presence/shape is sufficient.+ const sentHeaders = call?.options?.headers as+ | Record<string, string>+ | Headers+ | undefined;+ const contentType =+ sentHeaders instanceof Headers+ ? sentHeaders.get("Content-Type")+ : sentHeaders?.["Content-Type"];+ expect(contentType).toBeFalsy();+ });++ it("sends DELETE with a body", async () => {+ fetchMock.delete("path:/api/cache", {});++ await apiInstance.request({+ method: "DELETE",+ url: "/api/cache",+ body: { model: "question", model_id: [1, 2] },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.options?.body).toBe(+ JSON.stringify({ model: "question", model_id: [1, 2] }),+ );+ });++ it("folds body content into the querystring for GET", async () => {+ // Simulates the embed-override case (POST→GET transform): body content+ // must end up in the querystring since GET cannot carry a body.+ fetchMock.get("path:/api/card/5/query", { rows: [] });++ await apiInstance.request({+ method: "GET",+ url: "/api/card/:cardId/query",+ params: { cardId: 5 },+ body: { parameters: "[]" },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toContain("/api/card/5/query");+ expect(call?.url).toContain("parameters=");+ expect(call?.options?.body).toBeFalsy();+ });++ it("lets a middleware-overridden URL substitute :tag tokens from the body (guest-embed flow regression)", async () => {+ // Regression for the guest-embed card-query flow (run-query.ts): the+ // saved-card query is dispatched through RTK with `token` in the *body*.+ // The embed override middleware rewrites `/api/card/:cardId/query` to+ // `/api/embed/card/:token/query` (POST→GET), and `:token` must be filled+ // from the body field — not just from URL params.+ fetchMock.get("path:/api/embed/card/SOME_JWT/query", { rows: [] });++ apiInstance.beforeRequestHandlers.push(async (config) => {+ if (config.url === "/api/card/:cardId/query") {+ return {+ ...config,+ method: "GET" as const,+ url: "/api/embed/card/:token/query",+ };+ }+ return config;+ });++ await apiInstance.request({+ method: "POST",+ url: "/api/card/:cardId/query",+ params: { cardId: 42 },+ body: { token: "SOME_JWT", parameters: "[]" },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(/\/api\/embed\/card\/SOME_JWT\/query/);+ // The override changed the method to GET, so the leftover body field is+ // folded into the querystring (a GET request cannot carry a body).+ expect(call?.url).toContain("parameters=");+ expect(call?.options?.body).toBeFalsy();+ });++ it("omits params with undefined values from the querystring", async () => {+ fetchMock.get("path:/api/search", { items: [] });++ await apiInstance.request({+ method: "GET",+ url: "/api/search",+ params: { q: "foo", limit: undefined, offset: 0 },+ });++ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toContain("q=foo");+ expect(call?.url).toContain("offset=0");+ expect(call?.url).not.toContain("limit");+ });+ });++ describe("request cancellation", () => {+ let apiInstance: ApiClient;++ beforeEach(() => {+ apiInstance = new ApiClient();+ });++ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ });++ // An already-aborted signal makes the real `fetch` reject before the request+ // is dispatched, so a request the caller has already cancelled never reaches+ // the server and never resolves with data. We can't assert the "never+ // dispatched" part here (fetch-mock records the attempt before honoring the+ // abort), but the cancelled rejection is the contract callers depend on.+ it("rejects an already-aborted request as cancelled", async () => {+ fetchMock.get("path:/api/card/1/query", { rows: [] });++ const controller = new AbortController();+ controller.abort();++ await expect(+ apiInstance.request({+ method: "GET",+ url: "/api/card/:cardId/query",+ params: { cardId: 1 },+ signal: controller.signal,+ }),+ ).rejects.toMatchObject({ name: "AbortError" });+ });++ it("rejects with AbortError when the signal aborts while the request is in flight", async () => {+ const controller = new AbortController();+ fetchMock.get("path:/api/card/1/query", async () => {+ controller.abort();+ return { rows: [] };+ });++ await expect(+ apiInstance.request({+ method: "GET",+ url: "/api/card/:cardId/query",+ params: { cardId: 1 },+ signal: controller.signal,+ }),+ ).rejects.toMatchObject({ name: "AbortError" });+ });++ // The retry path surfaces the signal's AbortError when a backoff is cut+ // short via `signal.throwIfAborted()`, which the client lets propagate+ // unchanged — same standard web shape as a mid-fetch abort.+ it("rejects with AbortError when the signal aborts during a retry backoff", async () => {+ jest.useFakeTimers();+ try {+ fetchMock.get("path:/api/card/1/query", { status: 503, body: {} });++ const controller = new AbortController();+ const promise = apiInstance+ .request({+ method: "GET",+ url: "/api/card/:cardId/query",+ params: { cardId: 1 },+ signal: controller.signal,+ retry: true,+ })+ .catch((error: unknown) => error);++ // Let the first attempt fail with 503 and schedule the backoff.+ await jest.advanceTimersByTimeAsync(0);++ // Aborting mid-backoff ends the wait early; the loop stops without+ // another attempt and the 503 never surfaces.+ controller.abort();+ await jest.runAllTimersAsync();++ expect(await promise).toMatchObject({ name: "AbortError" });+ expect(fetchMock.callHistory.calls()).toHaveLength(1);+ } finally {+ jest.useRealTimers();+ }+ });+ });++ describe("status-code event emit", () => {+ let apiInstance: ApiClient;++ beforeEach(() => {+ apiInstance = new ApiClient();+ });++ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ });++ it("emits the relative path when basename is empty", async () => {+ fetchMock.get("path:/api/session/properties", { status: 401 });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({+ method: "GET",+ url: "/api/session/properties",+ })+ .catch(() => null);++ expect(listener).toHaveBeenCalledWith("/api/session/properties");+ });++ it("strips a subpath basename so listeners see the relative path", async () => {+ apiInstance.basename = "/metabase";+ fetchMock.get("path:/metabase/api/session", { status: 401 });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({ method: "GET", url: "/api/session" })+ .catch(() => null);++ expect(listener).toHaveBeenCalledWith("/api/session");+ });++ it("emits the relative path when basename is a full URL (SDK case)", async () => {+ apiInstance.basename = "https://metabase.example.com";+ fetchMock.get("https://metabase.example.com/api/session", {+ status: 401,+ });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({ method: "GET", url: "/api/session" })+ .catch(() => null);++ expect(listener).toHaveBeenCalledWith("/api/session");+ });++ it("strips the subpath when basename is a full URL with a subpath", async () => {+ apiInstance.basename = "http://localhost/mb";+ fetchMock.get("http://localhost/mb/api/session", { status: 401 });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({ method: "GET", url: "/api/session" })+ .catch(() => null);++ expect(listener).toHaveBeenCalledWith("/api/session");+ });++ it("includes the querystring in the emitted path", async () => {+ fetchMock.get("path:/api/search", { status: 401 });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({+ method: "GET",+ url: "/api/search",+ params: { q: "foo" },+ })+ .catch(() => null);++ expect(listener).toHaveBeenCalledWith("/api/search?q=foo");+ });++ it("does not emit when noEvent is set", async () => {+ fetchMock.get("path:/api/session/properties", { status: 401 });+ const listener = jest.fn();+ apiInstance.on(401, listener);++ await apiInstance+ .request({+ method: "GET",+ url: "/api/session/properties",+ noEvent: true,+ })+ .catch(() => null);++ expect(listener).not.toHaveBeenCalled();+ });+ });++ describe("response body parsing", () => {+ let apiInstance: ApiClient;++ beforeEach(() => {+ apiInstance = new ApiClient();+ });++ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ });++ it("parses a JSON-typed body", async () => {+ fetchMock.get("path:/api/thing", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ body: { id: 1 },+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).resolves.toEqual({ id: 1 });+ });++ // A successful response we're told is JSON but can't parse isn't really a+ // success — fail loud at the source rather than resolve with a silent null+ // that NPEs somewhere downstream.+ it("throws when a successful JSON-typed body cannot be parsed", async () => {+ fetchMock.get("path:/api/thing", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ body: "<html>not json</html>",+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).rejects.toThrow();+ });++ it("throws when a successful JSON-typed body is empty", async () => {+ fetchMock.get("path:/api/thing", {+ status: 200,+ headers: { "Content-Type": "application/json" },+ body: "",+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).rejects.toThrow();+ });++ // The regression this guards: an error response carrying a JSON content type+ // but an empty (or broken) body used to throw an opaque SyntaxError with no+ // `.status`, so downstream error handlers lost the HTTP status. It must+ // throw `{ status, data: null }` with the real status instead.+ it("throws the real status (not a SyntaxError) when an error body is empty but JSON-typed", async () => {+ fetchMock.get("path:/api/thing", {+ status: 500,+ headers: { "Content-Type": "application/json" },+ body: "",+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).rejects.toEqual({ status: 500, data: null });+ });++ it("throws the real status when an error body is malformed JSON", async () => {+ fetchMock.get("path:/api/thing", {+ status: 503,+ headers: { "Content-Type": "application/json" },+ body: "<html>gateway error</html>",+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).rejects.toEqual({ status: 503, data: null });+ });++ it("returns a non-JSON body as text", async () => {+ fetchMock.get("path:/api/thing", {+ status: 200,+ headers: { "Content-Type": "text/plain" },+ body: "plain text",+ });++ await expect(+ apiInstance.request({ method: "GET", url: "/api/thing" }),+ ).resolves.toBe("plain text");+ });+ });+});diff --git a/frontend/src/metabase/api/client/csrf.ts b/frontend/src/metabase/api/client/csrf.tsnew file mode 100644index 00000000000..4295870a924--- /dev/null+++ b/frontend/src/metabase/api/client/csrf.ts@@ -0,0 +1,18 @@+/* eslint-disable metabase/no-literal-metabase-strings */++const ANTI_CSRF_HEADER = "X-Metabase-Anti-CSRF-Token";++let ANTI_CSRF_TOKEN: string | null = null;++export function updateAntiCsrfToken(response: Response) {+ const token = response.headers.get(ANTI_CSRF_HEADER);+ if (token) {+ ANTI_CSRF_TOKEN = token;+ }+}++export function addAntiCsrfToken(request: Request) {+ if (ANTI_CSRF_TOKEN) {+ request.headers.set(ANTI_CSRF_HEADER, ANTI_CSRF_TOKEN);+ }+}diff --git a/frontend/src/metabase/api/client/errors.ts b/frontend/src/metabase/api/client/errors.tsnew file mode 100644index 00000000000..5cafc1aac2c--- /dev/null+++ b/frontend/src/metabase/api/client/errors.ts@@ -0,0 +1,45 @@+/**+ * Thrown when the transport itself fails before a response is received —+ * e.g. the server dropped the connection, DNS lookup failed, or the user is+ * offline. Callers `isNetworkError`-check to render a connectivity error+ * message instead of treating it as a generic failure.+ */+export class NetworkError extends Error {+ constructor(message = "Network error") {+ super(message);+ this.name = "NetworkError";+ }+}++export function isNetworkError(error: unknown): error is NetworkError {+ return error instanceof NetworkError;+}++/**+ * `true` for the standard `DOMException` of name `"AbortError"` that+ * `fetch()` rejects with when its signal aborts. Use this in place of the+ * legacy `error.isCancelled` flag.+ */+export function isAbortError(error: unknown): boolean {+ return (+ typeof error === "object" &&+ error !== null &&+ (error as { name?: unknown }).name === "AbortError"+ );+}++export function getErrorStatus(error: unknown): number | undefined {+ if (+ typeof error === "object" &&+ error !== null &&+ "status" in error &&+ typeof error.status === "number"+ ) {+ return error.status;+ }+ return undefined;+}++export function isRetriableError(error: unknown): boolean {+ return getErrorStatus(error) === 503;+}diff --git a/frontend/src/metabase/api/client/index.ts b/frontend/src/metabase/api/client/index.tsnew file mode 100644index 00000000000..cb3d022fa03--- /dev/null+++ b/frontend/src/metabase/api/client/index.ts@@ -0,0 +1,5 @@+export * from "./client";+export * from "./method";+export * from "./errors";+export type { RequestOptions } from "./types";+export { setLocaleHeader } from "./locale";diff --git a/frontend/src/metabase/api/client/locale.ts b/frontend/src/metabase/api/client/locale.tsnew file mode 100644index 00000000000..c0ef13e465a--- /dev/null+++ b/frontend/src/metabase/api/client/locale.ts@@ -0,0 +1,13 @@+let LOCALE: string | null = null;++export function getLocaleHeader(): string | null {+ return 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.+ */+ LOCALE = locale ?? null;+};diff --git a/frontend/src/metabase/api/client/method.ts b/frontend/src/metabase/api/client/method.tsnew file mode 100644index 00000000000..fc17d10b7fe--- /dev/null+++ b/frontend/src/metabase/api/client/method.ts@@ -0,0 +1,11 @@+export type RequestMethod = "GET" | "POST" | "PUT" | "DELETE";++const REQUEST_METHODS = new Set<RequestMethod>([+ "GET",+ "POST",+ "PUT",+ "DELETE",+]);++export const isRequestMethod = (method: unknown): method is RequestMethod =>+ REQUEST_METHODS.has(method as RequestMethod);diff --git a/frontend/src/metabase/api/client/middleware.ts b/frontend/src/metabase/api/client/middleware.tsnew file mode 100644index 00000000000..fa65a8da1b1--- /dev/null+++ b/frontend/src/metabase/api/client/middleware.ts@@ -0,0 +1,66 @@+import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";+import type {+ OnBeforeRequestHandler,+ OnBeforeRequestHandlerConfig,+} from "metabase/plugins/oss/api";++export async function apiRequestManipulationMiddleware(+ beforeRequestHandlers: OnBeforeRequestHandler[],+ requestConfig: OnBeforeRequestHandlerConfig,+): Promise<OnBeforeRequestHandlerConfig> {+ // Handlers order is important.+ // Handlers are executed in order and each handler uses the data returned by a previous handler.+ const handlers = [+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler,+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers+ .getOrRefreshGuestSessionHandler,+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds,+ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds,+ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForStaticEmbeds,+ ...beforeRequestHandlers,+ ];++ let result = requestConfig;+ for (const handler of handlers) {+ const next = await handler(result);+ if (next) {+ result = merge(result, next);+ }+ }++ return result;+}++function merge(+ prev: OnBeforeRequestHandlerConfig,+ next: Partial<OnBeforeRequestHandlerConfig>,+) {+ const result = { ...prev };++ if (next?.method) {+ result.method = next.method;+ }+ if (next?.url) {+ result.url = next.url;+ }+ if (next?.headers) {+ result.headers = {+ ...(result.headers ?? {}),+ ...next.headers,+ };+ }+ if (next?.data) {+ result.data = {+ ...result.data,+ ...next.data,+ };+ }+ if (next?.body) {+ result.body = {+ ...(result.body ?? {}),+ ...next.body,+ };+ }++ return result;+}diff --git a/frontend/src/metabase/api/client/middleware.unit.spec.ts b/frontend/src/metabase/api/client/middleware.unit.spec.tsnew file mode 100644index 00000000000..e20a57b434d--- /dev/null+++ b/frontend/src/metabase/api/client/middleware.unit.spec.ts@@ -0,0 +1,190 @@+import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";++import { apiRequestManipulationMiddleware } from "./middleware";++describe("apiRequestManipulationMiddleware", () => {+ it("should return the original data when there are no handlers", async () => {+ const inputData = {+ method: "GET" as const,+ url: "/api/test",+ headers: {},+ data: {},+ };++ const result = await apiRequestManipulationMiddleware([], inputData);+ expect(result).toEqual(inputData);+ });++ it("should return the original data when handler returns void", async () => {+ const inputData = {+ method: "POST" as const,+ url: "/api/test",+ headers: { "X-Test": "value" },+ data: {},+ };++ // Mock a handler that returns void+ const handler = jest.fn(async function () {+ return;+ });++ const result = await apiRequestManipulationMiddleware([handler], inputData);++ expect(result).toEqual(inputData);+ expect(handler).toHaveBeenCalledWith(inputData);+ });++ it("should update only the url when handler returns partial modification", async () => {+ const inputData = {+ method: "GET" as const,+ url: "/api/original",+ headers: {},+ data: {},+ };++ const expectedUrl = "/api/modified";++ const handler = jest.fn(async function () {+ // Simulate handler that only modifies URL+ return {+ url: expectedUrl,+ };+ });++ const result = await apiRequestManipulationMiddleware([handler], inputData);++ expect(result).toEqual({+ ...inputData,+ url: expectedUrl,+ });+ });++ it("should update method, url, and headers when handler returns full modification", async () => {+ const inputData = {+ method: "GET" as const,+ url: "/api/original",+ headers: {},+ data: {},+ };++ const modifications = {+ method: "POST" as const,+ url: "/api/modified",+ headers: { "X-Custom": "value" },+ };++ const handler = jest.fn(async function () {+ return modifications;+ });++ const result = await apiRequestManipulationMiddleware([handler], inputData);++ expect(result).toEqual({ ...inputData, ...modifications });+ });++ it("should merge headers properly when handler returns partial headers", async () => {+ const inputData = {+ method: "POST" as const,+ url: "/api/test",+ headers: { "X-Original": "value" },+ data: {},+ };++ const newHeaders = { "X-Modified": "new-value" };++ const handler = jest.fn(async function (+ data: OnBeforeRequestHandlerConfig,+ ) {+ return {+ headers: {+ ...data.headers,+ ...newHeaders,+ },+ };+ });++ const result = await apiRequestManipulationMiddleware([handler], inputData);++ expect(result.headers).toEqual({+ "X-Original": "value",+ "X-Modified": "new-value",+ });+ });++ it("should execute multiple handlers in order", async () => {+ const inputData = {+ method: "GET" as const,+ url: "/api/start",+ headers: {},+ data: { value: 0 },+ };++ const executionOrder: number[] = [];++ const handler1 = jest.fn(async (data: OnBeforeRequestHandlerConfig) => {+ executionOrder.push(1);+ return {+ ...data,+ url: data.url + "/step1",+ data: { ...data.data, value: (data.data.value as number) + 2 },+ };+ });++ const handler2 = jest.fn(async (data: OnBeforeRequestHandlerConfig) => {+ executionOrder.push(2);+ return {+ ...data,+ url: data.url + "/step2",+ data: { ...data.data, value: (data.data.value as number) * 10 },+ };+ });++ const handler3 = jest.fn(async (data: OnBeforeRequestHandlerConfig) => {+ executionOrder.push(3);+ return {+ ...data,+ url: data.url + "/step3",+ data: { ...data.data, value: (data.data.value as number) - 4 },+ };+ });++ const result = await apiRequestManipulationMiddleware(+ [handler1, handler2, handler3],+ inputData,+ );++ expect(executionOrder).toEqual([1, 2, 3]);+ expect(result.url).toBe("/api/start/step1/step2/step3");+ expect(result.data.value).toBe(16); // = ((0 + 2) * 10) - 4+ expect(handler1).toHaveBeenCalledWith(+ expect.objectContaining({ url: "/api/start" }),+ );+ expect(handler2).toHaveBeenCalledWith(+ expect.objectContaining({ url: "/api/start/step1" }),+ );+ expect(handler3).toHaveBeenCalledWith(+ expect.objectContaining({ url: "/api/start/step1/step2" }),+ );+ });++ it("should preserve the original headers and data when handler does not modify them", async () => {+ const inputData = {+ method: "POST" as const,+ url: "/api/complex",+ headers: { "X-Custom": "header" },+ data: { keepMe: true },+ };++ const handler = jest.fn(async function () {+ return {+ url: "/api/modified-url",+ };+ });++ const result = await apiRequestManipulationMiddleware([handler], inputData);++ expect(result.url).toBe("/api/modified-url");+ expect(result.headers).toEqual(inputData.headers);+ expect(result.data).toEqual(inputData.data);+ });+});diff --git a/frontend/src/metabase/api/client/types.ts b/frontend/src/metabase/api/client/types.tsnew file mode 100644index 00000000000..6514dd8d0b9--- /dev/null+++ b/frontend/src/metabase/api/client/types.ts@@ -0,0 +1,42 @@+import type { RequestMethod } from "./method";++export type RequestOptions<RawResponse extends boolean = boolean> = {+ noEvent?: boolean;+ headers?: Record<string, string>;+ signal?: AbortSignal;+ /**+ * When `true`, resolve with the raw `Response` instead of the parsed body —+ * for callers that read it themselves (binary downloads, map tiles as a blob).+ * Passing a literal `true` narrows the resolved type to `Response`.+ */+ rawResponse?: RawResponse;+};++/**+ * What a request resolves with: the raw `Response` when `rawResponse` is `true`,+ * otherwise the parsed body typed as `T`.+ */+export type ResponseFor<Raw extends boolean> = Raw extends true+ ? Response+ : unknown;++export type RequestClientInfo =+ | string+ | { name: string; version: string | null };++export type ResponseErrorInfo = {+ metabaseVersion: string | null;+};++export type EventMap = {+ 401: [string];+ 403: [string];+ responseError: [ResponseErrorInfo];+};++export type RequestInit<RawResponse extends boolean = boolean> = {+ method: RequestMethod;+ url: URL;+ body?: BodyInit;+ headers?: Record<string, string>;+} & RequestOptions<RawResponse>;diff --git a/frontend/src/metabase/api/client/utils.ts b/frontend/src/metabase/api/client/utils.tsnew file mode 100644index 00000000000..0cc19a784be--- /dev/null+++ b/frontend/src/metabase/api/client/utils.ts@@ -0,0 +1,225 @@+type ResponseResult = {+ ok: boolean;+ status: number;+ body: unknown;+};++// Basename can be a path prefix ("/metabase") or a full URL with an optional+// subpath ("http://localhost/mb"). The status-code emit needs the path portion+// only, listeners expect "/api/..." regardless of how the host is wired.+export function getBasenamePath(basename: string): string {+ if (!basename) {+ return "";+ }+ try {+ const url = new URL(basename);+ return trimSuffix(url.pathname, "/");+ } catch {+ // not a full url, assume it's a path prefix+ return trimSuffix(basename, "/");+ }+}++export function relativeUrl(basename: string, url: URL): string {+ const basenamePath = getBasenamePath(basename);+ const relativePath = removePrefix(url.pathname, basenamePath);+ return relativePath + url.search;+}++function removePrefix(str: string, prefix: string): string {+ return str.startsWith(prefix) ? str.slice(prefix.length) : str;+}++function trimSuffix(str: string, suffix: string): string {+ return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;+}++export function appendQueryParameters(+ url: URL,+ params: Record<string, unknown>,+) {+ for (const key in params) {+ const value = params[key];+ if (value === undefined) {+ continue;+ }+ if (Array.isArray(value)) {+ for (const item of value) {+ url.searchParams.append(key, String(item));+ }+ } else {+ url.searchParams.append(key, String(value));+ }+ }+}++function isJson(response: Response): boolean {+ return (+ response.headers.get("Content-Type")?.includes("application/json") ?? false+ );+}++function isOk(status: number): boolean {+ return 200 <= status && status <= 299;+}++/**+ * Parse a JSON body stream natively — `response.json()` never materializes the+ * payload as a JS string the way `text()` + `JSON.parse` would. A body that+ * can't be parsed (empty, truncated, or mislabeled `application/json`) resolves+ * to `null` rather than throwing, so it can never mask the response's status+ * with an opaque, status-less `SyntaxError`.+ */+async function parseJsonOrNull(response: Response): Promise<unknown> {+ try {+ return await response.json();+ } catch {+ return null;+ }+}++/**+ * Interpret a fetched `Response` into a `{ ok, status, body }` result, without+ * emitting or throwing — the caller decides what to do with a non-ok status.+ *+ * The body is only read when it'll actually be used — as the result of a normal+ * request, as error data, or to recover the real status of a 202 streaming+ * response (whose status hides in a `{_status}` body). A `rawResponse` caller+ * whose non-202 request succeeded gets the `Response` itself as `body`, unread,+ * so a binary payload like a map tile is never decoded as text.+ */+export async function handleResponse(+ response: Response,+ rawResponse?: boolean,+): Promise<ResponseResult> {+ // Hand back the raw Response only when the caller asked for it and the request+ // succeeded. A failure falls through below so its body can be read as error+ // data; a 202 counts as ok here and is sorted out next.+ if (rawResponse && response.ok) {+ if (response.status === 202) {+ // A 202's HTTP status can't be trusted (a streamed export commits it+ // before the work can fail), so read the body to learn the real status.+ // The caller still needs an unread Response, so clone before reading.+ const unreadResponse = response.clone();+ const info = await readBody(response);+ if (!info.ok) {+ return info;+ }+ return { ...info, body: unreadResponse };+ }++ // A non-202 status is authoritative, so skip reading the body entirely and+ // return the untouched Response — this is what keeps a binary payload like a+ // map tile from being decoded as text.+ return { ok: true, status: response.status, body: response };+ }++ // Either the caller doesn't want the raw Response (the parsed body IS the+ // result) or the request failed (the body is the error payload). Read it and+ // let the caller inspect `ok`.+ return await readBody(response);+}++/**+ * A streamed 202 signals its real status in a `{_status: N}` body.+ */+function streamedStatus(body: unknown): number | undefined {+ if (+ body &&+ typeof body === "object" &&+ "_status" in body &&+ typeof body._status === "number" &&+ body._status > 0+ ) {+ return body._status;+ }+ return undefined;+}++/**+ * Read the body by its `Content-Type`: JSON natively (never materializing an+ * intermediate string), otherwise text. A successful JSON body must be+ * parseable, so a parse failure throws; on a failed response the body is error+ * data, so an empty or garbage body is swallowed to `null` rather than masking+ * the status with a `SyntaxError`.+ */+async function readResponseBody(+ response: Response,+ ok: boolean,+): Promise<unknown> {+ if (!isJson(response)) {+ return response.text();+ }+ return ok ? response.json() : parseJsonOrNull(response);+}++/**+ * Read and interpret a response into `{ ok, status, body }`, routed by status:+ *+ * - 202: a streamed query/download commits the 202 before its work can fail, so+ * read the body to recover the real status from a `{_status}` payload. The+ * read stays tolerant — a non-`_status` body (even a non-JSON export) is a+ * success streamed straight through.+ * TODO: a JSON error emitted mid-stream parses to a non-`_status` object and+ * is silently treated as success.+ * - 204: no content.+ * - otherwise: the status line is authoritative; see `readResponseBody`.+ *+ * Does not throw on a non-2xx status — the caller inspects `ok`.+ */+async function readBody(response: Response): Promise<ResponseResult> {+ if (response.status === 202) {+ const body = await parseJsonOrNull(response);+ const status = streamedStatus(body) ?? 202;+ return { ok: isOk(status), status, body };+ }++ if (response.status === 204) {+ return { ok: true, status: 204, body: null };+ }++ const { status, ok } = response;+ const body = await readResponseBody(response, ok);+ return { ok, status, body };+}++// URL template tags:+// - `:tag` — value is URL-encoded (default; slashes become %2F).+// - `:tag*` — value is substituted raw (slashes preserved), for endpoints+// whose route includes a multi-segment path parameter.+const URL_TAG_REGEX = /:\w+\*?/g;++/**+ * Replace `:tag` / `:tag*` placeholders in a URL template with values pulled+ * from `data` (params) first, then falling back to `body` fields — this is how+ * an embed `:token` gets filled from the request body. The key is consumed from+ * whichever bag held it, so the caller can use any leftovers as querystring+ * params (from `data`) or as the JSON body (from `body`).+ */+export function substituteUrlTags(+ url: string,+ data: Record<string, unknown>,+ body?: Record<string, unknown>,+): string {+ return url.replace(URL_TAG_REGEX, (tag) => {+ const isRaw = tag.endsWith("*");+ const paramName = tag.slice(1, isRaw ? -1 : undefined);+ let value: unknown;+ for (const bag of [data, body]) {+ if (bag && paramName in bag) {+ value = bag[paramName];+ delete bag[paramName];+ // A key present in `data` but explicitly `undefined` still falls+ // through to `body` (e.g. an absent param, real token in the body).+ if (value !== undefined) {+ break;+ }+ }+ }+ if (value === undefined) {+ console.warn("Warning: calling", url, "without", tag);+ return "";+ }+ return isRaw ? String(value) : encodeURIComponent(String(value));+ });+}diff --git a/frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.ts b/frontend/src/metabase/api/client/utils.unit.spec.tssimilarity index 56%rename from frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.tsrename to frontend/src/metabase/api/client/utils.unit.spec.tsindex 3f07e2e5f33..d81ffee770a 100644--- a/frontend/src/metabase/api/utils/substitute-url-tags.unit.spec.ts+++ b/frontend/src/metabase/api/client/utils.unit.spec.ts@@ -1,16 +1,16 @@-import { substituteUrlTags } from "./substitute-url-tags";+import { substituteUrlTags } from "./utils";describe("substituteUrlTags", () => {it("returns the URL unchanged when no tags are present", () => {const data = { extra: 1 };- const url = substituteUrlTags("/api/foo", data, "GET");+ const url = substituteUrlTags("/api/foo", data);expect(url).toBe("/api/foo");expect(data).toEqual({ extra: 1 });});it("substitutes a single :tag and consumes it from data", () => {const data = { id: 42, leftover: "x" };- const url = substituteUrlTags("/api/foo/:id", data, "GET");+ const url = substituteUrlTags("/api/foo/:id", data);expect(url).toBe("/api/foo/42");expect(data).toEqual({ leftover: "x" });});@@ -20,7 +20,6 @@ describe("substituteUrlTags", () => {const url = substituteUrlTags("/api/dashboard/:dashId/params/:paramId/values",data,- "GET",);expect(url).toBe("/api/dashboard/1/params/p/values");expect(data).toEqual({});@@ -28,35 +27,31 @@ describe("substituteUrlTags", () => {it("URL-encodes :tag values by default", () => {const data = { id: "a/b c" };- const url = substituteUrlTags("/api/foo/:id", data, "GET");+ const url = substituteUrlTags("/api/foo/:id", data);expect(url).toBe("/api/foo/a%2Fb%20c");});it("substitutes :tag* values raw (preserves slashes)", () => {const data = { subPath: "table/3/cell/4" };- const url = substituteUrlTags(- "/api/automagic-dashboards/:subPath*",- data,- "GET",- );+ const url = substituteUrlTags("/api/automagic-dashboards/:subPath*", data);expect(url).toBe("/api/automagic-dashboards/table/3/cell/4");expect(data).toEqual({});});it("mixes :tag (encoded) and :tag* (raw) in the same URL", () => {const data = { id: "x/y", path: "a/b/c" };- const url = substituteUrlTags("/api/:id/sub/:path*", data, "GET");+ const url = substituteUrlTags("/api/:id/sub/:path*", data);expect(url).toBe("/api/x%2Fy/sub/a/b/c");});it("substitutes empty string and warns when a tag has no value in data", () => {const warn = jest.spyOn(console, "warn").mockImplementation(() => {});const data = {};- const url = substituteUrlTags("/api/foo/:missing", data, "POST");+ const url = substituteUrlTags("/api/foo/:missing", data);expect(url).toBe("/api/foo/");expect(warn).toHaveBeenCalledWith("Warning: calling",- "POST",+ "/api/foo/:missing","without",":missing",);@@ -65,7 +60,27 @@ describe("substituteUrlTags", () => {it("coerces non-string values to strings before encoding", () => {const data = { id: 7, flag: true };- const url = substituteUrlTags("/api/:id/:flag", data, "GET");+ const url = substituteUrlTags("/api/:id/:flag", data);expect(url).toBe("/api/7/true");});++ it("falls back to a body field when the tag is absent from data (embed :token)", () => {+ const data = {};+ const body = { token: "THE_JWT", parameters: "[]" };+ const url = substituteUrlTags("/api/embed/card/:token/query", data, body);+ expect(url).toBe("/api/embed/card/THE_JWT/query");+ // consumed from the body, leaving the other body field intact+ expect(body).toEqual({ parameters: "[]" });+ expect(data).toEqual({});+ });++ it("prefers a data value over a body value for the same tag", () => {+ const data = { id: "from-data" };+ const body = { id: "from-body" };+ const url = substituteUrlTags("/api/foo/:id", data, body);+ expect(url).toBe("/api/foo/from-data");+ expect(data).toEqual({});+ // the body value is left untouched since data satisfied the tag+ expect(body).toEqual({ id: "from-body" });+ });});diff --git a/frontend/src/metabase/api/dataset.ts b/frontend/src/metabase/api/dataset.tsindex 2c003097b03..b33a899379b 100644--- a/frontend/src/metabase/api/dataset.ts+++ b/frontend/src/metabase/api/dataset.ts@@ -70,10 +70,6 @@ export const datasetApi = Api.injectEndpoints({url: "/api/dataset",body,noEvent: ignore_error,- // Use fetch so RTK Query's AbortSignal actually cancels the- // request. The XHR path only honors a `cancelled` promise, which- // we can't thread through `endpoint.initiate(...).abort()`.- fetch: true,}),providesTags: () => provideAdhocDatasetTags(),// Dataset results can be large and the cache key is the full@@ -97,7 +93,6 @@ export const datasetApi = Api.injectEndpoints({url: "/api/dataset/pivot",body,noEvent: ignore_error,- fetch: true,}),providesTags: () => provideAdhocDatasetTags(),keepUnusedDataFor: 0,diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.tsindex dac2250e360..d0d59fb0e15 100644--- a/frontend/src/metabase/api/legacy-client.ts+++ b/frontend/src/metabase/api/legacy-client.ts@@ -1,641 +1,11 @@-/* eslint-disable metabase/no-literal-metabase-strings */-import EventEmitter from "events";-import querystring from "querystring";--import { substituteUrlTags } from "metabase/api/utils/substitute-url-tags";-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";-import { isTest } from "metabase/env";-import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";-import type {- OnBeforeRequestHandler,- 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";--const ONE_SECOND = 1000;-const MAX_RETRIES = 10;--const ANTI_CSRF_HEADER = "X-Metabase-Anti-CSRF-Token";-const METABASE_VERSION_HEADER = "X-Metabase-Version";--let ANTI_CSRF_TOKEN: string | null = null;--type RequestOptions = {- json: boolean;- hasBody: boolean;- noEvent: boolean;- /**- * When `true`, resolve with the raw `Response` instead of the parsed body —- * for callers that read it themselves (binary downloads, map tiles as a- * blob). Implies the fetch path (XHR has no `Response` object).- */- rawResponse?: boolean;- headers: Record<string, string>;- retry: boolean;- retryCount: number;- retryDelayIntervals: number[];- fetch?: boolean;- signal?: AbortSignal;-};--const DEFAULT_OPTIONS: RequestOptions = {- json: true,- hasBody: false,- noEvent: false,- headers: {},- retry: false,- retryCount: MAX_RETRIES,- // Creates an array with exponential backoff in millis- // i.e. [1000, 2000, 4000, 8000...]- retryDelayIntervals: new Array(MAX_RETRIES)- .fill(1)- .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>,-) => ApiMethod;--/**- * Thrown when the transport itself fails before a response is received —- * e.g. the server dropped the connection, DNS lookup failed, or the user is- * offline. Callers can `instanceof`-check this to render a connectivity- * error message instead of treating it as a generic JS exception.- */-export class NetworkError extends Error {- constructor(message = "Network error") {- super(message);- this.name = "NetworkError";- }-}--/**- * The standard web-platform shape for a cancelled request: an `Error` whose- * `name` is `"AbortError"`. `fetch()` rejects with a `DOMException` of this- * shape on abort, and we throw the same from the XHR path so both transports- * line up. Use `isAbortError` to narrow.- */-export type AbortError = Error & { name: "AbortError" };-/**- * Type guard for the standard `AbortError` that `fetch()` (and- * `XMLHttpRequest.abort()`-driven rejections) surface when the request is- * cancelled. Replaces the legacy `error.isCancelled` flag.+ * @deprecated These helpers are a compatibility shim for callers that haven't+ * moved to `api.request(...)` yet. New code should call `api.request` directly+ * (or the appropriate RTK endpoint). The exports below are scheduled for+ * removal once every importer migrates — search `metabase/api/legacy-client`+ * to find them.*/-export function isAbortError(error: unknown): error is AbortError {- return (- typeof error === "object" &&- error !== null &&- (error as { name?: unknown }).name === "AbortError"- );-}--type ResponseErrorInfo = {- body: unknown;- status: number;- metabaseVersion: string | null;-};--type EventMap = {- // Per-status events. Listeners receive the request URL (with basename- // stripped so subscribers see the relative path).- [status: number]: [string];- // Fired for any non-2xx response. Payload includes the response body so- // callers can inspect the failure beyond just its status.- responseError: [ResponseErrorInfo];-};--export class LegacyApi extends EventEmitter<EventMap> {- basename = "";- apiKey = "";- sessionToken: string | undefined;- requestClient: RequestClientInfo | undefined;-- beforeRequestHandlers: OnBeforeRequestHandler[] = [];-- GET: MethodCreator;- POST: MethodCreator;- PUT: MethodCreator;- DELETE: MethodCreator;-- constructor() {- super();- this.GET = this._makeMethod("GET", { retry: true });- this.DELETE = this._makeMethod("DELETE", {});- this.POST = this._makeMethod("POST", { hasBody: true, retry: true });- this.PUT = this._makeMethod("PUT", { hasBody: true });- }-- getClientHeaders(): Record<string, string> {- const self = this;- const headers: Record<string, string> = {};-- if (this.apiKey) {- headers["X-Api-Key"] = self.apiKey;- }-- if (this.sessionToken) {- headers["X-Metabase-Session"] = self.sessionToken!;- }-- if (isWithinIframe() && !isEmbeddingSdk()) {- headers["X-Metabase-Embedded"] = "true";- }-- if (self.requestClient) {- if (IFRAMED_IN_SELF) {- headers["X-Metabase-Embedded-Preview"] = "true";- }- if (typeof self.requestClient === "object") {- headers["X-Metabase-Client"] = self.requestClient.name;- if (self.requestClient.version) {- headers["X-Metabase-Client-Version"] = self.requestClient.version;- }- } else {- headers["X-Metabase-Client"] = self.requestClient;- }- }-- if (ANTI_CSRF_TOKEN) {- headers[ANTI_CSRF_HEADER] = ANTI_CSRF_TOKEN;- }-- if (DEFAULT_OPTIONS.headers["X-Metabase-Locale"]) {- headers["X-Metabase-Locale"] =- DEFAULT_OPTIONS.headers["X-Metabase-Locale"];- }-- const traceparent = getTraceparentHeader();- if (traceparent) {- headers["traceparent"] = traceparent;- }-- return headers;- }-- _makeMethod(- methodTemplate: string,- creatorOptions: Partial<RequestOptions> = {},- ): MethodCreator {- return (urlTemplate, methodOptions = {}) => {- const defaultOptions: RequestOptions = {- ...DEFAULT_OPTIONS,- ...creatorOptions,- ...methodOptions,- };-- 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;- url = substituteUrlTags(url, data, method);- // remove undefined- for (const name in data) {- if (data[name] === undefined) {- delete data[name];- }- }-- let body: string | FormData | URLSearchParams | undefined;- if (options.hasBody) {- if (- rawData instanceof FormData ||- rawData instanceof URLSearchParams- ) {- // Pass `FormData` / `URLSearchParams` bodies straight through so- // the browser sets the right Content-Type itself (multipart with- // boundary, or `application/x-www-form-urlencoded`). Replaces the- // legacy `body: { formData }, formData: true` wrapper shape.- body = rawData;- } else {- body = JSON.stringify(data);- }- } else {- const qs = querystring.stringify(data as Record<string, string>);- if (qs) {- url += (url.indexOf("?") >= 0 ? "&" : "?") + qs;- }- }-- const headers: Record<string, string> = {- ...this.getClientHeaders(),- ...(options.json- ? { Accept: "application/json", "Content-Type": "application/json" }- : {}),- ...options.headers,- };-- // A `FormData` / `URLSearchParams` body must NOT carry our default- // `application/json` Content-Type — the browser (or XHR's- // `send(body)`) sets the correct value, with the multipart boundary- // for `FormData`. Both transports honor this.- if (body instanceof FormData || body instanceof URLSearchParams) {- delete headers["Content-Type"];- }-- if (options.retry) {- return this._makeRequestWithRetries(- method,- url,- headers,- body,- data,- options,- );- } else {- return this._makeRequest(method, url, headers, body, data, options);- }- };- };- }-- async _makeRequestWithRetries(- method: string,- url: string,- headers: Record<string, string>,- body: string | FormData | URLSearchParams | undefined,- data: Record<string, unknown>,- options: RequestOptions,- ): Promise<unknown> {- // Get a copy of the delay intervals that we can pop items from as we retry- const retryDelays = options.retryDelayIntervals.slice().reverse();- let retryCount = 0;- // maxAttempts is the first attempt followed by the number of retries- const maxAttempts = options.retryCount + 1;- // Make the first attempt for the request, then loop incrementing the retryCount- do {- try {- return await this._makeRequest(- method,- url,- headers,- body,- data,- options,- );- } 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 as { status?: number }).status === 503 &&- retryCount < maxAttempts- ) {- await delay(retryDelays.pop() ?? 0, options.signal);- if (options.signal?.aborted) {- throw new DOMException("Aborted", "AbortError");- }- } else {- throw e;- }- }- } while (retryCount < maxAttempts);- }-- _makeRequest(- method: string,- url: string,- headers: Record<string, string>,- body: string | FormData | URLSearchParams | 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)- // `rawResponse` also forces fetch — XHR has no `Response` object.- if (isTest || options.fetch || options.rawResponse) {- return this._makeRequestWithFetch(- method,- url,- headers,- body,- data,- options,- );- } else {- return this._makeRequestWithXhr(- method,- url,- headers,- body,- data,- options,- );- }- }-- _makeRequestWithXhr(- method: string,- url: string,- headers: Record<string, string>,- body: string | FormData | URLSearchParams | undefined,- data: Record<string, unknown>,- options: RequestOptions,- ): Promise<unknown> {- return new Promise((resolve, reject) => {- let isCancelled = false;- const xhr = new XMLHttpRequest();- xhr.open(method, this.basename + url);- for (const headerName in headers) {- xhr.setRequestHeader(headerName, headers[headerName]);- }- xhr.onreadystatechange = () => {- if (xhr.readyState === XMLHttpRequest.DONE) {- // getResponseHeader() is case-insensitive- const antiCsrfToken = xhr.getResponseHeader(ANTI_CSRF_HEADER);- const metabaseVersion = xhr.getResponseHeader(- METABASE_VERSION_HEADER,- );-- if (antiCsrfToken) {- ANTI_CSRF_TOKEN = antiCsrfToken;- }-- // An empty body (e.g. 204 No Content) surfaces as `null`, not `""`,- // so callers don't have to handle "the response was empty" via- // per-endpoint `transformResponse` workarounds.- let responseBody: Response | string | null | undefined =- xhr.status === 204 ? null : xhr.responseText;-- if (options.json && xhr.responseText !== "") {- try {- responseBody = JSON.parse(xhr.responseText);- } catch (e) {}- }-- let status = xhr.status;- if (- status === 202 &&- responseBody &&- typeof responseBody === "object" &&- "_status" in responseBody &&- (responseBody._status as number) > 0- ) {- status = responseBody._status as number;- }-- if (isCancelled) {- // Surface aborts as the standard `DOMException` AbortError so- // callers can `isAbortError`-check the same shape both transports- // (and `fetch` itself) emit. Skip the responseError/status events- // since the request was cancelled — there's no real response.- reject(new DOMException("Aborted", "AbortError"));- return;- }-- if (status >= 200 && status <= 299) {- resolve(responseBody);- } else {- this.emit("responseError", {- body: responseBody,- status,- metabaseVersion,- });-- reject({- status: status,- data: responseBody,- });- }- if (!options.noEvent) {- this.emit(status, url);- }- }- };- xhr.send(body);-- if (options.signal) {- const onAbort = () => {- isCancelled = true;- xhr.abort();- };- if (options.signal.aborted) {- onAbort();- } else {- options.signal.addEventListener("abort", onAbort);- }- }- });- }-- async _makeRequestWithFetch(- method: string,- url: string,- headers: Record<string, string>,- requestBody: string | FormData | URLSearchParams | undefined,- data: Record<string, unknown>,- options: RequestOptions,- ): Promise<unknown> {- // We bridge `options.signal` through a local controller (rather than- // handing it to `fetch` directly) so an already-aborted signal still gets- // its request dispatched: the request is sent this microtask, then the- // local controller aborts on the next. This matches XHR's `send()` →- // `abort()` semantics and keeps superseded-but-parked requests (e.g.- // through the embedding-SDK token refresh) going out.- const controller = new AbortController();- const requestUrl = new URL(this.basename + url, location.origin);- const request = new Request(requestUrl.href, {- method,- headers,- body: requestBody,- signal: controller.signal,- });-- if (options.signal) {- if (options.signal.aborted) {- queueMicrotask(() => controller.abort());- } else {- options.signal.addEventListener("abort", () => controller.abort());- }- }-- return fetch(request)- .then((response) => {- const unreadResponse = response.clone();- return response.text().then((bodyText) => {- // An empty body (e.g. 204 No Content) surfaces as `null`, not `""`,- // so callers don't have to handle "the response was empty" via- // per-endpoint `transformResponse` workarounds.- let body: string | Response | null | undefined =- response.status === 204 ? null : bodyText;-- if (options.json && bodyText !== "") {- try {- body = JSON.parse(bodyText);- } catch (e) {}- }-- let status = response.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);- const metabaseVersion = response.headers.get(METABASE_VERSION_HEADER);-- if (token) {- ANTI_CSRF_TOKEN = token;- }-- if (!options.noEvent) {- this.emit(status, url);- }-- if (status >= 200 && status <= 299) {- // `rawResponse` callers (binary downloads, map tiles) want the- // `Response` object itself rather than the parsed body — return- // the unread clone so they can `.blob()`/`.arrayBuffer()` it.- return options.rawResponse ? unreadResponse : body;- } else {- this.emit("responseError", { body, status, metabaseVersion });-- throw { status: status, data: body };- }- });- })- .catch((error: unknown) => {- // When the request is aborted, `fetch` rejects with the standard- // `DOMException` AbortError. Let it propagate untouched so callers- // can `isAbortError`-check the standard web shape.- if (options.signal?.aborted) {- throw error;- }- // A raw `fetch` rejection (e.g. the server dropped the connection)- // surfaces as a plain Error here, indistinguishable from JS- // exceptions thrown elsewhere. Wrap it so downstream renderers can- // `instanceof NetworkError`-check and route it to the connectivity- // error message.- if (error instanceof Error) {- throw new NetworkError(error.message);- }- throw error;- });- }-- 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.- */- const handlers: Array<- (- data: OnBeforeRequestHandlerConfig,- ) => Promise<void | OnBeforeRequestHandlerConfig>- > = [];-- if (isEmbeddingSdk()) {- handlers.push(- ...[- PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers- .getOrRefreshSessionHandler,- PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers- .getOrRefreshGuestSessionHandler,- PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers- .overrideRequestsForGuestEmbeds,- ],- );- } else {- handlers.push(- ...[- PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds,- PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForStaticEmbeds,- ],- );- }-- handlers.push(...this.beforeRequestHandlers);-- if (handlers.length) {- for (const handler of handlers) {- const onBeforeRequestHandlerResult = await handler({- method,- url,- options,- data,- });-- if (onBeforeRequestHandlerResult) {- if (onBeforeRequestHandlerResult.method) {- method = onBeforeRequestHandlerResult.method;- }-- if (onBeforeRequestHandlerResult.url) {- url = onBeforeRequestHandlerResult.url;- }-- if (onBeforeRequestHandlerResult.options) {- options = {- ...options,- ...onBeforeRequestHandlerResult.options,- };- }-- if (onBeforeRequestHandlerResult.data) {- data = {- ...data,- ...onBeforeRequestHandlerResult.data,- };- }- }- }- }-- return { method, url, options, data };- }-}--const instance = new LegacyApi();--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default instance;-export const { GET, POST, PUT, DELETE } = instance;+import { api } from "./client";-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!;-};+export { NetworkError, type RequestMethod } from "./client";+export const { GET, POST, PUT, DELETE } = api;diff --git a/frontend/src/metabase/api/legacy-client.unit.spec.ts b/frontend/src/metabase/api/legacy-client.unit.spec.tsindex e06a1af1816..c0859f319df 100644--- a/frontend/src/metabase/api/legacy-client.unit.spec.ts+++ b/frontend/src/metabase/api/legacy-client.unit.spec.ts@@ -1,414 +1,95 @@import fetchMock from "fetch-mock";-import { LegacyApi } from "./legacy-client";+import { api } from "./client";+import { GET, POST } from "./legacy-client";-type OnBeforeRequestHandlerData = {- method: "GET" | "POST" | "PUT" | "DELETE";- url: string;- options: {- headers?: Record<string, string>;- hasBody: boolean;- } & Record<string, unknown>;-};--describe("api", () => {- describe("apiRequestManipulationMiddleware", () => {- let apiInstance: LegacyApi;-- beforeEach(() => {- apiInstance = new LegacyApi();- });-- it("should return the original data when there are no handlers", async () => {- const inputData = {- method: "GET" as const,- url: "/api/test",- options: { hasBody: false, json: true },- data: {},- };-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result).toEqual(inputData);- });-- it("should return the original data when handler returns void", async () => {- const inputData = {- method: "POST" as const,- url: "/api/test",- options: { hasBody: true, json: true, headers: { "X-Test": "value" } },- data: {},- };-- // Mock a handler that returns void- const voidHandler = jest.fn().mockResolvedValue(undefined);- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- await voidHandler(data);- return data;- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result).toEqual(inputData);- expect(voidHandler).toHaveBeenCalledWith(inputData);- });-- it("should update only the url when handler returns partial modification", async () => {- const inputData = {- method: "GET" as const,- url: "/api/original",- options: { hasBody: false, json: true },- data: {},- };-- const expectedUrl = "/api/modified";-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- // Simulate handler that only modifies URL- const typedData = data as OnBeforeRequestHandlerData;- return {- method: typedData.method,- url: expectedUrl,- options: typedData.options,- };- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result).toEqual({- method: inputData.method,- url: expectedUrl,- options: inputData.options,- });- });-- it("should update method, url, and options when handler returns full modification", async () => {- const inputData = {- method: "GET" as const,- url: "/api/original",- options: { hasBody: false, json: true },- data: {},- };-- const modifications = {- method: "POST" as const,- url: "/api/modified",- options: { hasBody: true, json: false, custom: "value" },- };-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async () => modifications);-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result).toEqual(modifications);- });-- it("should merge options properly when handler returns partial options", async () => {- const inputData = {- method: "POST" as const,- url: "/api/test",- options: {- hasBody: true,- json: true,- headers: { "X-Original": "value" },- retry: true,- },- data: {},- };-- const newHeaders = { "X-Modified": "new-value" };-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- const typedData = data as OnBeforeRequestHandlerData;- return {- method: typedData.method,- url: typedData.url,- options: {- ...typedData.options,- headers: { ...typedData.options.headers, ...newHeaders },- },- };- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result.options.headers).toEqual({- "X-Original": "value",- "X-Modified": "new-value",- });- expect(result.options.hasBody).toBe(true);- expect(result.options.json).toBe(true);- expect(result.options.retry).toBe(true);- });-- it("should execute multiple handlers in order", async () => {- const inputData = {- method: "GET" as const,- url: "/api/start",- options: { hasBody: false, counter: 0 },- data: {},- };-- const executionOrder: number[] = [];-- const handler1 = jest.fn(- async (- data: OnBeforeRequestHandlerData & { options: { counter: number } },- ) => {- executionOrder.push(1);- return {- ...data,- url: data.url + "/step1",- options: { ...data.options, counter: data.options.counter + 1 },- };- },- );-- const handler2 = jest.fn(- async (- data: OnBeforeRequestHandlerData & { options: { counter: number } },- ) => {- executionOrder.push(2);- return {- ...data,- url: data.url + "/step2",- options: { ...data.options, counter: data.options.counter + 10 },- };- },- );-- const handler3 = jest.fn(- async (- data: OnBeforeRequestHandlerData & { options: { counter: number } },- ) => {- executionOrder.push(3);- return {- ...data,- url: data.url + "/step3",- options: { ...data.options, counter: data.options.counter + 100 },- };- },- );-- // Mock the middleware to use our handlers- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- let currentData = data as OnBeforeRequestHandlerData & {- options: { counter: number };- };- for (const handler of [handler1, handler2, handler3]) {- const result = await handler(currentData);- if (result) {- currentData = result;- }- }- return currentData;- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(executionOrder).toEqual([1, 2, 3]);- expect(result.url).toBe("/api/start/step1/step2/step3");- expect(result.options.counter).toBe(111); // 0 + 1 + 10 + 100- expect(handler1).toHaveBeenCalledWith(- expect.objectContaining({ url: "/api/start" }),- );- expect(handler2).toHaveBeenCalledWith(- expect.objectContaining({ url: "/api/start/step1" }),- );- expect(handler3).toHaveBeenCalledWith(- expect.objectContaining({ url: "/api/start/step1/step2" }),- );- });-- it("should handle async handlers correctly", async () => {- const inputData = {- method: "POST" as const,- url: "/api/async",- options: { hasBody: true, json: true },- data: {},- };-- const asyncHandler = jest.fn(async (data: OnBeforeRequestHandlerData) => {- // Simulate async operation- await new Promise((resolve) => setTimeout(resolve, 10));- return {- ...data,- url: "/api/async-modified",- };- });-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- return await asyncHandler(data as OnBeforeRequestHandlerData);- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(asyncHandler).toHaveBeenCalled();- expect(result.url).toBe("/api/async-modified");- });-- it("should handle handler that only returns options", async () => {- const inputData = {- method: "GET" as const,- url: "/api/test",- options: { hasBody: false },- data: {},- };-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- const typedData = data as OnBeforeRequestHandlerData;- return {- method: typedData.method,- url: typedData.url,- options: { ...typedData.options, newOption: "added" },- };- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result.method).toBe("GET");- expect(result.url).toBe("/api/test");- expect(result.options).toEqual({ hasBody: false, newOption: "added" });- });-- it("should preserve all original options when handler does not modify them", async () => {- const complexOptions = {- hasBody: true,- json: true,- headers: { "X-Custom": "header" },- retry: true,- retryCount: 5,- noEvent: false,- rawResponse: true,- };-- const inputData = {- method: "POST" as const,- url: "/api/complex",- options: complexOptions,- data: {},- };-- jest- .spyOn(apiInstance as any, "apiRequestManipulationMiddleware")- .mockImplementation(async (data) => {- const typedData = data as OnBeforeRequestHandlerData;- return {- ...typedData,- url: "/api/modified-url",- };- });-- const result =- await apiInstance.apiRequestManipulationMiddleware(inputData);-- expect(result.url).toBe("/api/modified-url");- expect(result.options).toEqual(complexOptions);- expect(result.options.rawResponse).toBe(true);- });+describe("legacy-client", () => {+ afterEach(() => {+ fetchMock.removeRoutes().clearHistory();+ api.beforeRequestHandlers = [];});- // In test environments (`isTest`) the legacy client routes every request- // through `_makeRequestWithFetch`, so these specs cover the fetch path. The- // XHR path's empty-body branch mirrors the same `status === 204` check and is- // exercised end-to-end by the live app; co-locating both transports' unit- // coverage would require a dedicated XHR mock which the spec doesn't- // currently set up.- describe("response body parsing", () => {- let apiInstance: LegacyApi;+ it("substitutes URL :tags from rawData and routes the remainder to the JSON body for POST", async () => {+ fetchMock.post("path:/api/card/42/query", { rows: [] });- beforeEach(() => {- apiInstance = new LegacyApi();+ await POST("/api/card/:cardId/query")({+ cardId: 42,+ parameters: ["a"],+ ignore_cache: true,});- afterEach(() => {- fetchMock.removeRoutes().clearHistory();- });-- it("resolves an empty 204 body as null (not the empty string)", async () => {- fetchMock.get("path:/api/empty", { status: 204, body: "" });+ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(/\/api\/card\/42\/query$/);+ expect(call?.url).not.toContain("parameters=");+ expect(call?.options?.body).toBe(+ JSON.stringify({ parameters: ["a"], ignore_cache: true }),+ );+ });- const result = await apiInstance.GET("/api/empty")({});+ it("substitutes URL :tags from rawData and routes the remainder to the querystring for GET", async () => {+ fetchMock.get("path:/api/card/7/params/p/values", { values: [] });- expect(result).toBeNull();+ await GET("/api/card/:cardId/params/:paramId/values")({+ cardId: 7,+ paramId: "p",+ limit: 10,});- it("leaves an empty non-204 body as the empty string", async () => {- // Only 204 No Content is normalized to null. An empty-bodied 200 keeps- // its historical empty-string value so callers that index into a body- // (e.g. `result.id`) don't begin dereferencing null.- fetchMock.get("path:/api/also-empty", { status: 200, body: "" });+ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toContain("/api/card/7/params/p/values");+ expect(call?.url).toContain("limit=10");+ expect(call?.options?.body).toBeFalsy();+ });- const result = await apiInstance.GET("/api/also-empty")({});+ it("sends FormData bodies as-is and strips Content-Type", async () => {+ fetchMock.post("path:/api/table/9/append-csv", { success: true });- expect(result).toBe("");- });+ const formData = new FormData();+ formData.append("file", new Blob(["a,b\n1,2"]), "x.csv");- it("parses a non-empty JSON body to its decoded value", async () => {- fetchMock.get("path:/api/data", {- status: 200,- body: { hello: "world" },- });+ await POST("/api/table/9/append-csv")(formData);- const result = await apiInstance.GET("/api/data")({});-- expect(result).toEqual({ hello: "world" });- });+ const call = fetchMock.callHistory.lastCall();+ const sentHeaders = call?.options?.headers as+ | Record<string, string>+ | Headers+ | undefined;+ const contentType =+ sentHeaders instanceof Headers+ ? sentHeaders.get("Content-Type")+ : sentHeaders?.["Content-Type"];+ expect(contentType).toBeFalsy();});- describe("form-encoded requests", () => {- let apiInstance: LegacyApi;+ it("lets a middleware-overridden URL substitute :tag tokens from any rawData field (embed flow regression)", async () => {+ // Regression for the guest-embed flow: legacy `CardApi.query(rawData)` is+ // called with `{ token, parameters, ... }`. The embed URL override+ // middleware rewrites `/api/card/:cardId/query` to+ // `/api/embed/card/:token/query`, and `:token` must be filled from the+ // (body-shaped) `token` field of the bag — not just from URL params.+ fetchMock.get("path:/api/embed/card/SOME_JWT/query", { rows: [] });- beforeEach(() => {- apiInstance = new LegacyApi();+ api.beforeRequestHandlers.push(async (config) => {+ if (config.url === "/api/card/:cardId/query") {+ return {+ ...config,+ method: "GET" as const,+ url: "/api/embed/card/:token/query",+ };+ }+ return config;});- afterEach(() => {- fetchMock.removeRoutes().clearHistory();+ await POST("/api/card/:cardId/query")({+ token: "SOME_JWT",+ parameters: "[]",});- // Regression: a `URLSearchParams` body (e.g. a dataset download) must be- // passed through verbatim — not JSON-stringified — and must drop our- // default `application/json` Content-Type so the browser can set- // `application/x-www-form-urlencoded`. Keeping the JSON header made the- // backend reject the request with a 400.- //- // The Content-Type strip is gated on `body instanceof URLSearchParams`, so- // this assertion doubles as proof the body reached `fetch` as a real- // `URLSearchParams` rather than a JSON string.- it("drops the application/json Content-Type for a URLSearchParams body", async () => {- fetchMock.post("path:/api/download", { status: 200, body: "" });-- const body = new URLSearchParams();- body.append("query", JSON.stringify({ foo: "bar" }));-- await apiInstance.POST("/api/download")(body, { rawResponse: true });-- const call = fetchMock.callHistory.lastCall("path:/api/download");- const headers = new Headers(call?.options?.headers);- expect(headers.get("Content-Type")).not.toContain("application/json");- });+ const call = fetchMock.callHistory.lastCall();+ expect(call?.url).toMatch(/\/api\/embed\/card\/SOME_JWT\/query/);+ // The override-changed method is GET, so leftover bag fields are folded+ // into the querystring (a GET request cannot carry a body).+ expect(call?.url).toContain("parameters=");+ expect(call?.options?.body).toBeFalsy();});});diff --git a/frontend/src/metabase/api/localization.ts b/frontend/src/metabase/api/localization.tsindex fbe4af46e57..be362e52af2 100644--- a/frontend/src/metabase/api/localization.ts+++ b/frontend/src/metabase/api/localization.ts@@ -1,4 +1,4 @@-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import {type LocaleDataWithLanguage,setLocalization,diff --git a/frontend/src/metabase/api/query.ts b/frontend/src/metabase/api/query.tsdeleted file mode 100644index 2e03cce4c1b..00000000000--- a/frontend/src/metabase/api/query.ts+++ /dev/null@@ -1,47 +0,0 @@-import type { BaseQueryFn } from "@reduxjs/toolkit/query/react";--import api from "metabase/api/legacy-client";--type AllowedHTTPMethods = "GET" | "POST" | "PUT" | "DELETE";-const allowedHTTPMethods = new Set<AllowedHTTPMethods>([- "GET",- "POST",- "PUT",- "DELETE",-]);-const isAllowedHTTPMethod = (method: any): method is AllowedHTTPMethods => {- return allowedHTTPMethods.has(method);-};--// custom fetcher that wraps our Api client-export const apiQuery: BaseQueryFn = async (args, ctx, extraOptions) => {- const method = typeof args === "string" ? "GET" : (args?.method ?? "GET");- const url = typeof args === "string" ? args : args.url;- const { noEvent, fetch, rawResponse } = args;-- if (!isAllowedHTTPMethod(method)) {- return { error: "Invalid HTTP method" };- }-- // `FormData` / `URLSearchParams` bodies are forwarded as-is — spreading would- // yield an empty object (their entries aren't enumerable as keys) and erase- // the body. Other bodies merge with `params` so a single combined object- // reaches the legacy client (which doesn't separate them).- const rawData =- args?.body instanceof FormData || args?.body instanceof URLSearchParams- ? args.body- : { ...args?.body, ...args?.params };-- try {- const response = await api[method](url)(rawData, {- signal: ctx.signal,- noEvent,- fetch,- rawResponse,- ...extraOptions,- });- return { data: response };- } catch (error) {- return { error };- }-};diff --git a/frontend/src/metabase/api/utils/index.ts b/frontend/src/metabase/api/utils/index.tsindex 3c6ad8edd7f..f359f728c2f 100644--- a/frontend/src/metabase/api/utils/index.ts+++ b/frontend/src/metabase/api/utils/index.ts@@ -2,5 +2,4 @@ export * from "./errors";export * from "./hydrate-metadata-store";export * from "./run-rtk-endpoint";export * from "./settings";-export * from "./substitute-url-tags";export * from "./use-token-refresh";diff --git a/frontend/src/metabase/api/utils/substitute-url-tags.ts b/frontend/src/metabase/api/utils/substitute-url-tags.tsdeleted file mode 100644index 10e0b289106..00000000000--- a/frontend/src/metabase/api/utils/substitute-url-tags.ts+++ /dev/null@@ -1,28 +0,0 @@-// URL template tags:-// - `:tag` — value is URL-encoded (default; slashes become %2F).-// - `:tag*` — value is substituted raw (slashes preserved), for endpoints-// whose route includes a multi-segment path parameter.-const URL_TAG_REGEX = /:\w+\*?/g;--/**- * Replace `:tag` / `:tag*` placeholders in a URL template with values pulled- * from `data`. Substituted keys are deleted from `data` so the caller can use- * any leftovers as querystring params.- */-export function substituteUrlTags(- url: string,- data: Record<string, unknown>,- method: string,-): string {- return url.replace(URL_TAG_REGEX, (tag) => {- const isRaw = tag.endsWith("*");- const paramName = tag.slice(1, isRaw ? -1 : undefined);- const value = data[paramName];- delete data[paramName];- if (value === undefined) {- console.warn("Warning: calling", method, "without", tag);- return "";- }- return isRaw ? String(value) : encodeURIComponent(String(value));- });-}diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsxindex c5f725722c7..adc44abdb11 100644--- a/frontend/src/metabase/app-embed-mcp.tsx+++ b/frontend/src/metabase/app-embed-mcp.tsx@@ -3,7 +3,7 @@ import { createRoot } from "react-dom/client";// Import the embedding SDK vendors side-effects (sets up global CSS vars, etc.)import "metabase/embedding-sdk/vendors-side-effects";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { McpUiAppRoute } from "metabase/embedding/mcp/McpUiAppRoute";import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";diff --git a/frontend/src/metabase/app-main.js b/frontend/src/metabase/app-main.jsindex a609a852ff6..6dfa48aaeb5 100644--- a/frontend/src/metabase/app-main.js+++ b/frontend/src/metabase/app-main.js@@ -5,7 +5,7 @@ import "metabase-dev";import { push } from "react-router-redux";import _ from "underscore";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { init } from "metabase/app";import { mainReducers } from "metabase/reducers-main";import { setErrorPage } from "metabase/redux/app";diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.jsindex 0888a88742d..f17e4fd7661 100644--- a/frontend/src/metabase/app.js+++ b/frontend/src/metabase/app.js@@ -33,7 +33,7 @@ import { syncHistoryWithStore } from "react-router-redux";import { initializePlugins } from "ee-plugins";import { AppThemeProvider } from "metabase/AppThemeProvider";import { createSnowplowTracker } from "metabase/analytics";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { ModifiedBackend } from "metabase/common/components/dnd/ModifiedBackend";import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-embedding";diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex 694657b8526..a7928ebcbeb 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -12,7 +12,7 @@ import {makePivotAwareQueryRunner,publicApi,} from "metabase/api";-import { isAbortError } from "metabase/api/legacy-client";+import { isAbortError } from "metabase/api/client";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { applyParameters } from "metabase/common/utils/card";import { showAutoApplyFiltersToast } from "metabase/dashboard/actions/parameters";diff --git a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx b/frontend/src/metabase/dashboard/components/DashboardGrid.tsxindex 7e0552a2537..900bb173f2d 100644--- a/frontend/src/metabase/dashboard/components/DashboardGrid.tsx+++ b/frontend/src/metabase/dashboard/components/DashboardGrid.tsx@@ -521,14 +521,18 @@ class DashboardGridInner extends Component<);}- onVisualizerModalSave = (visualization: VisualizerVizDefinition) => {+ onVisualizerModalSave = async (visualization: VisualizerVizDefinition) => {const { visualizerModalStatus } = this.state;if (!visualizerModalStatus) {return;}- this.props.replaceCardWithVisualization({+ // Await the replacement before closing the modal: it commits the new+ // card series to the dashcard only after fetching the referenced cards.+ // Closing early lets a subsequent dashboard save run against the+ // not-yet-updated dashcard, which would drop the new series.+ await this.props.replaceCardWithVisualization({dashcardId: visualizerModalStatus.dashcardId,visualization,});diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionList.tsx b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionList.tsxindex a27f3ce98e3..82d102f4949 100644--- a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionList.tsx+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionList.tsx@@ -191,8 +191,11 @@ export function QuestionList({<VisualizerModalWithCardIdcardId={visualizerModalCardId}dashboardId={dashboardId ?? undefined}- onSave={(visualization) => {- dispatch(+ onSave={async (visualization) => {+ // Await the dispatch before closing: the thunk commits the new+ // dashcard (and its series) only after fetching the referenced+ // cards, so closing early can race a subsequent dashboard save.+ await dispatch(addCardWithVisualization({ visualization, tabId: selectedTabId }),);setVisualizerModalCardId(null);diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsxindex df3e85b8bcf..987d7d427d2 100644--- a/frontend/src/metabase/dashboard/context/context.tsx+++ b/frontend/src/metabase/dashboard/context/context.tsx@@ -13,7 +13,7 @@ import {import { usePrevious, useUnmount } from "react-use";import { isEqual, noop } from "underscore";-import { isAbortError } from "metabase/api/legacy-client";+import { isAbortError } from "metabase/api/client";import { useEmbeddingEntityContext } from "metabase/embedding/context";import { getTabHiddenParameterSlugs } from "metabase/embedding/lib/tab-parameters";import type {diff --git a/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts b/frontend/src/metabase/dashboard/types/fetch-dashboard-result.tsindex 23c739c862d..bdedd403d48 100644--- a/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts+++ b/frontend/src/metabase/dashboard/types/fetch-dashboard-result.ts@@ -1,15 +1,15 @@-import type { AbortError } from "metabase/api/legacy-client";import type { Dashboard } from "metabase-types/api";type SuccessfulFetchDashboardResult = {payload: { dashboard: Dashboard };};-// A cancelled fetch surfaces as an `AbortError` payload. It also satisfies+// A cancelled fetch surfaces as a `payload` matching the standard+// `DOMException` AbortError shape. It also satisfies// `FailedFetchDashboardResult` shape-wise, so consumers use// `isAbortError(result.payload)` to distinguish.type CancelledFetchDashboardResult = {- payload: AbortError;+ payload: { name: "AbortError" };};export type FailedFetchDashboardResult = { error: unknown; payload: unknown };diff --git a/frontend/src/metabase/embedding/LocaleProvider.tsx b/frontend/src/metabase/embedding/LocaleProvider.tsxindex 9e49eb99204..b0eb3ad7554 100644--- a/frontend/src/metabase/embedding/LocaleProvider.tsx+++ b/frontend/src/metabase/embedding/LocaleProvider.tsx@@ -6,7 +6,7 @@ import {useState,} from "react";-import { setLocaleHeader } from "metabase/api/legacy-client";+import { setLocaleHeader } from "metabase/api/client";import { loadLocalization } from "metabase/api/localization";import { useSetting } from "metabase/common/hooks";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";diff --git a/frontend/src/metabase/embedding/config.ts b/frontend/src/metabase/embedding/config.tsindex 4fbfd487e4c..57c30516c6c 100644--- a/frontend/src/metabase/embedding/config.ts+++ b/frontend/src/metabase/embedding/config.ts@@ -1,4 +1,4 @@-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex 7b40fff47b0..8600bd1137a 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -20,7 +20,7 @@ import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/dimport type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";import { applyThemePreset } from "embedding-sdk-shared/lib/apply-theme-preset";import { createSnowplowTracker } from "metabase/analytics";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { EmbeddingFooter } from "metabase/embedding/components/EmbeddingFooter/EmbeddingFooter";import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";@@ -53,13 +53,10 @@ const embedReferrerHandler = async (if (_embedReferrer) {return {...config,- options: {- ...config.options,- headers: {- ...config.options.headers,- // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name- "X-Metabase-Embed-Referrer": _embedReferrer,- },+ headers: {+ ...config.headers,+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name+ "X-Metabase-Embed-Referrer": _embedReferrer,},};}diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.tsindex 4245f62ddba..31545d3e97d 100644--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts@@ -1,4 +1,5 @@import { sessionPropertiesPath } from "metabase/api";+import type { RequestMethod } from "metabase/api/client";import {PLUGIN_API,PLUGIN_CONTENT_TRANSLATION,@@ -48,7 +49,7 @@ const EMBED_URL_TRANSFORMATIONS: Record<string,(data: { embedType: EmbedType }) => {url: string;- method: "GET" | "POST";+ method: RequestMethod;}> = {[URL_PATTERNS.CARD_QUERY]: ({ embedType }) => ({@@ -86,12 +87,9 @@ const EMBED_URL_TRANSFORMATIONS: Record<} as const;type RequestData = {- method: "GET" | "POST";+ method: RequestMethod;url: string;- options: {- headers?: Record<string, string>;- hasBody: boolean;- } & Record<string, unknown>;+ headers?: Record<string, string>;};/**@@ -132,7 +130,7 @@ function getRequestTransformation({method,embedType,url,- options,+ headers,}: RequestData & { embedType: EmbedType }): RequestData | null {const matchedPattern = findMatchingPattern(url);@@ -146,7 +144,7 @@ function getRequestTransformation({// No transformation needed if pattern doesn't matchif (!matchedPattern) {- return { method, url, options };+ return { method, url, headers };}// Apply the transformation for this pattern@@ -154,15 +152,12 @@ function getRequestTransformation({embedType,});if (!transformation) {- return { method, url, options };+ return { method, url, headers };}return {...transformation,- options: {- ...options,- hasBody: transformation.method === "POST",- },+ headers,};}@@ -189,7 +184,7 @@ export const overrideRequests = async ({embedType,method,url,- options,+ headers,data,}: OnBeforeRequestHandlerConfig & {embedType: EmbedType;@@ -198,21 +193,17 @@ export const overrideRequests = async ({method,embedType,url,- options,+ headers,});if (!transformation) {- return { method, url, options, data };- }-- if (!options.headers) {- options.headers = {};+ return { method, url, headers, data };}return {method: transformation.method,url: replaceWithEmbedBase({ embedType, url: transformation.url }),- options: transformation.options,+ headers: transformation.headers ?? {},data,};};diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.tsindex 9fda0646524..edec2a11770 100644--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts@@ -96,8 +96,6 @@ describe("matchUrlPattern", () => {});describe("overrideRequests", () => {- const defaultOptions = { hasBody: false };-it.each(["guest", "static", "public"] as const)("leaves /api/frontend-errors untouched in %s embed mode",async (embedType) => {@@ -105,7 +103,6 @@ describe("overrideRequests", () => {embedType,method: "POST",url: "/api/frontend-errors",- options: { ...defaultOptions, hasBody: true },data: { type: "component-crash" },});@@ -119,7 +116,6 @@ describe("overrideRequests", () => {embedType: "guest",method: "GET",url: "/api/card/THE_JWT_TOKEN",- options: defaultOptions,data: {},});@@ -131,7 +127,6 @@ describe("overrideRequests", () => {embedType: "guest",method: "POST",url: "/api/card/123/query",- options: { ...defaultOptions, hasBody: true },data: {},});diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.tsindex cb37e2cbacb..3e90e208f04 100644--- a/frontend/src/metabase/metabot/state/actions.ts+++ b/frontend/src/metabase/metabot/state/actions.ts@@ -80,36 +80,43 @@ const handleResponseError = (error: unknown,metabotName: string,): HandledResponseError => {+ // HTTP failures arrive as the legacy client's `{ status, data }` shape, with+ // the parsed response body under `data`.return match(error)+ .with({ status: 401 }, () => ({+ error: { type: "unauthenticated" },+ display: {+ type: "alert" as const,+ message: METABOT_ERR_MSG.unauthenticated(metabotName),+ },+ })).with(- { message: P.string.startsWith("Response status: 401") },- { status: 401 },+ { status: 402, data: { "error-code": "metabase_ai_managed_locked" } },() => ({- error: { type: "unauthenticated" },- display: {- type: "alert" as const,- message: METABOT_ERR_MSG.unauthenticated(metabotName),- },+ error: { type: "metabase_ai_managed_locked" },+ display: { type: "locked" as const, message: METABOT_ERR_MSG.locked },}),)- .with({ status: 402, "error-code": "metabase_ai_managed_locked" }, () => ({- error: { type: "metabase_ai_managed_locked" },- display: { type: "locked" as const, message: METABOT_ERR_MSG.locked },- }))- .with({ status: P.number, message: P.string }, ({ message }) => ({- error: { type: "http_error", message },- display: {- type: "message" as const,- message: METABOT_ERR_MSG.format(message),- },- })).with(- { "error-code": "ai_usage_limit_reached", message: P.string },- ({ message }) => ({+ {+ status: P.number,+ data: { "error-code": "ai_usage_limit_reached", message: P.string },+ },+ ({ data: { message } }) => ({error: { type: "ai_usage_limit_reached", message },display: { type: "message" as const, message },}),)+ .with(+ { status: P.number, data: { message: P.string } },+ ({ data: { message } }) => ({+ error: { type: "http_error", message },+ display: {+ type: "message" as const,+ message: METABOT_ERR_MSG.format(message),+ },+ }),+ ).with(P.string, (err) => ({error: { type: "http_error", message: err },display: {diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsxindex 4a23426d828..23a6f5364d2 100644--- a/frontend/src/metabase/metabot/tests/utils.tsx+++ b/frontend/src/metabase/metabot/tests/utils.tsx@@ -130,15 +130,10 @@ export const lastReqBody = async (agentSpy: ReturnType<typeof mockAgentEndpoint>,) => {await waitFor(() => expect(agentSpy).toHaveBeenCalled());- // Today the client calls `fetch(url, init)`, so the body is on `init`. A- // follow-up switches it to `fetch(new Request(url, init))`, moving the body- // onto the Request. Read whichever shape is present so this works either way.- const [first, init] = agentSpy.mock.lastCall ?? [];- const body =- typeof first === "string"- ? (init?.body as string)- : await (first as Request).clone().text();- return JSON.parse(body);+ // The client calls `fetch(new Request(url, init))`, so the body lives on the+ // Request object rather than a separate init arg.+ const [request] = agentSpy.mock.lastCall ?? [];+ return JSON.parse(await (request as Request).clone().text());};// Common mock response fixturesdiff --git a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsxindex d5d2894dada..1b23672c078 100644--- a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx+++ b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/QuestionAlertListModal.tsx@@ -41,16 +41,20 @@ export const QuestionAlertListModal = ({const [sendToast] = useToast();- const { data: questionNotifications } = useListNotificationsQuery({- card_id: question.id(),- include_inactive: false,- });+ const { data: questionNotifications, isFetching } = useListNotificationsQuery(+ {+ card_id: question.id(),+ include_inactive: false,+ },+ );const [updateNotification] = useUpdateNotificationMutation();const [unsubscribe] = useUnsubscribeFromNotificationMutation();const [activeModal, setActiveModal] = useState<AlertModalMode | null>(- questionNotifications ? getDefaultActiveModal(questionNotifications) : null,+ questionNotifications && !isFetching+ ? getDefaultActiveModal(questionNotifications)+ : null,);useEffect(() => {@@ -61,11 +65,17 @@ export const QuestionAlertListModal = ({* loaded and activeModal will not be null. However, in the SDK,* we'll need to wait for the data to load, so the activeModal* will be null at first.+ *+ * We wait for `isFetching` to settle before deciding so the choice+ * is based on fresh data. On reopen the cached list can momentarily+ * be stale (e.g. still containing a just-deleted alert) while a+ * refetch is in flight; deciding from that stale data would lock us+ * into the wrong modal.*/- if (questionNotifications && activeModal === null) {+ if (questionNotifications && !isFetching && activeModal === null) {setActiveModal(getDefaultActiveModal(questionNotifications));}- }, [activeModal, questionNotifications]);+ }, [activeModal, questionNotifications, isFetching]);const previousActiveModal = usePreviousDistinct(activeModal);diff --git a/frontend/src/metabase/plugins/oss/api.ts b/frontend/src/metabase/plugins/oss/api.tsindex 3037fc31ad5..e8f9ff69328 100644--- a/frontend/src/metabase/plugins/oss/api.ts+++ b/frontend/src/metabase/plugins/oss/api.ts@@ -1,18 +1,24 @@+import type { RequestMethod } from "metabase/api/client";import type { CardId, DashboardId, ParameterId } from "metabase-types/api";export type OnBeforeRequestHandlerConfig = {- method: "GET" | "POST";+ method: RequestMethod;url: string;- options: {- headers?: Record<string, string>;- hasBody: boolean;- } & Record<string, unknown>;+ headers?: Record<string, string>;+ // URL `:tag` params (and querystring leftovers). For the legacy GET/POST+ // helpers this holds the whole request bag.data: Record<string, unknown>;+ // The JSON-body bag, kept as a separate channel from `data`. Exposed to+ // handlers so embed URL `:tag`s — notably the guest-embed `:token` — can be+ // filled from body fields, and so the refresh handler can swap a stale body+ // token. `undefined` for GETs, raw (FormData/URLSearchParams) bodies, and the+ // legacy helpers (which pack everything into `data`).+ body?: Record<string, unknown>;};export type OnBeforeRequestHandler = (data: OnBeforeRequestHandlerConfig,-) => Promise<void | OnBeforeRequestHandlerConfig>;+) => Promise<void | Partial<OnBeforeRequestHandlerConfig>>;const getDefaultPluginApi = () => ({onBeforeRequestHandlers: {diff --git a/frontend/src/metabase/query_builder/actions/querying.ts b/frontend/src/metabase/query_builder/actions/querying.tsindex 3cee8bc5cf7..97e499bebef 100644--- a/frontend/src/metabase/query_builder/actions/querying.ts+++ b/frontend/src/metabase/query_builder/actions/querying.ts@@ -1,7 +1,7 @@import { createAction } from "redux-actions";import { t } from "ttag";-import { isAbortError } from "metabase/api/legacy-client";+import { isAbortError } from "metabase/api/client";import { runQuestionQuery as apiRunQuestionQuery } from "metabase/querying/run-query";import { syncVizSettingsWithSeries } from "metabase/querying/viz-settings/utils/sync-viz-settings";import { createThunkAction } from "metabase/redux";diff --git a/frontend/src/metabase/query_builder/actions/url.ts b/frontend/src/metabase/query_builder/actions/url.tsindex 443adc95188..7c6a82f0b40 100644--- a/frontend/src/metabase/query_builder/actions/url.ts+++ b/frontend/src/metabase/query_builder/actions/url.ts@@ -3,7 +3,7 @@ import { parse as parseUrl } from "url";import type { LocationDescriptor } from "history";import { push, replace } from "react-router-redux";-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { isEqualCard } from "metabase/common/utils/card";import { createThunkAction } from "metabase/redux";import * as Lib from "metabase-lib";diff --git a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsxindex 172759694d9..e8a064e6663 100644--- a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx+++ b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx@@ -2,7 +2,7 @@ import cx from "classnames";import { getIn } from "icepick";import { t } from "ttag";-import { NetworkError } from "metabase/api/legacy-client";+import { isNetworkError } from "metabase/api/client";import { EmptyState } from "metabase/common/components/EmptyState";import { ErrorDetails } from "metabase/common/components/ErrorDetails/ErrorDetails";import { ErrorMessage } from "metabase/common/components/ErrorMessage";@@ -50,7 +50,7 @@ export function VisualizationError({// the same as an HTTP error with a status — the user just needs to know the// server isn't reachable, not see a stack trace.if (- error instanceof NetworkError ||+ isNetworkError(error) ||(typeof error === "object" && error.status != null)) {// Assume if the request took more than 15 seconds it was due to a timeoutdiff --git a/frontend/src/metabase/querying/run-query.unit.spec.ts b/frontend/src/metabase/querying/run-query.unit.spec.tsindex c1ffacd5789..e209d61f0ec 100644--- a/frontend/src/metabase/querying/run-query.unit.spec.ts+++ b/frontend/src/metabase/querying/run-query.unit.spec.ts@@ -2,6 +2,7 @@ import fetchMock from "fetch-mock";import { getStore } from "__support__/entities-store";import { createMockEntitiesState } from "__support__/store";+import { waitFor } from "__support__/ui";import { Api } from "metabase/api";import { mainReducers } from "metabase/reducers-main";import { createMockState } from "metabase/redux/store/mocks";@@ -362,12 +363,22 @@ describe("metabase/querying/run-query > runQuestionQuery", () => {signal: new AbortController().signal,});+ // Wait for both requests to actually be in flight before aborting:+ // independent cache keys ⇒ two real requests, not one shared (deduped)+ // one. Aborting synchronously would short-circuit the cancelled run+ // before the client ever issues its fetch, so we'd never observe whether+ // the two queries were deduped.+ await waitFor(() =>+ expect(fetchMock.callHistory.calls(path)).toHaveLength(2),+ );+abortController.abort();await expect(liveRun).resolves.toHaveLength(1);await cancelledRun;- // Independent cache keys ⇒ two real requests, not one shared (deduped) one.+ // Aborting the cancelled run must not have disturbed the live run's+ // separate request.expect(fetchMock.callHistory.calls(path)).toHaveLength(2);});diff --git a/frontend/src/metabase/redux/downloads.ts b/frontend/src/metabase/redux/downloads.tsindex 45294714a07..9a093fd0a86 100644--- a/frontend/src/metabase/redux/downloads.ts+++ b/frontend/src/metabase/redux/downloads.ts@@ -8,8 +8,8 @@ import {import { t } from "ttag";import _ from "underscore";+import { api } from "metabase/api/client";import { datasetApi } from "metabase/api/dataset";-import api from "metabase/api/legacy-client";import { exportFormatPng } from "metabase/common/types/export";import { waitUntilNextFramePainted } from "metabase/common/utils/wait-until-next-frame-paints";import { trackExportDashboardToPDF } from "metabase/dashboard/analytics";diff --git a/frontend/src/metabase/redux/downloads.unit.spec.ts b/frontend/src/metabase/redux/downloads.unit.spec.tsindex 2d11178c378..73428e45bc5 100644--- a/frontend/src/metabase/redux/downloads.unit.spec.ts+++ b/frontend/src/metabase/redux/downloads.unit.spec.ts@@ -1,4 +1,4 @@-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";import Question from "metabase-lib/v1/Question";import type { EntityToken } from "metabase-types/api/entity";@@ -32,7 +32,7 @@ describe("getDatasetResponse", () => {describe("subpath deployment", () => {/*** We will assert that the result is a relative path without subpath.- * Because this URL will be pass to `frontend/src/metabase/api/legacy-client.ts`+ * Because this URL will be pass to `frontend/src/metabase/api/client`* which already takes care of the subpath (api.basename)*/const origin = "http://localhost";diff --git a/frontend/src/metabase/urls/utils.ts b/frontend/src/metabase/urls/utils.tsindex 24186eefffa..c114fd43d84 100644--- a/frontend/src/metabase/urls/utils.ts+++ b/frontend/src/metabase/urls/utils.ts@@ -1,4 +1,4 @@-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";export function appendSlug(path: string | number, slug?: string) {return slug ? `${path}-${slug}` : String(path);diff --git a/frontend/src/metabase/urls/utils.unit.spec.ts b/frontend/src/metabase/urls/utils.unit.spec.tsindex 44cc24bd137..ab18db6af05 100644--- a/frontend/src/metabase/urls/utils.unit.spec.ts+++ b/frontend/src/metabase/urls/utils.unit.spec.ts@@ -1,4 +1,4 @@-import api from "metabase/api/legacy-client";+import { api } from "metabase/api/client";import {getSubpathSafeUrl,diff --git a/frontend/src/metabase/utils/retry.ts b/frontend/src/metabase/utils/retry.tsnew file mode 100644index 00000000000..b5466180e58--- /dev/null+++ b/frontend/src/metabase/utils/retry.ts@@ -0,0 +1,64 @@+import { delay } from "metabase/utils/promise";++export type RetryOptions = {+ /**+ * Maximum number of retries after the initial attempt.+ * Total attempts will be `maxRetries + 1`.+ */+ maxRetries: number;+ /**+ * Predicate that decides whether to retry. Receives the error and the+ * 0-indexed attempt number that just failed (0 = first attempt failed).+ */+ shouldRetry: (error: unknown, attempt: number) => boolean;+ /**+ * Milliseconds to wait before the next retry. Receives the 0-indexed+ * attempt number that just failed. Defaults to `exponentialBackoff()`+ * (1s, 2s, 4s, 8s, ...).+ */+ delayMs?: (attempt: number) => number;+ /**+ * When provided, aborting short-circuits the loop: an in-flight backoff+ * wait ends early and the loop throws the signal's abort reason (an+ * `AbortError` by default) instead of making another attempt. An+ * already-aborted signal throws before `fn` is ever called.+ */+ signal?: AbortSignal;+};++/**+ * Exponential backoff schedule: `baseMs * 2^attempt`.+ * With the default base of 1000ms produces 1s, 2s, 4s, 8s, ...+ */+export function exponentialBackoff(+ baseMs: number = 1000,+): (attempt: number) => number {+ return (attempt) => baseMs * Math.pow(2, attempt);+}++const DEFAULT_DELAY_MS = exponentialBackoff();++/**+ * Run `fn()` with retries.+ *+ * On error, asks `shouldRetry(error, attempt)`. If true and the retry budget+ * allows, waits `delayMs(attempt)` and tries again. Otherwise rethrows.+ */+export async function retry<T>(+ fn: () => Promise<T>,+ { maxRetries, shouldRetry, delayMs = DEFAULT_DELAY_MS, signal }: RetryOptions,+): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ // Bail before each attempt if aborted — including right after an+ // interrupted backoff — rather than making another call to `fn`.+ signal?.throwIfAborted();+ try {+ return await fn();+ } catch (error) {+ if (!shouldRetry(error, attempt) || attempt >= maxRetries) {+ throw error;+ }+ await delay(delayMs(attempt), signal);+ }+ }+}diff --git a/frontend/src/metabase/utils/retry.unit.spec.ts b/frontend/src/metabase/utils/retry.unit.spec.tsnew file mode 100644index 00000000000..e8077254db0--- /dev/null+++ b/frontend/src/metabase/utils/retry.unit.spec.ts@@ -0,0 +1,207 @@+import { exponentialBackoff, retry } from "./retry";++describe("retry", () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it("returns the result on first success without retrying", async () => {+ const fn = jest.fn().mockResolvedValue("ok");++ const result = await retry(fn, {+ maxRetries: 3,+ shouldRetry: () => true,+ delayMs: () => 0,+ });++ expect(result).toBe("ok");+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it("retries until success and returns the eventual result", async () => {+ const fn = jest+ .fn()+ .mockRejectedValueOnce(new Error("first"))+ .mockRejectedValueOnce(new Error("second"))+ .mockResolvedValue("third-success");++ const promise = retry(fn, {+ maxRetries: 5,+ shouldRetry: () => true,+ delayMs: () => 0,+ });++ await jest.runAllTimersAsync();+ const result = await promise;++ expect(result).toBe("third-success");+ expect(fn).toHaveBeenCalledTimes(3);+ });++ it("rethrows immediately when shouldRetry returns false", async () => {+ const error = new Error("nope");+ const fn = jest.fn().mockRejectedValue(error);++ await expect(+ retry(fn, {+ maxRetries: 3,+ shouldRetry: () => false,+ delayMs: () => 0,+ }),+ ).rejects.toBe(error);++ expect(fn).toHaveBeenCalledTimes(1);+ });++ it("throws after exhausting maxRetries retries (maxRetries + 1 total attempts)", async () => {+ const error = new Error("flaky");+ const fn = jest.fn().mockRejectedValue(error);++ const promise = retry(fn, {+ maxRetries: 3,+ shouldRetry: () => true,+ delayMs: () => 0,+ });++ // Swallow the eventual rejection so jest doesn't see an unhandled rejection+ const resultPromise = promise.catch((e: unknown) => e);++ await jest.runAllTimersAsync();+ const result = await resultPromise;++ expect(result).toBe(error);+ // 1 initial attempt + 3 retries = 4 calls+ expect(fn).toHaveBeenCalledTimes(4);+ });++ it("passes the error and attempt index to shouldRetry", async () => {+ const shouldRetry = jest+ .fn<boolean, [unknown, number]>()+ .mockReturnValue(true);+ const fn = jest+ .fn()+ .mockRejectedValueOnce(new Error("a"))+ .mockRejectedValueOnce(new Error("b"))+ .mockResolvedValue("ok");++ const promise = retry(fn, {+ maxRetries: 5,+ shouldRetry,+ delayMs: () => 0,+ });++ await jest.runAllTimersAsync();+ await promise;++ expect(shouldRetry).toHaveBeenNthCalledWith(1, expect.any(Error), 0);+ expect(shouldRetry).toHaveBeenNthCalledWith(2, expect.any(Error), 1);+ });++ it("defaults to exponential backoff when delayMs is omitted", async () => {+ const fn = jest+ .fn()+ .mockRejectedValueOnce(new Error("a"))+ .mockResolvedValue("ok");++ const promise = retry(fn, {+ maxRetries: 3,+ shouldRetry: () => true,+ });++ // First retry waits 1000ms (exponentialBackoff()(0)). Before that timer+ // fires, fn should only have been called once.+ await Promise.resolve();+ expect(fn).toHaveBeenCalledTimes(1);++ await jest.advanceTimersByTimeAsync(1000);+ expect(await promise).toBe("ok");+ expect(fn).toHaveBeenCalledTimes(2);+ });++ it("ends the backoff early and throws the abort reason instead of retrying", async () => {+ const error = new Error("flaky");+ const fn = jest.fn().mockRejectedValue(error);+ const controller = new AbortController();++ const promise = retry(fn, {+ maxRetries: 5,+ shouldRetry: () => true,+ delayMs: () => 1000,+ signal: controller.signal,+ });+ const resultPromise = promise.catch((e: unknown) => e);++ // First attempt fails and schedules a 1000ms backoff.+ await Promise.resolve();+ expect(fn).toHaveBeenCalledTimes(1);++ // Aborting ends the backoff early and stops the loop without another+ // attempt; the signal's abort reason is thrown.+ controller.abort();+ await jest.runAllTimersAsync();++ const result = await resultPromise;+ expect(result).toBeInstanceOf(DOMException);+ expect((result as DOMException).name).toBe("AbortError");+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it("throws without ever calling fn when the signal is already aborted", async () => {+ const fn = jest.fn().mockResolvedValue("ok");+ const controller = new AbortController();+ controller.abort();++ await expect(+ retry(fn, {+ maxRetries: 5,+ shouldRetry: () => true,+ delayMs: () => 0,+ signal: controller.signal,+ }),+ ).rejects.toBeInstanceOf(DOMException);++ expect(fn).not.toHaveBeenCalled();+ });++ it("waits delayMs(attempt) between attempts", async () => {+ const fn = jest+ .fn()+ .mockRejectedValueOnce(new Error("a"))+ .mockRejectedValueOnce(new Error("b"))+ .mockResolvedValue("ok");+ const delayMs = jest.fn((attempt: number) => (attempt + 1) * 100);++ const promise = retry(fn, {+ maxRetries: 5,+ shouldRetry: () => true,+ delayMs,+ });++ await jest.runAllTimersAsync();+ await promise;++ expect(delayMs).toHaveBeenNthCalledWith(1, 0);+ expect(delayMs).toHaveBeenNthCalledWith(2, 1);+ });+});++describe("exponentialBackoff", () => {+ it("doubles each attempt with the default 1000ms base", () => {+ const delayMs = exponentialBackoff();+ expect(delayMs(0)).toBe(1000);+ expect(delayMs(1)).toBe(2000);+ expect(delayMs(2)).toBe(4000);+ expect(delayMs(9)).toBe(512_000);+ });++ it("accepts a custom base", () => {+ const delayMs = exponentialBackoff(50);+ expect(delayMs(0)).toBe(50);+ expect(delayMs(1)).toBe(100);+ expect(delayMs(4)).toBe(800);+ });+});diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsxindex 6d7be5dc83b..4eb1fd9e0ad 100644--- a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx+++ b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx@@ -185,12 +185,10 @@ export class LeafletTilePinMap extends LeafletMap<LeafletTilePinMapProps> {const controller = new AbortController();tile._fetchCtrl = controller;- (- GET(tileUrl, {- signal: controller.signal,- rawResponse: true,- })() as Promise<Response>- )+ GET(tileUrl, {+ signal: controller.signal,+ rawResponse: true,+ })().then((response) => response.blob()).then((blob) => {const reader = new FileReader();