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
feat(embed-js): Add analytics to Embedded Analytics JS (#63580)
Mahatthana (Kelvin) Nomsawadi4ef96bd73aaa
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.tsindex 5e60ab04964..4e428e16b21 100644--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts@@ -29,15 +29,7 @@ export interface BaseEmbedTestPageOptions {locale?: string;};- // The element to embed- element: "metabase-dashboard" | "metabase-question";-- // Attributes passed serialized to the element- attributes: {- dashboardId?: number | string;- questionId?: number | string;- [key: string]: any;- };+ elements: MetabaseElement[];// Options for the test pageorigin?: string;@@ -50,6 +42,17 @@ export interface BaseEmbedTestPageOptions {onVisitPage?(): void;}+export interface MetabaseElement {+ // The component to embed+ component: "metabase-dashboard" | "metabase-question" | "metabase-browser";++ // Attributes passed serialized to the element+ attributes: {+ dashboardId?: number | string;+ questionId?: number | string;+ [key: string]: any;+ };+}export const waitForSimpleEmbedIframesToLoad = (n: number = 1) => {cy.get("iframe[data-metabase-embed]").should("have.length", n);cy.get("iframe[data-iframe-loaded]").should("have.length", n, {@@ -113,8 +116,7 @@ export function loadSdkIframeEmbedTestPage({function getSdkIframeEmbedHtml({insertHtml,metabaseConfig,- element,- attributes,+ elements,}: BaseEmbedTestPageOptions) {return `<!DOCTYPE html>@@ -138,8 +140,13 @@ function getSdkIframeEmbedHtml({${getNewEmbedConfigurationScript(metabaseConfig)}${insertHtml?.beforeEmbed ?? ""}-- <${element} ${convertPropertiesToEmbedTagAttributes(attributes)} />+ ${elements+ .map(+ ({ component, attributes }) => `+ <${component} ${convertPropertiesToEmbedTagAttributes(attributes)} />+ `,+ )+ .join("\n")}${insertHtml?.afterEmbed ?? ""}</body>@@ -148,7 +155,7 @@ function getSdkIframeEmbedHtml({}const convertPropertiesToEmbedTagAttributes = (- attributes: BaseEmbedTestPageOptions["attributes"],+ attributes: MetabaseElement["attributes"],) => {return Object.entries(attributes).map(([key, value]) => {diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.tsindex c85f8d592ba..0afcf0c5844 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts@@ -11,10 +11,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],});frame.within(() => {@@ -28,10 +32,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: false });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {useExistingUserSession: true,},@@ -44,10 +52,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: false });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {useExistingUserSession: false,},@@ -68,10 +80,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],});assertDashboardLoaded(frame);@@ -82,10 +98,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],onVisitPage: () => stubWindowOpenForSamlPopup(),});@@ -97,10 +117,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],onVisitPage: () => stubWindowOpenForSamlPopup({ isUserValid: false }),});@@ -126,11 +150,15 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>cy.log("visit a test page with an origin of example.com using api keys");cy.get<string>("@apiKey").then((apiKey) => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],origin: "http://example.com",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },metabaseConfig: {apiKey,},@@ -154,11 +182,15 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>"visit a test page with an origin of example.com using the existing user session",);const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],origin: "http://example.com",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },metabaseConfig: {useExistingUserSession: true,},@@ -181,10 +213,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>cy.get<string>("@apiKey").then((apiKey) => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {apiKey,},@@ -207,10 +243,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>});const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {preferredAuthMethod: "jwt",},@@ -229,10 +269,14 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>});const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {preferredAuthMethod: "saml",},diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.tsindex 787dad6a111..896f698c723 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/embed-options.cy.spec.ts@@ -13,11 +13,15 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("shows a static question with drills=false", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- drills: false,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ drills: false,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -36,12 +40,16 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("shows a static question with drills=false, withTitle=true", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- drills: false,- withTitle: true,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ drills: false,+ withTitle: true,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -57,13 +65,17 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("shows a static dashboard using drills=false, withTitle=false, withDownloads=true", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- drills: false,- withTitle: false,- withDownloads: true,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ drills: false,+ withTitle: false,+ withDownloads: true,+ },+ },+ ],});cy.wait("@getDashCardQuery");@@ -86,13 +98,17 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("renders an interactive question with drills=true, withTitle=false, withDownloads=true", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- drills: true,- withDownloads: true,- withTitle: false,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ drills: true,+ withDownloads: true,+ withTitle: false,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -119,13 +135,17 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("renders an interactive dashboard with drills=true, withDownloads=true, withTitle=false", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- drills: true,- withDownloads: true,- withTitle: false,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ drills: true,+ withDownloads: true,+ withTitle: false,+ },+ },+ ],});cy.wait("@getDashCardQuery");@@ -155,13 +175,17 @@ describe("scenarios > embedding > sdk iframe embed options passthrough", () => {it("renders the exploration template with isSaveEnabled=true, targetCollection, entityTypes", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: "new",- isSaveEnabled: true,- targetCollection: FIRST_COLLECTION_ID,- entityTypes: ["table"],- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ isSaveEnabled: true,+ targetCollection: FIRST_COLLECTION_ID,+ entityTypes: ["table"],+ },+ },+ ],});frame.within(() => {diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.tsindex 7c2edd03ee3..8d8c0ce6d2d 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts@@ -17,11 +17,15 @@ describe("scenarios > embedding > sdk iframe embedding > without token features"cy.get<string>("@apiKey").then((apiKey) => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ },+ },+ ],origin: "http://example.com",- attributes: {- questionId: "new",- },metabaseConfig: {apiKey,},@@ -36,10 +40,14 @@ describe("scenarios > embedding > sdk iframe embedding > without token features"it("does not show an error if the token features are missing and the parent page is localhost", () => {cy.get<string>("@apiKey").then((apiKey) => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: "new",- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ },+ },+ ],metabaseConfig: {apiKey,},diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.tsindex cffeef476e4..baa81bea568 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts@@ -22,10 +22,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("uses the embedding-simple client request header", () => {H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],});cy.wait("@getDashCardQuery").then(({ request }) => {@@ -37,10 +41,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("displays a dashboard", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],});cy.wait("@getDashCardQuery");@@ -54,10 +62,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("displays a question", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -69,10 +81,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("displays a dashboard using entity id", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ENTITY_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ENTITY_ID,+ },+ },+ ],});cy.wait("@getDashCardQuery");@@ -86,10 +102,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("displays a question using entity id", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ENTITY_ID,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ENTITY_ID,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -101,10 +121,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("displays the exploration template", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: "new",- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ },+ },+ ],});frame.within(() => {@@ -117,10 +141,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("applies the provided locale", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {locale: "de",},@@ -133,10 +161,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("updates the question id with embed.setAttribute", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ },+ },+ ],});cy.wait("@getCardQuery");@@ -168,10 +200,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("fires ready event after iframe is loaded", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: ORDERS_QUESTION_ID,- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ },+ },+ ],onVisitPage: () => {cy.window().then((win) => {const element = win.document!.querySelector("metabase-question")!;@@ -206,11 +242,15 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("shows dashboard title when updateSettings({ withTitle: true }) is called", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- withTitle: false,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ withTitle: false,+ },+ },+ ],});cy.wait("@getDashCardQuery");@@ -233,10 +273,14 @@ describe("scenarios > embedding > sdk iframe embedding", () => {it("CSP nonces are set for custom expression styles (EMB-707)", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-question",- attributes: {- questionId: "new",- },+ elements: [+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ },+ },+ ],});frame.within(() => {@@ -266,6 +310,104 @@ describe("scenarios > embedding > sdk iframe embedding", () => {});});+H.describeWithSnowplowEE(+ "scenarios > embedding > embedded analytics JS",+ () => {+ beforeEach(() => {+ H.resetSnowplow();+ H.prepareSdkIframeEmbedTest({ signOut: false });+ H.enableTracking();+ cy.signOut();+ });++ it("should send an Embedded Analytics JS usage event", () => {+ const frame = H.loadSdkIframeEmbedTestPage({+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ {+ component: "metabase-question",+ attributes: {+ questionId: ORDERS_QUESTION_ID,+ },+ },+ {+ component: "metabase-question",+ attributes: {+ questionId: "new",+ },+ },+ {+ component: "metabase-browser",+ attributes: {},+ },+ ],+ });++ frame.within(() => {+ cy.findByText("Orders in a dashboard").should("be.visible");+ cy.findByText("Orders").should("be.visible");+ H.assertTableRowsCount(2000);+ });++ H.expectUnstructuredSnowplowEvent({+ event: "setup",+ global: {+ auth_method: "sso",+ },+ dashboard: {+ with_title: {+ false: 0,+ true: 1,+ },+ with_downloads: {+ false: 1,+ true: 0,+ },+ drills: {+ false: 0,+ true: 1,+ },+ },+ question: {+ drills: {+ false: 0,+ true: 1,+ },+ with_downloads: {+ false: 1,+ true: 0,+ },+ with_title: {+ false: 0,+ true: 1,+ },+ is_save_enabled: {+ false: 1,+ true: 0,+ },+ },+ exploration: {+ is_save_enabled: {+ false: 1,+ true: 0,+ },+ },+ browser: {+ read_only: {+ false: 0,+ true: 1,+ },+ },+ });+ });+ },+);+const getIframeWindow = () =>cy.get("iframe")diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.tsindex c45155441b5..05c6f5fce8c 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/theming.cy.spec.ts@@ -33,10 +33,14 @@ describe("scenarios > embedding > sdk iframe embedding > theming", () => {it("should apply custom themes", () => {const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {theme: DARK_THEME,},@@ -87,10 +91,14 @@ describe("scenarios > embedding > sdk iframe embedding > theming", () => {`;const frame = H.loadSdkIframeEmbedTestPage({- element: "metabase-dashboard",- attributes: {- dashboardId: ORDERS_DASHBOARD_ID,- },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],metabaseConfig: {theme: LIGHT_THEME,},diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.tsnew file mode 100644index 00000000000..c5fb8d78705--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.ts@@ -0,0 +1,204 @@+import { assocIn, getIn, updateIn } from "icepick";+import { P, match } from "ts-pattern";+import _ from "underscore";++import type { FlattenObjectKeys } from "metabase/embedding-sdk/types/utils";+import type {+ AUTH_TYPES,+ DefaultValues,+ EmbeddedAnalyticsJsEventSchema,+} from "metabase-types/analytics/embedded-analytics-js";++import type { MetabaseEmbedElement } from "./embed";++const DEFAULT_VALUES: DefaultValues = {+ dashboard: {+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx#L119} */+ drills: true,+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx#L129} */+ with_downloads: false,+ /** @see {@link https://github.com/metabase/metabase/blob/master/enterprise/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx#L127} */+ with_title: true,+ },+ question: {+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx#L149} */+ drills: true,+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx#L129} */+ with_downloads: false,+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx#L145} */+ with_title: true,+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx#L157} */+ is_save_enabled: false,+ },+ exploration: {+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx#L157} */+ is_save_enabled: false,+ },+ browser: {+ /** @see {@link https://github.com/metabase/metabase/blob/7aa3f7fed11113ed32901aad4e4227be68cff78f/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/MetabaseBrowser.tsx#L39} */+ read_only: true,+ },+};++const SECOND = 1000;++/**+ * Because the way it's designed to be consumed when each embed is being registered. There could be multiple embed in a page, so we want to debounce and only call this once.+ */+export const debouncedReportAnalytics = _.debounce(+ reportAnalyticsOnce,+ 1 * SECOND,+);++/**+ * This is just a safe-guard to ensure we only call this once for whatever reason.+ */+let isAnalyticsReported = false;+function reportAnalyticsOnce(activeEmbeds: Set<MetabaseEmbedElement>) {+ if (!isAnalyticsReported) {+ isAnalyticsReported = true;+ const [firstEmbed] = activeEmbeds;+ firstEmbed.sendMessage(+ "metabase.embed.reportAnalytics",+ createEmbeddedAnalyticsJsUsage(activeEmbeds),+ );+ }+}++export function createEmbeddedAnalyticsJsUsage(+ activeEmbeds: Set<MetabaseEmbedElement>,+): EmbeddedAnalyticsJsEventSchema {+ const [firstEmbed] = activeEmbeds;+ let usage = {+ event: "setup",+ global: {+ auth_method: getAuthMethod(firstEmbed),+ },+ } as EmbeddedAnalyticsJsEventSchema;++ activeEmbeds.forEach((embed) => {+ match(embed.properties)+ .with({ componentName: "metabase-dashboard" }, (properties) => {+ if (!usage.dashboard) {+ usage = assocIn(usage, ["dashboard"], {+ drills: { true: 0, false: 0 },+ with_downloads: { true: 0, false: 0 },+ with_title: { true: 0, false: 0 },+ });+ }+ usage = incrementComponentPropertyCount(+ "dashboard.drills",+ properties.drills,+ usage,+ );+ usage = incrementComponentPropertyCount(+ "dashboard.with_downloads",+ properties.withDownloads,+ usage,+ );+ usage = incrementComponentPropertyCount(+ "dashboard.with_title",+ properties.withTitle,+ usage,+ );+ })+ .with(+ { componentName: "metabase-question", questionId: "new" },+ (properties) => {+ if (!usage.exploration) {+ usage = assocIn(usage, ["exploration"], {+ is_save_enabled: { true: 0, false: 0 },+ });+ }+ usage = incrementComponentPropertyCount(+ "exploration.is_save_enabled",+ properties.isSaveEnabled,+ usage,+ );+ },+ )+ .with(+ {+ componentName: "metabase-question",+ },+ (properties) => {+ if (!usage.question) {+ usage = assocIn(usage, ["question"], {+ drills: { true: 0, false: 0 },+ with_downloads: { true: 0, false: 0 },+ with_title: { true: 0, false: 0 },+ is_save_enabled: { true: 0, false: 0 },+ });+ }+ usage = incrementComponentPropertyCount(+ "question.drills",+ properties.drills,+ usage,+ );+ usage = incrementComponentPropertyCount(+ "question.with_downloads",+ properties.withDownloads,+ usage,+ );+ usage = incrementComponentPropertyCount(+ "question.with_title",+ properties.withTitle,+ usage,+ );+ usage = incrementComponentPropertyCount(+ "question.is_save_enabled",+ properties.isSaveEnabled,+ usage,+ );+ },+ )+ .with({ componentName: "metabase-browser" }, (properties) => {+ if (!usage.browser) {+ usage = assocIn(usage, ["browser"], {+ read_only: { true: 0, false: 0 },+ });+ }+ usage = incrementComponentPropertyCount(+ "browser.read_only",+ properties.readOnly,+ usage,+ );+ });+ });++ return usage;+}++function getAuthMethod(firstEmbed: MetabaseEmbedElement): AUTH_TYPES {+ return match(firstEmbed.properties)+ .returnType<AUTH_TYPES>()+ .with(+ {+ useExistingUserSession: true,+ },+ () => "session",+ )+ .with(+ {+ apiKey: P.string,+ },+ () => "api_key",+ )+ .otherwise(() => {+ return "sso";+ });+}++function incrementComponentPropertyCount(+ propertyPath: FlattenObjectKeys<DefaultValues>,+ value: any | undefined,+ usage: EmbeddedAnalyticsJsEventSchema,+) {+ const path = propertyPath.split(".");++ return updateIn(+ usage,+ [...path, String(value ?? getIn(DEFAULT_VALUES, path))],+ (value) => value + 1,+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.unit.spec.tsxnew file mode 100644index 00000000000..59189e86cad--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/analytics.unit.spec.tsx@@ -0,0 +1,432 @@+// Ensure the custom elements are registered+import "metabase-enterprise/embedding_iframe_sdk/embed";+import type { MetabaseEmbedElement } from "metabase-enterprise/embedding_iframe_sdk/embed";++import { createEmbeddedAnalyticsJsUsage } from "./analytics";+import type { SdkIframeEmbedBaseSettings } from "./types/embed";++const defineMetabaseConfig = (config: SdkIframeEmbedBaseSettings) => {+ (window as any).metabaseConfig = config;+};++describe("createEmbeddedAnalyticsJsUsage", () => {+ beforeEach(() => {+ // clean up window.metabaseConfig+ delete (window as any).metabaseConfig;+ });++ describe("Metabase configuration", () => {+ it('should capture "session" auth method', () => {+ defineMetabaseConfig({+ useExistingUserSession: true,+ instanceUrl: "https://example.com",+ });++ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([createEmbeddedAnalyticsJsElement("metabase-question")]),+ ),+ ).toEqual(+ expect.objectContaining({+ global: {+ auth_method: "session",+ },+ }),+ );+ });++ it('should capture "api_key" auth method', () => {+ defineMetabaseConfig({+ useExistingUserSession: false,+ apiKey: "blabla",+ instanceUrl: "https://example.com",+ });++ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([createEmbeddedAnalyticsJsElement("metabase-question")]),+ ),+ ).toEqual(+ expect.objectContaining({+ global: {+ auth_method: "api_key",+ },+ }),+ );+ });++ it('should capture "sso" auth method', () => {+ defineMetabaseConfig({+ instanceUrl: "https://example.com",+ });++ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([createEmbeddedAnalyticsJsElement("metabase-question")]),+ ),+ ).toEqual(+ expect.objectContaining({+ global: {+ auth_method: "sso",+ },+ }),+ );+ });+ });++ describe("Component usage", () => {+ describe("dashboard", () => {+ it("should count default values", () => {+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([createEmbeddedAnalyticsJsElement("metabase-dashboard")]),+ ),+ ).toEqual(+ expect.objectContaining({+ dashboard: {+ drills: { true: 1, false: 0 },+ with_downloads: { true: 0, false: 1 },+ with_title: { true: 1, false: 0 },+ },+ }),+ );+ });++ it("should count properties correctly", () => {+ // Explicit default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-dashboard", {+ drills: true,+ "with-downloads": false,+ "with-title": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ dashboard: {+ drills: { true: 1, false: 0 },+ with_downloads: { true: 0, false: 1 },+ with_title: { true: 1, false: 0 },+ },+ }),+ );++ // Flip the default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-dashboard", {+ drills: false,+ "with-downloads": true,+ "with-title": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ dashboard: {+ drills: { true: 0, false: 1 },+ with_downloads: { true: 1, false: 0 },+ with_title: { true: 0, false: 1 },+ },+ }),+ );++ // Multiple components+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-dashboard"),+ createEmbeddedAnalyticsJsElement("metabase-dashboard"),+ createEmbeddedAnalyticsJsElement("metabase-dashboard", {+ drills: false,+ "with-downloads": true,+ "with-title": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ dashboard: {+ drills: { true: 2, false: 1 },+ with_downloads: { true: 1, false: 2 },+ with_title: { true: 2, false: 1 },+ },+ }),+ );+ });+ });++ describe("question", () => {+ it("should count default values", () => {+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": 1,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ question: {+ drills: { true: 1, false: 0 },+ with_downloads: { true: 0, false: 1 },+ with_title: { true: 1, false: 0 },+ is_save_enabled: { true: 0, false: 1 },+ },+ }),+ );+ });++ it("should count properties correctly", () => {+ // Explicit default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": 1,+ drills: true,+ "with-downloads": false,+ "with-title": true,+ "is-save-enabled": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ question: {+ drills: { true: 1, false: 0 },+ with_downloads: { true: 0, false: 1 },+ with_title: { true: 1, false: 0 },+ is_save_enabled: { true: 0, false: 1 },+ },+ }),+ );++ // Flip the default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": 1,+ drills: false,+ "with-downloads": true,+ "with-title": false,+ "is-save-enabled": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ question: {+ drills: { true: 0, false: 1 },+ with_downloads: { true: 1, false: 0 },+ with_title: { true: 0, false: 1 },+ is_save_enabled: { true: 1, false: 0 },+ },+ }),+ );++ // Multiple components+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question"),+ createEmbeddedAnalyticsJsElement("metabase-question"),+ createEmbeddedAnalyticsJsElement("metabase-question", {+ drills: false,+ "with-downloads": true,+ "with-title": false,+ "is-save-enabled": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ question: {+ drills: { true: 2, false: 1 },+ with_downloads: { true: 1, false: 2 },+ with_title: { true: 2, false: 1 },+ is_save_enabled: { true: 1, false: 2 },+ },+ }),+ );+ });+ });++ describe("question with exploration", () => {+ it("should count default values", () => {+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ exploration: {+ is_save_enabled: { true: 0, false: 1 },+ },+ }),+ );+ });++ it("should count question components with exploration", () => {+ // Explicit default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ "is-save-enabled": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ exploration: {+ is_save_enabled: { true: 0, false: 1 },+ },+ }),+ );++ // Flip the default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ "is-save-enabled": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ exploration: {+ is_save_enabled: { true: 1, false: 0 },+ },+ }),+ );++ // Multiple components+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ }),+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ }),+ createEmbeddedAnalyticsJsElement("metabase-question", {+ "question-id": "new",+ "is-save-enabled": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ exploration: {+ is_save_enabled: { true: 1, false: 2 },+ },+ }),+ );+ });+ });++ describe("browser", () => {+ it("should count default values", () => {+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([createEmbeddedAnalyticsJsElement("metabase-browser")]),+ ),+ ).toEqual(+ expect.objectContaining({+ browser: {+ read_only: { true: 1, false: 0 },+ },+ }),+ );+ });++ it("should count properties correctly", () => {+ // Explicit default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-browser", {+ "read-only": true,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ browser: {+ read_only: { true: 1, false: 0 },+ },+ }),+ );++ // Flip the default values+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-browser", {+ "read-only": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ browser: {+ read_only: { true: 0, false: 1 },+ },+ }),+ );++ // Multiple components+ expect(+ createEmbeddedAnalyticsJsUsage(+ new Set([+ createEmbeddedAnalyticsJsElement("metabase-browser"),+ createEmbeddedAnalyticsJsElement("metabase-browser"),+ createEmbeddedAnalyticsJsElement("metabase-browser", {+ "read-only": false,+ }),+ ]),+ ),+ ).toEqual(+ expect.objectContaining({+ browser: {+ read_only: { true: 2, false: 1 },+ },+ }),+ );+ });+ });+ });+});++type Component =+ | "metabase-dashboard"+ | "metabase-question"+ | "metabase-browser";+function createEmbeddedAnalyticsJsElement(+ componentName: Component,+ properties: Record<string, any> = {},+): MetabaseEmbedElement {+ const component = document.createElement(+ componentName,+ ) as MetabaseEmbedElement;+ Object.entries(properties).forEach(([key, value]) => {+ component.setAttribute(key, value);+ });++ return component;+}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsxindex fe03da59c2b..a66589bce02 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/components/SdkIframeEmbedRoute.tsx@@ -9,8 +9,10 @@ import {InteractiveDashboard,StaticDashboard,} from "embedding-sdk-bundle/components/public/dashboard";+import { getSdkStore } from "embedding-sdk-bundle/store";import type { MetabaseAuthConfig } from "embedding-sdk-package";import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";+import { createTracker } from "metabase/lib/analytics-untyped";import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";import { Box } from "metabase/ui";@@ -31,6 +33,9 @@ const onSettingsChanged = (settings: SdkIframeEmbedSettings) => {settings?.useExistingUserSession || false;};+const store = getSdkStore();+createTracker(store);+export const SdkIframeEmbedRoute = () => {const { embedSettings } = useSdkIframeEmbedEventBus({ onSettingsChanged });@@ -68,7 +73,12 @@ export const SdkIframeEmbedRoute = () => {};return (- <ComponentProvider authConfig={authConfig} theme={theme} locale={locale}>+ <ComponentProvider+ authConfig={authConfig}+ theme={theme}+ locale={locale}+ reduxStore={store}+ ><Box h="100vh" bg={theme?.colors?.background}><SdkIframeEmbedView settings={embedSettings} /></Box>diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.tsindex e046e540ab7..01c985cceeb 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts@@ -9,11 +9,13 @@ import {MetabaseError,} from "embedding-sdk-bundle/errors";+import { debouncedReportAnalytics } from "./analytics";import {ALLOWED_EMBED_SETTING_KEYS_MAP,DISABLE_UPDATE_FOR_KEYS,} from "./constants";import type {+ SdkIframeEmbedElementSettings,SdkIframeEmbedEvent,SdkIframeEmbedEventHandler,SdkIframeEmbedMessage,@@ -67,7 +69,9 @@ const setupConfigWatcher = () => {}};-export const updateAllEmbeds = (config: Partial<SdkIframeEmbedSettings>) => {+export const updateAllEmbeds = (+ config: Partial<SdkIframeEmbedElementSettings>,+) => {assertFieldCanBeUpdated(config);_activeEmbeds.forEach((embedElement) => {@@ -77,6 +81,7 @@ export const updateAllEmbeds = (config: Partial<SdkIframeEmbedSettings>) => {const registerEmbed = (embed: MetabaseEmbedElement) => {_activeEmbeds.add(embed);+ debouncedReportAnalytics(_activeEmbeds);};const unregisterEmbed = (embed: MetabaseEmbedElement) => {@@ -91,7 +96,9 @@ const raiseError = (message: string) => {throw new MetabaseError("EMBED_ERROR", message);};-function assertFieldCanBeUpdated(newValues: Partial<SdkIframeEmbedSettings>) {+function assertFieldCanBeUpdated(+ newValues: Partial<SdkIframeEmbedElementSettings>,+) {const currentConfig = (window as any).metabaseConfig || {};for (const field of DISABLE_UPDATE_FOR_KEYS) {if (@@ -108,7 +115,7 @@ type AllowedMetabaseConfigKey =(typeof ALLOWED_EMBED_SETTING_KEYS_MAP.base)[number];function assertValidMetabaseConfigField(- newValues: Partial<SdkIframeEmbedSettings>,+ newValues: Partial<SdkIframeEmbedElementSettings>,) {for (const field in newValues) {if (@@ -139,7 +146,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {}// returns the attributes converted to camelCase + global settings- get properties(): SdkIframeEmbedSettings {+ get properties(): SdkIframeEmbedElementSettings {const attributesConverted = this._attributeNames.reduce((acc, attr) => {const attrValue = this.getAttribute(attr as string);@@ -157,7 +164,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {...attributesConverted,componentName: this._componentName,_isLocalhost: this._getIsLocalhost(),- } as SdkIframeEmbedSettings;+ } as SdkIframeEmbedElementSettings;}addEventListener(@@ -220,11 +227,11 @@ export abstract class MetabaseEmbedElement extends HTMLElement {/*** Send a message with the new settings*/- _updateSettings(settings: Partial<SdkIframeEmbedSettings>) {+ _updateSettings(settings: Partial<SdkIframeEmbedElementSettings>) {const newValues = {...this.properties,...settings,- } as SdkIframeEmbedSettings;+ } as SdkIframeEmbedElementSettings;// If the iframe isn't ready yet, don't send the message now.if (!this._isEmbedReady) {@@ -234,7 +241,11 @@ export abstract class MetabaseEmbedElement extends HTMLElement {this._validateEmbedSettings(newValues);// Iframe is ready – propagate the delta- this._sendMessage("metabase.embed.setSettings", newValues);+ this.sendMessage(+ "metabase.embed.setSettings",+ // When we properly fix the type for Exploration template which uses `questionId: "new"` on the custom element, we should remove this type casting.+ newValues as SdkIframeEmbedSettings,+ );}destroy() {@@ -283,7 +294,9 @@ export abstract class MetabaseEmbedElement extends HTMLElement {return;}- const key = attributeToSettingKey(attrName) as keyof SdkIframeEmbedSettings;+ const key = attributeToSettingKey(+ attrName,+ ) as keyof SdkIframeEmbedElementSettings;if ((DISABLE_UPDATE_FOR_KEYS as readonly string[]).includes(key as string)) {@@ -293,7 +306,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {this._updateSettings({[key]: parseAttributeValue(newVal),- } as Partial<SdkIframeEmbedSettings>);+ } as Partial<SdkIframeEmbedElementSettings>);}private _emitEvent(event: SdkIframeEmbedEvent) {@@ -342,7 +355,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {return hostname === "localhost" || hostname === "127.0.0.1";}- private _validateEmbedSettings(settings: SdkIframeEmbedSettings) {+ private _validateEmbedSettings(settings: SdkIframeEmbedElementSettings) {if (!settings.instanceUrl) {raiseError("instanceUrl must be provided");}@@ -394,7 +407,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {}};- private _sendMessage<Message extends SdkIframeEmbedMessage>(+ sendMessage<Message extends SdkIframeEmbedMessage>(type: Message["type"],data: Message["data"],) {@@ -414,7 +427,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {validateSessionToken(sessionToken);if (sessionToken) {- this._sendMessage("metabase.embed.submitSessionToken", {+ this.sendMessage("metabase.embed.submitSessionToken", {authMethod: method,sessionToken,});@@ -422,7 +435,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {} catch (error) {// if the error is an authentication error, show it to the iframe tooif (error instanceof MetabaseError) {- this._sendMessage("metabase.embed.reportAuthenticationError", {+ this.sendMessage("metabase.embed.reportAuthenticationError", {error,});}diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.tsindex b7ce386ef59..b66233c8509 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/hooks/use-sdk-iframe-embed-event-bus.ts@@ -1,6 +1,7 @@import { useEffect, useState } from "react";import { match } from "ts-pattern";+import { trackSchemaEvent } from "metabase/lib/analytics";import { isWithinIframe } from "metabase/lib/dom";import type {@@ -26,13 +27,14 @@ export function useSdkIframeEmbedEventBus({return;}- match(event.data).with(- { type: "metabase.embed.setSettings" },- ({ data }) => {+ match(event.data)+ .with({ type: "metabase.embed.setSettings" }, ({ data }) => {setEmbedSettings(data);onSettingsChanged?.(data);- },- );+ })+ .with({ type: "metabase.embed.reportAnalytics" }, ({ data }) => {+ trackSchemaEvent("embedded_analytics_js", data);+ });};window.addEventListener("message", messageHandler);diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.tsindex e8210d9b043..3d2d02500a8 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts@@ -9,6 +9,7 @@ import type {SqlParameterValues,} from "embedding-sdk-package";import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";+import type { EmbeddedAnalyticsJsEventSchema } from "metabase-types/analytics/embedded-analytics-js";import type { CollectionId } from "metabase-types/api";/** Events that the embed.js script listens for */@@ -34,6 +35,10 @@ export type SdkIframeEmbedMessage =data: {error: MetabaseError<string, unknown>;};+ }+ | {+ type: "metabase.embed.reportAnalytics";+ data: EmbeddedAnalyticsJsEventSchema;};// --- Embed Option Interfaces ---@@ -149,6 +154,14 @@ export type SdkIframeEmbedTemplateSettings =export type SdkIframeEmbedSettings = SdkIframeEmbedBaseSettings &SdkIframeEmbedTemplateSettings;+export type SdkIframeEmbedElementSettings = SdkIframeEmbedBaseSettings &+ (+ | DashboardEmbedOptions+ | QuestionEmbedOptions+ | (Omit<ExplorationEmbedOptions, "questionId"> & { questionId: "new" })+ | BrowserEmbedOptions+ );+export type SdkIframeEmbedEvent = { type: "ready" };export type SdkIframeEmbedEventHandler = () => void;diff --git a/frontend/src/metabase-types/analytics/embedded-analytics-js.ts b/frontend/src/metabase-types/analytics/embedded-analytics-js.tsnew file mode 100644index 00000000000..dacff1055e7--- /dev/null+++ b/frontend/src/metabase-types/analytics/embedded-analytics-js.ts@@ -0,0 +1,88 @@+export type EmbeddedAnalyticsJsEventSchema = {+ event: EVENTS;+ global: {+ auth_method: AUTH_TYPES;+ };+ dashboard?: {+ drills: BOOLEAN_COUNT;+ with_downloads: BOOLEAN_COUNT;+ with_title: BOOLEAN_COUNT;+ };+ question?: {+ drills: BOOLEAN_COUNT;+ with_downloads: BOOLEAN_COUNT;+ with_title: BOOLEAN_COUNT;+ is_save_enabled: BOOLEAN_COUNT;+ };+ exploration?: {+ is_save_enabled: BOOLEAN_COUNT;+ };+ browser?: {+ read_only: BOOLEAN_COUNT;+ };+};++/**+ * The type of event being recorded. For example, then the Embedded Analytics JS is initialized, or when the Metabase configuration is updated.+ */+type EVENTS = "setup";++/**+ * Authentication method used for the Embedded Analytics JS.+ */+export type AUTH_TYPES = "session" | "api_key" | "sso";++type BOOLEAN_COUNT = {+ true: number;+ false: number;+};++export type DefaultValues = {+ dashboard: Record<+ keyof NonNullable<EmbeddedAnalyticsJsEventSchema["dashboard"]>,+ boolean+ >;+ question: Record<+ keyof NonNullable<EmbeddedAnalyticsJsEventSchema["question"]>,+ boolean+ >;+ exploration: Record<+ keyof NonNullable<EmbeddedAnalyticsJsEventSchema["exploration"]>,+ boolean+ >;+ browser: Record<+ keyof NonNullable<EmbeddedAnalyticsJsEventSchema["browser"]>,+ boolean+ >;+};++type ValidateEvent<+ T extends EmbeddedAnalyticsJsEventSchema &+ Record<Exclude<keyof T, keyof EmbeddedAnalyticsJsEventSchema>, never>,+> = T;++type EmbeddedAnalyticsJsSetupEvent = ValidateEvent<{+ event: "setup";+ global: {+ auth_method: AUTH_TYPES;+ };+ dashboard?: {+ drills: BOOLEAN_COUNT;+ with_downloads: BOOLEAN_COUNT;+ with_title: BOOLEAN_COUNT;+ };+ question?: {+ drills: BOOLEAN_COUNT;+ with_downloads: BOOLEAN_COUNT;+ with_title: BOOLEAN_COUNT;+ is_save_enabled: BOOLEAN_COUNT;+ };+ exploration?: {+ is_save_enabled: BOOLEAN_COUNT;+ };+ browser?: {+ read_only: BOOLEAN_COUNT;+ };+}>;++export type EmbeddedAnalyticsJsEvent = EmbeddedAnalyticsJsSetupEvent;diff --git a/frontend/src/metabase-types/analytics/schema.ts b/frontend/src/metabase-types/analytics/schema.tsindex 804e6931ff3..473e33d9191 100644--- a/frontend/src/metabase-types/analytics/schema.ts+++ b/frontend/src/metabase-types/analytics/schema.ts@@ -8,6 +8,7 @@ import type { DatabaseEvent } from "./database";import type { DownloadsEvent } from "./downloads";import type { EmbedFlowEvent } from "./embed-flow";import type { EmbedShareEvent } from "./embed-share";+import type { EmbeddedAnalyticsJsEvent } from "./embedded-analytics-js";import type { EmbeddingHomepageEvent } from "./embedding-homepage";import type { SimpleEvent } from "./event";import type { InviteEvent } from "./invite";@@ -31,6 +32,7 @@ export type SchemaEventMap = {downloads: DownloadsEvent;embed_flow: EmbedFlowEvent;embed_share: EmbedShareEvent;+ embedded_analytics_js: EmbeddedAnalyticsJsEvent;embedding_homepage: EmbeddingHomepageEvent;simple_event: SimpleEvent;invite: InviteEvent;diff --git a/frontend/src/metabase/lib/analytics.ts b/frontend/src/metabase/lib/analytics.tsindex d2844593939..b47f610f5cb 100644--- a/frontend/src/metabase/lib/analytics.ts+++ b/frontend/src/metabase/lib/analytics.ts@@ -23,6 +23,7 @@ const VERSIONS: Record<SchemaType, SchemaVersion> = {downloads: "1-0-0",embed_flow: "1-0-3",embed_share: "1-0-1",+ embedded_analytics_js: "1-0-0",embedding_homepage: "1-0-0",simple_event: "1-0-0",invite: "1-0-1",diff --git a/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/1-0-0 b/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/1-0-0new file mode 100644index 00000000000..452093212df--- /dev/null+++ b/snowplow/iglu-client-embedded/schemas/com.metabase/embedded_analytics_js/jsonschema/1-0-0@@ -0,0 +1,239 @@+{+ "$schema": "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",+ "description": "Embedded Analytics JS configuration",+ "self": {+ "vendor": "com.metabase",+ "name": "embedded_analytics_js",+ "format": "jsonschema",+ "version": "1-0-0"+ },+ "type": "object",+ "properties": {+ "event": {+ "description": "The type of event being recorded. For example, when the Embedded Analytics JS is initialized, or when the Metabase configuration is updated.",+ "type": "string",+ "enum": [+ "setup"+ ],+ "maxLength": 1024+ },+ "global": {+ "description": "Global configuration for Embedded Analytics JS.",+ "type": "object",+ "properties": {+ "auth_method": {+ "description": "Authentication method used for the Embedded Analytics JS.",+ "type": "string",+ "enum": [+ "session",+ "api_key",+ "sso"+ ],+ "maxLength": 1024+ }+ }+ },+ "dashboard": {+ "description": "Counts of <metabase-dashboard> component properties.",+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "drills": {+ "description": "Counts of dashboards with drills enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of dashboards with drills enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of dashboards with drills disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ },+ "with_downloads": {+ "description": "Counts of dashboards with downloads enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of dashboards with downloads enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of dashboards with downloads disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ },+ "with_title": {+ "description": "Counts of dashboards with title shown or hidden.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of dashboards with title shown.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of dashboards with title hidden.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ }+ }+ },+ "question": {+ "description": "Counts of <metabase-question> component properties.",+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "drills": {+ "description": "Counts of questions with drills enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of questions with drills enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of questions with drills disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ },+ "with_downloads": {+ "description": "Counts of questions with downloads enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of questions with downloads enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of questions with downloads disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ },+ "with_title": {+ "description": "Counts of questions with title shown or hidden.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of questions with title shown.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of questions with title hidden.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ },+ "is_save_enabled": {+ "description": "Counts of questions with save enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of questions with save enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of questions with save disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ }+ }+ },+ "exploration": {+ "description": "Counts of <metabase-question> component with question-id=\"new\" properties.",+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "is_save_enabled": {+ "description": "Counts of explorations with save enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of explorations with save enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of explorations with save disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ }+ }+ },+ "browser": {+ "description": "Counts of <metabase-browser> component properties.",+ "type": [+ "object",+ "null"+ ],+ "properties": {+ "read_only": {+ "description": "Counts of browsers with read-only mode enabled or disabled.",+ "type": "object",+ "properties": {+ "true": {+ "description": "Number of browsers with read-only mode enabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ },+ "false": {+ "description": "Number of browsers with read-only mode disabled.",+ "type": "integer",+ "minimum": 0,+ "maximum": 2147483647+ }+ }+ }+ }+ }+ },+ "required": [+ "event",+ "global"+ ]+}